Compare commits

...
Author SHA1 Message Date
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
JannikStandGitHub 31ff561df6 feat(ci): allow pinning prime-rl image_tag on nightly-fft dispatch (#3132)
* feat(ci): allow pinning prime-rl image_tag on nightly-fft dispatch

Adds an optional image_tag workflow_dispatch input. Empty (default)
keeps the existing auto-resolve behavior (newest v*.dev* with a
published manifest). Non-empty pins the tag directly, after verifying
the manifest is pullable.

* fix(ci): sanitize image_tag input to avoid shell injection

Move the workflow_dispatch input through a step env var so a
malicious value containing $(...) or embedded quotes cannot break
out of shell context during expression substitution. Validate the
result against the OCI/Docker tag charset before curl or GITHUB_OUTPUT
sees it.
2026-07-24 02:53:43 +02:00
JannikStandGitHub dea7707526 fix(nightly-fft): pin hendrycks attn to flash_attention_2 (#3131)
DeepSeek-R1-Distill-Qwen-1.5B is Qwen2 arch, not in prime-rl's
custom-impl support list, so impl='auto' resolves to 'hf'. The
platform default attn='flash_attention_3' requires impl='custom',
which raises ValueError and the trainer crash-loops. Pin attn to
fa2 (works with hf impl on H200).
2026-07-24 02:10:21 +02:00
fca9fb0975 fix(examples): set cp=4 for GLM-4.5-Air advanced examples (#3129)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:50:46 -07:00
JannikStandGitHub 1dcec737d9 ci(nightly-fft): add alphabet-sort, reverse-text, wiki-search, hendrycks-sanity (#3127)
* ci(nightly-fft): add alphabet-sort, reverse-text, wiki-search, hendrycks-sanity, multimodal configs

Broaden nightly-fft coverage beyond wordle. Each config mirrors wordle's
2 train + 6 infer shape and pulls model/taskset/renderer from the
corresponding configs/basic/*/rl.toml.

- multimodal-color-codeword moved from configs/ci/nightly/ (its pytest
  path updated); nightly/ is now empty
- hendrycks-sanity trimmed from 5000 -> 200 steps to fit the nightly
  budget
- wiki-search carries tool_call_parser = 'hermes' for tool use

* ci(nightly-fft): revert multimodal move; restore hendrycks max_steps=5000

* ci(nightly-fft): size deployments per env; add zero-advantage filter to wiki-search

- reverse-text: 1+1 GPUs, batch 128 (was 2+6/512 — overkill for a 0.6B toy loop)
- alphabet-sort: 4+4 GPUs (was 2+6 — 4B FFT needs more trainer memory)
- wiki-search: 4+4 GPUs; adds oversampling_factor=2.0 + zero_advantage
  pre-batch filter mirroring examples/basic/wiki-search — without them sparse
  tool rewards fill batches with all-zero groups and abort the run

* test(nightly): remove LoRA alphabet-sort and wiki-search — covered by FFT nightly workflow

* ci(nightly-fft): align hendrycks-sanity with examples/basic upstream

- drop max_completion_tokens=1024 cap so R1-Distill can produce full CoT
- group_size 16 -> 8, GPUs 2+6 -> 4+4 (upstream)
- add trainer.model.seq_len=16384 for long-context training
- add aime2024 eval block (interval=50, group_size=32)

* fix(nightly-fft): move seq_len under [orchestrator] in hendrycks-sanity

RLConfig rejects setting shared top-level seq_len alongside
trainer.model.seq_len. Mirror examples/basic/hendrycks-sanity/rl.toml:
seq_len=8192 under [orchestrator] for rollout context, seq_len=16384
under [trainer.model] for long-context training.

* revert(nightly): restore test_alphabet_sort and test_wiki_search — keep tests/nightly/ untouched
2026-07-24 01:18:33 +02:00
JannikStandGitHub 43c2905243 ci(nightly-fft): name RFTRun nightly-<config>-<date>-<run_id>; verify GHCR manifest exists before dispatch (#3121) 2026-07-24 00:32:29 +02:00
minh hoangandGitHub 54307fc301 fix(ci): build ghcr image on release via explicit dispatch (#3125)
Releases are published with GITHUB_TOKEN, whose events do not retrigger
workflows, so build_image.yaml's `on: release` trigger never fired and
release commits never received a GHCR image. Dispatch build_image.yaml
explicitly from tag-and-release.yaml after publishing (workflow_dispatch
is exempt from the no-retrigger rule), and drop the now-dead `on: release`
trigger plus its unreachable github.event.release.* references.
2026-07-23 14:27:49 -07:00
JannikStandGitHub 069e580c78 fix(trainer): skip identity HF↔PrimeRL conversion (fixes RO model-cache crash on dense Qwen3) (#3124)
* fix(trainer): skip identity HF↔PrimeRL conversion to avoid RO-cache write

* chore: ruff format

* refactor: drop inline explanation; gate branches on unambiguous snapshot format
2026-07-23 21:11:49 +02:00
samsjaandGitHub 45488ca048 fix(trainer): skip no-op weight conversion for dense models (#3069)
Dense models (Qwen3, Qwen3.5, Llama) use identical key names in both
HF and PrimeRL weight formats, so is_hf_state_dict and is_prime_state_dict
both returned True for the same state dict. The auto-conversion logic in
load_dcp_from_hf would fire anyway, performing a no-op convert and
attempting to save the unchanged weights into the snapshot directory —
which crashes with OSError [Errno 30] Read-only file system when the
model cache is mounted read-only.

Fix: make is_hf_state_dict / is_prime_state_dict mutually exclusive for
dense models by having is_prime_state_dict return False (following the
pattern already used by GPT-OSS). This makes the conversion branches
naturally skip when there is no format difference, without needing
extra guards in load_dcp_from_hf.

MoE models are unaffected: their is_hf_state_dict / is_prime_state_dict
checks are already mutually exclusive (expert.0.w1 vs experts.w1 key
patterns).
2026-07-23 19:08:58 +02:00
JannikStandGitHub 3b5d031028 feat(ci): nightly FFT workflow (#3118)
* feat(ci): add nightly FFT workflow dispatching hosted training runs

* ci(nightly-fft): pin --image-tag to the latest published dev tag

* ci(nightly-fft): rename to reverse-text and align with pytest nightly setup

* ci(nightly-fft): pin deployment shape (2 train + 6 infer)

* ci(nightly-fft): switch to wordle mirroring examples/basic/wordle/rl.toml

* ci(nightly-fft): update wordle config to match examples/basic/wordle

* ci(nightly-fft): add explicit least-privilege permissions block

* ci(nightly-fft): drop top-level type/name — [deployment] alone triggers FFT dispatch

* ci(nightly-fft): resolve image tag from GHCR to avoid unpublished tags

* ci(nightly-fft): forward WANDB_API_KEY and HF_TOKEN into hosted payload via -e
2026-07-23 09:46:44 +02:00
Matej SirovatkaandGitHub 783cff546d fix(nixl): replay strided views on inference (#3113) 2026-07-23 07:32:42 +02:00
acbabc6f0f fix(orchestrator): hold batch ship on the trainer's published version (#3050)
* fix(orchestrator): enforce target lag strictly at ship time

The dispatch gate only stops new rollouts; on tiny fast envs the sink
keeps forming batches from buffered rollouts, so the orchestrator ships
past TARGET_LAG, finishes, and tears down the watcher while the trainer
still has pending NCCL broadcasts. Those broadcasts then block forever
in the STABLE->NCCL_READY handshake (no watcher to trigger the inference
receive) and the launcher never exits.

hold_for_target_lag blocks shipping batch N until the trainer has
published v{N-1-TARGET_LAG}, bounding in-queue staleness and keeping the
orchestrator alive for every broadcast the trainer will make. Under NCCL
the last published version is max_steps-2, exactly what the final batch
requires, so the hold never waits on an unpublishable version.

Also logs a per-batch staleness decomposition (pre-queue = versions
elapsed during generation, in-queue = versions spent waiting in the
sink) under staleness/*.

Fixes RES-1077

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

* remove staleness metrics from ship path

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

* feat(orchestrator): step-based staleness with demand-driven dispatch

Measure a rollout's off-policy lag against the batch that consumes it —
batch N trains on policy v{N-1}, so lag = (N-1) - generation version,
queue time included. The old off_policy_steps counter only counted
weight updates during generation, so a rollout that finished fast but
sat buffered across steps trained arbitrarily stale while reporting 0.

- max_off_policy_steps now bounds consumption lag: in-flight groups are
  cancelled pre-pause (cancel_stale_train_groups) and buffered sink
  survivors are swept whenever the cutoff moves (ship, weight update).
  Groups share one generation version, so stale groups drop whole.
- Dispatch is demand-driven: the orchestrator injects train_demand
  (batch shortfall minus buffered + partial-group + in-transit
  rollouts), re-evaluated per scheduled group, replacing the lead-based
  dispatch gate and the #2990 final-batch NCCL exemption it needed.
  out_q backlog counts as coverage so ship-holds don't over-provision.
- Max Off-Policy in logs is now the honest consumption lag, stamped at
  ship (reverse_text: steady-state max 3 vs a dishonest 0 before).

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

* review pass: bool dispatch contract, oversampling-aware demand, inline single-use helpers

- train_demand -> train_needed: the dispatcher only thresholds the value,
  and the magnitude isn't even unit-stable across batch modes, so the
  injected contract is a bool predicate.
- Demand target is max(batch_size, max_inflight_rollouts): explicit
  over-provisioning (oversampling_factor > 1 or a raised max_inflight)
  keeps racing batch stragglers instead of being silently capped at one
  batch; capacities below the batch keep a batch_size target so the
  batch can still complete.
- Reject max_off_policy_steps=0 with NCCL broadcast + max_steps: the
  final batch necessarily trains one version off-policy (the trainer
  never broadcasts the last versions), so a zero budget would hang the
  run collecting the final batch.
- Inline single-call helpers (hold_for_target_lag, stale_cutoff, the
  dispatcher lag gauges) into their call sites.

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

* require max_off_policy_steps >= 1 at the field

The last NCCL batch necessarily trains one version off-policy (the
trainer never broadcasts the final versions), so a zero budget can never
be met and would hang the run collecting the final batch. A field floor
covers this without a conditional validator.

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

* fix CI regressions: partial-group dispatch deadlock + serialized weight applies

Two regressions surfaced by the PR's GPU CI run:

- alphabet_sort/rl_opd deadlocked at 126/128 (+3 buffered, 0 inflight):
  demand hit zero mid-group, so an open group's remaining rollouts were
  never scheduled — its buffered members count as batch coverage but the
  group can never finalize. Already-open groups now keep scheduling
  regardless of demand (try_schedule allow_fresh); only fresh groups are
  demand-gated.
- reverse_text timed out (~26s/step vs ~19s on main): the ship hold
  waited on the applied version, serializing every inference weight
  reload into the ship path. Filesystem broadcast decouples publish from
  apply and the trainer never blocks on the watcher there, so the hold
  now releases on the published version (tracked in on_version_pending).
  NCCL keeps waiting for the apply — the trainer blocks in the receive
  handshake until then, so releasing on publish could strand its final
  handshake at teardown.

Verified: reverse_text e2e clean on both broadcast types (filesystem
6-7s steps, NCCL exits clean), 485 unit tests pass.

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

* raise multi-run integration timeout to 600s

Resumed orchestrators now pace to the shared trainer — a batch only
ships once the trainer has produced the required policy version — so
with three runs round-robining one trainer, beta_resume's tail (steps
21-25) can legitimately exceed the old 300s wait while its versions
queue behind the other runs. Matches the 600s budget of the other RL
integration tests.

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

* retract stale-dropped rollouts from the payload-size estimate

drop_stale now mirrors what entering pending_batch added to
_payload_total/_payload_count, keeping the token-mode demand estimate
consistent with the buffered set. Also expand the allow_fresh comment
with the group-finalization invariant it protects.

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

* upload integration run logs as artifacts on failure

The multi-run test's failures only surface a sampled tail of one
orchestrator's output; the copied per-run orchestrator/trainer/inference
logs are what's needed to debug them (currently: beta_resume wedging on
a policy version the shared trainer never publishes after resume).

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

* keep CI test outputs for the failure-artifact upload

The output_dir fixture rmtree'd the whole outputs dir at session
teardown, so the upload step found nothing. Skip the cleanup under CI
(the workspace is discarded with the job) and match log files directly
instead of a directory glob.

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

* dispatch lookahead: cover TARGET_LAG extra batches when freshness allows

Exact-one-batch demand synchronized dispatch into one 128-rollout wave
per batch: each ship opened demand 0->128 at once, the wave stampeded
the env server together (MCP timeouts + backoff retries in CI
alphabet_sort), and inference idled ~60s per cycle while the whole wave
sat in env round-trips — tripling the step cadence vs main (artifact
logs: vLLM alternating 30s busy / 60s '0 running, 0 waiting').

With up to TARGET_LAG batches of lookahead — allowed only while a
rollout landing that far ahead still fits max_off_policy_steps —
steady-state dispatch is continuous (each arrival frees demand for the
next start), keeping the engine fed through env-phase gaps. Costs one
version of staleness on the lookahead batch (reverse_text plateau 3->4,
within the default cap of 8).

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

* raise reverse_text mismatch-KL budget to 0.02

Mismatch KL compares generation-time inference logprobs against the
training weights, so it includes async training's policy-version gap on
top of trainer/inference numerics. With strict pacing + dispatch
lookahead the steady-state consumption lag is 2-3 versions (visible and
bounded, vs unmeasured before), which puts the last-steps average at
~0.011-0.012 against the old 0.01 budget calibrated for main's profile.

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

* raise alphabet_sort and multi-run integration budgets

Artifacts from the failed runs show no wedges — every process was
mid-progress at the deadline: alphabet_sort cycles at ~70s on slow vm
runners (33s on fast ones; trainer MFU varies 2-6% across the pool) and
the multi-run trainer was mid-micro-step serving three runs
round-robin. With strict pacing the orchestrators ride the trainer's
pace instead of finishing early on stale buffers, so wall time tracks
the slowest component.

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

* raise multi-run inner milestone waits to 600s

The wait_for_log/wait_for_file 300s defaults were calibrated for
orchestrators that sprint ahead of the shared trainer on buffered
batches; with strict pacing three orchestrators ride the trainer's
actual speed, so every internal milestone (alpha steps, checkpoint
STABLE markers, resume completion) lands slower and a different 300s
wait tripped on each CI round.

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

* count group-scored partial arrivals as batch coverage

buffered_count hides group-scoring envs' partial groups for the
pipeline log's honesty, but demand must count them — otherwise members
sitting between arrival and group completion invite bounded
over-dispatch. Also document why a held batch intentionally does not
count as coverage (dispatch-ahead keeps inference busy through
trainer-bound holds; staleness stays bounded by lookahead + cutoff).

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

* guard token-export STABLE markers against deleted run dirs

The multi-run trainer crashed with FileNotFoundError touching
run_gamma/token_exports/step_20/STABLE: the multi-run integration test
rmtree's a run's dir once its orchestrator finishes, while the trainer
is still flushing that run's tail steps. The broadcast paths already
skip deleted runs on FileNotFoundError; mark_stable now does the same.

This was the root cause of the recurring multi_run CI failure: the
crashed trainer never published the resumed run's next version, so
beta_resume's ship-hold waited forever ('failed with code None'). On
main the same crash risk exists but the orchestrator never waited on
the trainer, so nothing surfaced.

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

* recalibrate multi-run early-step reward floor for strict pacing

Batch N's data now comes from v{N-2}..v{N-4} instead of main's
effectively-fresher buffer profile, so reward-at-step-7 reads 1-2
policy versions staler (observed 0.14-0.20 across four CI rounds vs the
0.2 floor). The final-reward thresholds still enforce learning quality;
the early floor drops to 0.1 — comfortably above a broken run's flat
~0.05-0.08.

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

* raise rl_sft integration budget to 900s

Same class as the other RL integration budgets: the trainer was
SIGTERM'd at step 14 with the orchestrator already finished — killed by
the 600s deadline steps from completion on a slow runner.

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

* lower multi-run final reward floor to 0.6

With strict pacing the reward-vs-step-index curve sits 1-2 policy
versions lower throughout; gamma — the most trainer-contended of the
five runs — landed at 0.627 while its siblings cleared 0.69-0.75. A
broken run still reads ~0.1-0.3.

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

* bound dispatch freshness at DISPATCH_LAG instead of the drop cap

Root cause of the reward-at-step gap vs main: the old lead gate doubled
as the dispatch freshness bound (rollouts only started at version >=
step-2, landing lag <= 2). The demand rewrite left freshness gated only
by max_off_policy_steps (8) plus a deliberately-ahead lookahead batch,
so mean consumption lag ran 2-4 versions vs main's 1-2 — visible as
Max Off-Policy 3-4, mismatch KL ~2x main's, and reward-at-step lower by
1-2 versions of learning.

Dispatch now pauses when new rollouts would train more than
DISPATCH_LAG = TARGET_LAG+1 versions behind their generation policy,
with the lookahead scaled inside that budget — the tightest bound that
still keeps inference busy during ship-holds. Landing lag returns to
<= 2 (spill 3); local e2e: Max Off-Policy plateau 4 -> 3, mismatch KL
mean ~0.012 -> ~0.008. max_off_policy_steps returns to being purely the
drop safety net.

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

* ci: retrigger GPU tests

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

* tolerate trainer tail-flush when deleting run dirs in multi-run test

The fixture's rmtree races the shared trainer's token-export writes,
which mkdir the run dir back mid-deletion (OSError: Directory not
empty). Retry until the flush for the finished run drains.

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

* restore NIXL ModelExpress handshake signals in the version hooks

The merge of #3060 kept this branch's on_version_pending/on_new_version
bodies and dropped main's ModelExpress status updates — the READY
signal the NIXL trainer waits on before each broadcast and the
INITIALIZING reset after it. Post-startup NIXL runs would hang in the
handshake. Both signals are back, ordered as on main (READY pre-update,
INITIALIZING post-update) around this branch's staleness/wake logic.

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

* reduce to the minimal ship-hold fix + staleness docs

Strip the demand-driven dispatch, consumption-lag drop rework, and test
recalibrations accumulated on this branch back to main's behavior, and
keep only what the spec (docs/staleness.md) strictly requires:

- ADVANCE rule: batch N ships only once the trainer has published
  v{N-1-TARGET_LAG}, so the orchestrator cannot finish and tear down the
  weight watcher while the trainer still has in-memory broadcast
  handshakes pending (RES-1077). Main's dispatch gate (START) and
  in-flight drop aging (DIE) are untouched, so generation freshness and
  throughput are unchanged in both pacing regimes — the hold only moves
  where a finished batch waits, never when the trainer consumes it.
- policy.version advances at publish confirmation (inference applies
  immediately and pauses during the update, so published and applied
  are indistinguishable to consumers), and WeightWatcher.stop() drains
  an in-flight apply before cancelling — teardown can never strand the
  trainer mid-handshake.
- Keep the trainer-side token-export guard, the multi-run test's
  deletion-race helper, and the CI failure-artifact pipeline from the
  earlier iterations; drop everything else.

Verified on the original repro (reverse_text, fast env, NCCL): 10/10
batches, clean trainer exit, 2 holds at the buffer-fed tail.

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

* fold staleness spec into docs/training.md

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

* drop the docs section for now, trim the hold comment

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

* never delete the test output dir; clean at run start instead

The output_dir fixture deleted the whole workspace at session teardown,
racing the failure-artifact upload (and hiding logs from post-mortems
generally). Keep it unconditionally and make fresh starts responsible
for their own hygiene: alphabet_sort and reverse_text_moe now pass
--clean-output-dir like the other rl-launcher tests. Resume runs are
unaffected — validate_output_dir returns before cleaning when resuming.
The multi-run orchestrators manage per-run dirs the test creates (and
the standalone orchestrator entrypoint has no clean flag).

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

* stamp true consumption staleness on shipped rollouts

Batch N trains on policy v{N-1}, so a rollout generated from v{k} is
(N-1)-k versions off-policy — queue time included. The dispatcher's
in-flight counter only sees weight updates during generation, which
undercounts by the queue-wait aging and the dispatch-time baseline gap;
the ship-time stamp overwrites it so Max Off-Policy in logs and the
rollout records report the real number. The counter itself (and the
max_off_policy_steps drop rule it feeds) is unchanged.

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

* use the deletion-retry helper for alpha's run dir too

Alpha is SIGTERM'd mid-run, so the trainer is actively flushing its
token-export tail when the dir is deleted — the recreate race is most
likely at exactly this site.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 06:43:48 +02:00
055f62ca32 chore(rl): add message to multimodal packing assert (#3117)
Follow-up to #3103 review feedback: make the mm_kwargs invariant assert self-describing when it fires.

Co-authored-by: eligotts <eligotts@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 06:11:09 +02:00
samsjaandGitHub 1b8c5ef01a fix: sync docs to public-docs on stable release only (#3116)
* fix: sync docs to public-docs on release tags only

Change the Sync Docs to Public Docs workflow to trigger on stable v*
tag pushes instead of every commit to main that touches docs/, so the
public docs only update on releases.

Exclude v*dev* tags so dev pre-release tags never trigger a sync.

Keep workflow_dispatch for manual syncs.

On a tag push github.sha resolves to the tagged commit, so the ref sent
to public-docs remains correct.

Mirrors PrimeIntellect-ai/verifiers#2108.

* fix: trigger docs sync on release published, not on main push

Change the Sync Docs to Public Docs workflow to trigger when a stable
GitHub release is published instead of every commit to main that touches
docs/, so the public docs only update on actual stable releases.

Dev tags (v*dev*) are created via GITHUB_TOKEN which doesn't retrigger
workflows, and they don't have GitHub Releases, so using the release
event with types: [published] naturally excludes them.

Keep workflow_dispatch for manual syncs.

On a release publish, github.sha resolves to the tagged commit, so the
ref sent to public-docs remains correct.
2026-07-23 05:42:45 +02:00
55fc08db46 feat(rl): pack multimodal samples with context parallelism (#3103)
* feat(rl): pack multimodal samples

Multimodal RL samples no longer force one-sample micro-batches: eager
image samples pack with text spans and compatible mm_kwargs samples from
the same run/LoRA, with per-sample boundaries kept in seq_lens. Packing
is always on — VLM training is custom-implementation-only and the custom
Qwen3.5 models advertise supports_packed_multimodal_training; a config
validator requires varlen flash attention for VLM training and
validate_multi_modal_pack fails loudly at startup for models without
packed-MM support.

Ported from #2889 minus its gating (pack_multimodal knob, resolve_pack_multimodal)
and its tokenizer packer params (removed on main since).

(cherry picked from commit 027edc2c510c35ab5666e8f9cbf160f58b1fba48)

* fix: fail loudly when RL micro batches carry multimodal data without [model.vlm]

Mirrors the SFT-side check: transported mm samples would otherwise flow
into forward unvalidated (no packability, attn, or freeze policy checks).

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

* fix(rl): preserve multimodal packing across workers

Keep multimodal bins intact during worker balancing and reject malformed multimodal samples before they can stop shared multi-run packing.
2026-07-22 20:09:45 -07:00
440b3afaa8 fix(trainer): use UE8M0 FP8 scales only on SM100 (#3112)
#3022 flipped use_ue8m0 to True unconditionally to support DeepGEMM on
SM100, which also switched SM90 to power-of-2-rounded scale factors —
a pure precision loss on Hopper. On a GLM-5.2 RL prod run this doubled
trainer/inference mismatch KL (0.0038 -> 0.0059 at step 1, verified
A/B on an identical batch: same tokens and inference logprobs read
0.0059 with UE8M0 and 0.0038 with float scales).

Derive use_ue8m0 from the device (compute capability >= 10) so SM100
keeps the required UE8M0 recipe and SM90 returns to exact float scales.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 23:06:35 +02:00
f5946b098e feat: orchestrator owns v1 tasksets, ships task data to env servers (#3043)
* feat: orchestrator owns v1 tasksets, ships task data to env servers

Companion to PrimeIntellect-ai/verifiers#2039. A v1 env's taskset is loaded once,
in the orchestrator: finite tasksets become the train source's shuffled example
table (real tasks, not index ranges); an infinite taskset's generator is pulled
per example — no server-side materialization, no idx-addressed cache, no
requirement that every pool worker regenerate the same sequence. Each dispatched
rollout ships its task's data (task.data.full_dump()) and the env server
pydantic-validates and runs it.

The legacy (v0) bridge keeps its server-side dataset and task_idx addressing.

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

* chore: bump deps/verifiers to client-side-tasksets tip

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

* chore: bump deps/verifiers to client-side-tasksets tip

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

* chore: bump deps/verifiers to client-side-tasksets tip

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

* chore: plain model_dump task payload; bump deps/verifiers (full_dump removed)

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

* feat: re-land client-side tasksets on the episode wire

Companion to the rebased PrimeIntellect-ai/verifiers#2039. A v1 env's taskset is
loaded once, in the orchestrator: finite tasksets become the train source's
shuffled example table (real tasks, not index ranges); an infinite taskset's
generator is pulled per example. Each dispatched env-rollout ships its task's
data (task.data.model_dump()) and the env server validates and runs it. The
legacy (v0) bridge keeps its server-side dataset, task_idx addressing, and the
run_group route.

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

* chore: bump deps/verifiers (non-optional taskset); drop redundant assert

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

* chore: actually drop the redundant taskset assert

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

* chore: bump deps/verifiers (content-identity resume)

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

* chore: bump deps/verifiers (simplified task_key)

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

* chore: bump deps/verifiers

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

* chore: bump deps/verifiers

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

* chore: bump deps/verifiers to main (client-side tasksets merged, vf#2039)

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

* refactor: one Env.tasks iterator instead of tasks/task_iter

Finite tasksets still materialize at start() (num_tasks needs the count and the
train source shuffles epochs), but the field is a single iterator either way —
consumers pull it uniformly and branch on num_tasks alone. Consumed once, by
TrainSource or EvalEnv.start.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 13:45:15 -07:00
cd00986f71 feat(monitor): add local file monitor (#3111)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 21:59:47 +02:00
208ea64308 chore: bump research-environments submodule to latest main (#3106)
* chore: bump research-environments submodule to latest main

Picks up the registry ref-cleanup wave: platform image naming convention
(openswe/tmax/terminal-lego/openthoughts-tblite/senior-swe-bench switched to
org-less platform refs, multiswe REGISTRY mapping removed) and the tmax Harbor
registry pointer bump.

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

* chore: relock env versions for research-environments bump

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 10:22:17 +02:00
Matej SirovatkaandGitHub c505e07a1a feat(weight-transfer): add NIXL + ModelExpress synchronization (#3060)
* feat(weight-transfer): add NIXL ModelExpress synchronization

* refactor(weight-transfer): simplify NIXL integration

* refactor(weight-transfer): simplify NIXL worker planning

* refactor(weight-transfer): align MX update lifecycle

* feat(inference): pass through online quantization methods

* feat(weight-transfer): add GLM trainer conversion graph

* feat(weight-transfer): stream NIXL updates by layer

* feat(weight-transfer): pipeline NIXL layer reloads

* fix(weight-transfer): preserve single-buffer NIXL behavior

* fix(weight-transfer): reserve observed inference peak

* feat(weight-transfer): preserve model-declared FP32 tensors

* cleanup(weight-transfer): simplify trainer wire schema

* cleanup(weight-transfer): make trainer shard ranges explicit

* cleanup(weight-transfer): resolve model conversions through registry

* cleanup(weight-transfer): clarify lazy copy destinations

* cleanup(weight-transfer): derive lazy metadata from source

* cleanup(weight-transfer): rename weight load tracing

* cleanup(weight-transfer): name recorded tensor operations

* cleanup(weight-transfer): simplify transfer planning

* cleanup(weight-transfer): consolidate load graph

* cleanup(weight-transfer): name trainer tensor table

* cleanup(weight-transfer): clarify tensor routing

* cleanup(weight-transfer): simplify NIXL adapter

* cleanup(weight-transfer): clarify ModelExpress sessions

* cleanup(weight-transfer): clarify CUDA memory sizing

* cleanup(weight-transfer): clarify staged trainer shards

* cleanup(weight-transfer): simplify trainer broadcast guards

* cleanup(weight-transfer): clarify trainer staging state

* cleanup(weight-transfer): simplify trainer constants

* cleanup(weight-transfer): use ModelExpress client name

* cleanup(weight-transfer): clarify trainer shard discovery

* cleanup(weight-transfer): structure trainer initialization

* cleanup(weight-transfer): reuse trainer agent metadata

* cleanup(weight-transfer): reuse trainer table fragments

* cleanup(weight-transfer): simplify trainer staging setup

* cleanup(weight-transfer): simplify inference transfer planning

* cleanup(weight-transfer): split inference plan construction

* cleanup(weight-transfer): clarify inference replay methods

* cleanup(weight-transfer): localize receive arena sizing

* cleanup(weight-transfer): clarify loader recording wrapper

* cleanup(weight-transfer): clarify watcher synchronization

* cleanup(weight-transfer): unify checkpoint wait timing

* cleanup(weight-transfer): align in-memory broadcast lifecycle

* fix(weight-transfer): skip NIXL startup filesystem wait

* cleanup(weight-transfer): use declarative model conversions

* style(weight-transfer): format NIXL implementation

* fix(weight-transfer): stabilize ranks and final watcher step

* fix(tests): use instance conversion API

* cleanup(weight-transfer): scope package to NIXL

* cleanup(weight-transfer): align names and package layout
2026-07-22 02:24:19 +02:00
cb74ae2beb feat: bump verifiers to 0.2.2.dev7, adopt the multi-agent episode wire (#3104)
* feat: bump verifiers to 0.2.2.dev7, adopt the multi-agent episode wire

Companion to PrimeIntellect-ai/verifiers#1939 (multi-agent api). Re-pins
deps/verifiers to 192fd8ef0 (= 0.2.2.dev7) and deps/pydantic-config to
v0.4.2 (verifiers now requires prime-pydantic-config>=0.4.2).

- Serve wire: the env-server route run_rollout -> run, answering one
  Episode envelope ({id, env, ok, errors, traces}) per env-rollout.
  Env.run returns list[Rollout]; an episode that failed before minting
  any trace raises (the dispatcher synthesizes its error marker), and a
  not-ok episode marks its clean traces failed so a broken episode's
  partial seats are never trained on.
- The episode is the pipeline currency: the dispatcher emits one episode
  (list[Rollout]) per completed task onto out_q (a legacy run_group
  result emits its traces as single-trace episodes), and both sinks
  count episodes - never loose traces - toward group_size and eval epoch
  sizes. episode_id is stamped into info so saved records keep grouping.
- ok is the success sentinel: has_error now reads it, so the dispatcher's
  empty-trajectory promotion also flips ok, and error markers carry it.
- Only the trainable subset becomes training samples: a trace stamped
  untrainable (a multi-agent env's frozen agent) is never tokenized,
  never enters the group advantage, and never ships; it still lands in
  the trace files and observation window.
- Config shape: everything env lives under the env block, following the
  new vf.EnvServerConfig (env.taskset, env.agent.harness, per-agent caps
  under env.agent.*). All checked-in TOMLs migrated; the spawned env
  server receives the picklable env block via env_config_data.
- run_group survives only for v0/legacy bridge envs (a v1 server refuses
  it and always reports requires_group_scoring=False); vf's @group_reward
  removal doesn't touch prime-rl's own Algorithm.score_group.

Verified: tests/unit green (487 passed; config-loading params covered all
migrated TOMLs), ruff clean, and a 3-step reverse-text RL run on 2 GPUs
trains at 0% errors with every saved trace carrying ok, agent.name,
agent.trainable, and a distinct info.episode_id.

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

* chore: trim narrative comments to the load-bearing facts

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

* fix: count buffered sink progress in episodes; explicit ok=False on cancel markers

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

* fix: keep untrainable traces out of the effective views and the derived avg@k

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 16:44:20 -07:00
56a6c5fea6 fix(trainer): don't resolve Hub envs when parsing orchestrator configs (#3096)
* fix(trainer): don't resolve Hub envs when parsing orchestrator configs

discover_runs() builds OrchestratorConfig to read training-relevant fields, but
constructing a v1 env config eagerly resolves (imports/installs) its taskset/
harness plugins from the Environments Hub. On the trainer that 404s for private
hub envs (taskset.id = owner/name@version) — the trainer has no Hub credentials —
so get_orchestrator_config() returns None and the run is silently skipped.

Parse under verifiers' skip_plugin_install contextvar so the trainer never
touches the Hub; the env server still installs the plugin at runtime.

Depends on verifiers exposing `skip_plugin_install` — bump deps/verifiers to a
commit that includes it before this lands.

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

* chore(trainer): sort imports to satisfy ruff isort (I001)

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 12:51:32 -07:00
HubertandGitHub d69dbb8da4 feat(cp): context parallelism for hybrid + VLM SFT (#3099)
* feat(cp): context parallelism for hybrid + VLM SFT

Unify model CP setup and make packed-boundary metadata CP-aware:

- setup_model_cp replaces setup_hybrid_cp/setup_nemotron_h_cp: models
  owning linear-attention/Mamba layers expose
  set_context_parallel_attributes (dense + MoE Qwen3.5, NemotronH) and
  wire their own layers; hybrid models without the hook are rejected
  instead of silently misconfigured.
- seq_lens stays global under CP: documents can straddle the shard
  cut, so input_ids/position_ids shard per rank while seq_lens keeps
  the full pre-shard boundaries, flagged via seq_lens_are_global
  through forward() / prime_forward_kwargs into both Qwen3.5 models.
  A cu_seqlens_are_global provenance flag rides along to fla's
  GatedDeltaNet instead of reading cu_seqlens back (which cost one
  CPU-GPU sync per linear-attention layer per microbatch); the CP
  conv path switches to fla's causal_conv1d with a CP context so conv
  state passes between ranks with document-boundary resets.
- VLM CP defers sharding to the model: the vision encoder and the
  image-embed merge see the full sequence, then the root forward
  shards embeds/positions (shard_position_ids_for_cp handles 3D
  MRoPE) and updates ulysses attention params from global seq_lens.
  The SFT trainer skips pre-sharding for MRoPE batches; the vision
  encoder is pinned to SDPA under CP.
- shard_for_cp validates divisibility (uneven shards deadlock ulysses
  all-to-all) and CatDataset's seq_len padding guarantees it; the
  LoRA token count follows the sharded loss_mask.
- Qwen3.5 CP requires the custom implementation (the HF impl has no
  set_context_parallel_attributes); rejected in get_model.
2026-07-20 23:53:42 -07:00
samsjaandGitHub 67ba2ff986 fix(ci): increase GPU integration test timeouts to reduce flakiness (#3100)
The GPU integration tests have been failing intermittently on main since
the verifiers re-pin (d085605b) added per-call tracing overhead. The
root cause is tight timeouts that are now occasionally exceeded:

- reverse_text_multi_run: 300s timeout for waiting on Step 11 with 3
  concurrent orchestrators contending for 2 inference GPUs → 600s
- alphabet_sort: 900s for 10 steps that can each take 2+ min on
  contended runners → 1200s
- reverse_text_rl_opd: 600s despite ~8m orchestrator + cleanup → 900s
- reverse_text & reverse_text_rl_sft: 600s → 900s

All remain within the 60-min workflow timeout.
2026-07-21 08:26:55 +02:00
HubertandGitHub 0af5506215 feat(sft): multimodal (VLM) SFT (#3075)
* feat(sft): multimodal (VLM) SFT

Renderer-produced multimodal samples flow end to end through SFT:

- SFTDataset keeps the renderer's MultiModalData: image-safe truncation
  (never cuts inside a placeholder run, drops truncated-out images, and
  skips samples whose EOS was truncated away), mm_token_type_ids kept
  aligned through EOS append and causal shift, video inputs rejected
  explicitly. _flatten_mm_items folds per-image processor outputs into
  model-forward kwargs (pixel_values, image_grid_thw, ...).
- Cat packing concatenates mm_kwargs across samples in a pack and
  represents text-only spans as zeros in mm_token_type_ids; stack
  bucketing emits multimodal samples solo. Collates move mm tensors to
  CUDA and keep packed rows batch-size 1.
- Local data_files normalization wraps string message content into
  typed content blocks under a multimodal flag so Arrow can unify
  text and image rows.
- setup_processor loads the AutoProcessor and attaches it to the
  renderer; VLM SFT fails fast without one; weight checkpoints save
  the processor alongside the tokenizer.
- Dense Qwen3.5 gains the composite VLM body (HF vision encoder +
  custom text model) with MRoPE positions from mm_token_type_ids and
  registers in _CUSTOM_VLM_MAPPING; VLM training requires a custom
  PrimeRL implementation. Both dense and MoE VLM bodies always run
  the vision encoder (dummy input on text-only microbatches, kept in
  the backward graph) for FSDP/EP collective symmetry.
- Config: VLM SFT requires micro_batch_size=1; unfreezing the vision
  encoder is incompatible with LoRA; the renderer-vs-VLM rejection is
  gone (renderers own multimodal tokenization now).
2026-07-20 20:33:51 -07:00
47f97ee1b0 chore: bump verifiers + research-environments to latest main (#3097)
* chore: bump verifiers to latest main

deps/verifiers ab65b6e8d (v0.2.1) -> 1f457da17 (0.2.2.dev6). uv.lock is
unchanged: verifiers is an editable path dep and its dependency set did
not change, so `uv lock` is a no-op.

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

* chore: bump research-environments to latest main

deps/research-environments 85b1527b9 -> e40d32690 (one commit:
refactor(swe): import patch capture from verifiers, #682), pairing with
the verifiers capture_patch/resolve_head utils pulled in by the previous
commit. uv.lock: swelego-v1 / swerebench-v2-v1 / swesmith-v1 0.1.1 ->
0.1.2.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 02:27:55 +02:00
5264eb8984 fix: dp=1 EP replicas launch dense-style (vLLM rejects external-LB args at dp=1) (#3094)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 00:48:45 +02:00
4453922943 chore: bump verifiers to 0.2.1, prime-pydantic-config to 0.4.2, renderers to 0.1.8 (#3095)
* chore: bump verifiers to 0.2.1, prime-pydantic-config to 0.4.2, renderers to 0.1.8

- deps/verifiers -> v0.2.1 (ab65b6e8d), pin verifiers[harbor]>=0.2.1
- deps/pydantic-config -> v0.4.2 (4f5ae37), pin prime-pydantic-config>=0.4.2
- prime-rl-configs: verifiers>=0.2.1, renderers>=0.1.8 (drop dev pins)

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

* chore: bump research-environments to verifiers 0.2.1 pins

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

* fix: drop use_prime_registry from example configs

research-environments#676 removed the field from the swe/terminal
tasksets (the platform now auto-builds images from any docker ref), so
taskset configs no longer accept it.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 14:46:54 -07:00
ed16f19a05 chore: bump prime to 0.6.19, verifiers pin to latest main (#3093)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 11:20:49 -07:00
185 changed files with 6523 additions and 2703 deletions
+3 -5
View File
@@ -1,8 +1,6 @@
name: Build Image (ghcr)
on:
release:
types: [published]
workflow_dispatch:
inputs:
ref:
@@ -27,12 +25,12 @@ on:
env:
REGISTRY: ghcr.io
IMAGE_NAME: primeintellect-ai/prime-rl
BUILD_REF: ${{ github.event.release.tag_name || inputs.ref || github.ref_name }}
BUILD_TAG: ${{ github.event.release.tag_name || inputs.tag || '' }}
BUILD_REF: ${{ inputs.ref || github.ref_name }}
BUILD_TAG: ${{ inputs.tag || '' }}
BUILD_PLATFORMS: ${{ inputs.platforms || 'both' }}
concurrency:
group: build-image-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
group: build-image-${{ inputs.tag || inputs.ref || github.ref_name }}
cancel-in-progress: false
jobs:
+8
View File
@@ -121,3 +121,11 @@ jobs:
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.test }}-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+197
View File
@@ -0,0 +1,197 @@
name: Nightly FFT
on:
# Allow to manually trigger the workflow
workflow_dispatch:
inputs:
config_file:
description: "Full-FT config to dispatch (e.g. configs/ci/nightly-fft/wordle.toml). Leave empty to run all."
required: false
default: ""
image_tag:
description: "prime-rl image tag to pin (e.g. v0.7.1.dev58). Leave empty to auto-resolve the newest v*.dev* with a published manifest."
required: false
default: ""
# Scheduled run at 3AM PST (11AM UTC)
schedule:
- cron: "0 11 * * *"
permissions:
contents: read
packages: read
jobs:
discover-configs:
name: Discover configs
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.build-matrix.outputs.matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
submodules: false
- name: Build matrix from nightly FFT configs
id: build-matrix
run: |
# Find all nightly full-finetune configs
files=$(ls configs/ci/nightly-fft/*.toml)
# Filter to specific config if provided in workflow_dispatch
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.config_file }}" ]; then
filtered=$(echo "$files" | grep -F "${{ github.event.inputs.config_file }}" || true)
if [ -z "$filtered" ]; then
echo "Error: Config file '${{ github.event.inputs.config_file }}' not found"
exit 1
fi
files="$filtered"
fi
echo "Discovered nightly FFT configs:"
echo "$files"
# Build JSON of the form: { "config_file": ["configs/ci/nightly-fft/foo.toml", ...] }
json=$(printf '%s\n' "$files" | jq -R . | jq -sc '{config_file: .}')
echo "matrix=$json" >> "$GITHUB_OUTPUT"
dispatch-run:
name: Dispatch hosted FFT run
needs: discover-configs
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.discover-configs.outputs.matrix) }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
submodules: false
- name: Resolve prime-rl image tag
id: image
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Pass the dispatch input through env so a malicious value
# cannot break out of shell context via $(...) or embedded
# quotes — the GitHub expression is substituted before Bash
# parses the script.
REQUESTED_IMAGE_TAG: ${{ github.event.inputs.image_tag }}
run: |
# If workflow_dispatch passed an explicit image_tag, validate
# it as a Docker/OCI tag, verify its manifest is pullable,
# and use it as-is (skip resolution).
requested="$REQUESTED_IMAGE_TAG"
if [ -n "$requested" ]; then
# OCI/Docker tag charset: [A-Za-z0-9._-], max 128, no
# leading '.' or '-'. Reject anything else before it
# reaches curl or GITHUB_OUTPUT.
if ! printf '%s' "$requested" | grep -Eq '^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$'; then
echo "Invalid image_tag: only [A-Za-z0-9._-] allowed, max 128 chars, no leading '.' or '-'." >&2
exit 1
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$requested")
if [ "$code" != "200" ]; then
echo "Requested image_tag '$requested' has no published manifest (HTTP $code)." >&2
exit 1
fi
echo "Using pinned prime-rl image tag: $requested"
echo "tag=$requested" >> "$GITHUB_OUTPUT"
exit 0
fi
# 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
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
tag=""
for cand in $candidates; do
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$cand")
if [ "$code" = "200" ]; then
tag="$cand"
break
fi
echo "Skip $cand — manifest HEAD returned $code"
done
if [ -z "$tag" ]; then
echo "None of the top v*.dev* tags have a published manifest." >&2
exit 1
fi
echo "Latest published prime-rl image tag on GHCR: $tag"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install prime CLI (latest)
run: uv tool install prime
- name: Dispatch run
env:
PRIME_API_KEY: ${{ secrets.PRIME_FFT_API_KEY }}
PRIME_TEAM_ID: ${{ secrets.PRIME_FFT_TEAM_ID }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
echo "Dispatching config: ${{ matrix.config_file }}"
echo "Image tag: ${{ steps.image.outputs.tag }}"
# Tag the RFTRun so it's identifiable on the platform as
# coming from this workflow. Injected here rather than in
# the checked-in toml because a top-level `name` field
# breaks tests/unit/test_configs.py::test_load_configs
# (RLConfig has no top-level name).
config_base=$(basename "${{ matrix.config_file }}" .toml)
run_name="nightly-${config_base}-$(date -u +%Y-%m-%d)-${{ github.run_id }}"
dispatch_cfg=$(mktemp --suffix=.toml)
printf 'name = "%s"\n\n' "$run_name" > "$dispatch_cfg"
cat "${{ matrix.config_file }}" >> "$dispatch_cfg"
echo "Dispatched run name: $run_name"
# Forward WANDB_API_KEY / HF_TOKEN into the hosted payload:
# the full-FT dispatch path (`prime train`) only picks up
# secrets that were explicitly collected via `-e` / `--env-file`,
# not ambient env, so the workflow env: block alone is not
# enough to reach the hosted trainer/orchestrator pods.
prime train "$dispatch_cfg" \
--image-tag "${{ steps.image.outputs.tag }}" \
-e WANDB_API_KEY \
-e HF_TOKEN \
--yes --output json
+3 -5
View File
@@ -1,11 +1,9 @@
name: Sync Docs to Public Docs
on:
push:
branches:
- main
paths:
- 'docs/**'
release:
types:
- published
workflow_dispatch:
jobs:
+25
View File
@@ -119,6 +119,8 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
env:
@@ -127,11 +129,22 @@ jobs:
run: |
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
# Publishing runs as GITHUB_TOKEN, whose events don't retrigger
# workflows, so dispatch the image build explicitly.
- name: Trigger image build for the release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
tag-and-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
@@ -195,6 +208,7 @@ jobs:
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Publish draft release
id: publish
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
@@ -207,6 +221,17 @@ jobs:
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; nothing to do."
echo "published=false" >> "$GITHUB_OUTPUT"
exit 0
fi
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
echo "published=true" >> "$GITHUB_OUTPUT"
# Skipped when the release was already published (no rebuild needed).
- name: Trigger image build for the release
if: steps.publish.outputs.published == 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
+1 -1
View File
@@ -106,7 +106,7 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra modelexpress --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
+1 -1
View File
@@ -53,7 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ❌ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
+3 -2
View File
@@ -34,8 +34,9 @@ max_completion_tokens = 768
[[orchestrator.train.env]]
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt] # Checkpoint at the end of training
+3 -2
View File
@@ -21,8 +21,9 @@ seq_len = 8192
[[orchestrator.train.env]]
name = "hendrycks-math"
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.model]
seq_len = 16384
+3 -2
View File
@@ -24,8 +24,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+3 -2
View File
@@ -42,8 +42,9 @@ max_completion_tokens = 512
[[orchestrator.train.env]]
name = "wiki-search"
taskset = { id = "wiki-search-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt] # Checkpoint at the end of training
+3 -2
View File
@@ -23,8 +23,9 @@ group_size = 8
[[orchestrator.train.env]]
name = "wordle"
taskset = { id = "wordle-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 1024
+3 -2
View File
@@ -24,8 +24,9 @@ max_completion_tokens = 384
[[orchestrator.train.env]]
name = "alphabet-sort"
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 } }
harness = { id = "null", runtime = { type = "subprocess" } }
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" }
env.agent.runtime = { type = "subprocess" }
[inference]
@@ -28,8 +28,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
enable_lora = true
@@ -27,8 +27,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
enable_lora = true
@@ -27,8 +27,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
gpu_memory_utilization = 0.7
@@ -16,8 +16,9 @@ max_completion_tokens = 128
[[train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt]
interval = 10
@@ -39,8 +39,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -51,8 +52,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
@@ -45,8 +45,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -57,8 +58,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
@@ -25,8 +25,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
@@ -24,8 +24,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
+33
View File
@@ -0,0 +1,33 @@
max_steps = 200
seq_len = 2048
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "alphabet-sort"
name = "alphabet-sort"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
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" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
@@ -0,0 +1,51 @@
max_steps = 5000
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[ckpt]
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
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" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
group_size = 32
[trainer]
[trainer.model]
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
max_model_len = 8192
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+35
View File
@@ -0,0 +1,35 @@
max_steps = 20
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
project = "reverse-text"
name = "reverse-text"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 128
[trainer]
[inference]
[orchestrator.renderer]
name = "prime-qwen3"
+41
View File
@@ -0,0 +1,41 @@
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "wiki-search"
name = "wiki-search"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
tool_call_parser = "hermes"
+36
View File
@@ -0,0 +1,36 @@
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
project = "wordle"
name = "wordle"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[orchestrator.renderer]
name = "prime-qwen3"
@@ -1,4 +1,4 @@
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
# Based on configs/debug/multimodal.toml but tuned for CI.
max_steps = 25
seq_len = 4096
@@ -7,7 +7,7 @@ num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
name = "Qwen/Qwen3.5-4B"
[model.vlm]
vision_encoder_attr = "model.visual"
@@ -22,12 +22,14 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer]
[trainer.model]
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
+3 -2
View File
@@ -26,8 +26,9 @@ alpha = 0.1
[[orchestrator.train.env]]
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 512
+6 -4
View File
@@ -23,8 +23,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -35,8 +36,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+6 -4
View File
@@ -23,8 +23,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -35,8 +36,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+9 -6
View File
@@ -33,13 +33,15 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text-grpo"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.train.env]]
name = "reverse-text-opd"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.env.algo]
type = "opd"
@@ -57,8 +59,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+6 -4
View File
@@ -35,8 +35,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -47,8 +48,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+6 -4
View File
@@ -35,8 +35,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -47,8 +48,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 1e-4
+53
View File
@@ -0,0 +1,53 @@
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.env]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.env]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+6 -4
View File
@@ -31,8 +31,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -43,8 +44,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+6 -4
View File
@@ -40,8 +40,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -52,8 +53,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+6 -4
View File
@@ -40,8 +40,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -52,8 +53,9 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 1e-4
+1 -1
+6 -10
View File
@@ -28,7 +28,7 @@ impl = "custom" # or "hf" to force the HF path
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ❌ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
@@ -72,20 +72,17 @@ The built-in VLM registry covers:
| Family | `model_type` | Vision attr | LM attr |
|---|---|---|---|
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
| Qwen3-VL MoE | `qwen3_vl_moe` | `model.visual` | `model.language_model` |
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
For a model not in the table, look up the attribute paths on the loaded HF model with `model.named_children()` and set them under `[model.vlm]` directly.
### Enabling VLM Mode
Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
name = "Qwen/Qwen3.5-4B"
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
@@ -97,12 +94,11 @@ language_model_attr = "model.language_model"
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
VLM training requires a registered custom PrimeRL implementation.
### Limitations
- **Vision encoder frozen by default.** Set `freeze_vision_encoder = false` to fine-tune it; in that case it's FSDP-sharded per block. The combination `freeze_vision_encoder = false` + LoRA is rejected by a config validator — LoRA freezes everything non-adapter, so unfreezing the encoder under LoRA would be a silent no-op.
- **No multimodal-safe truncation.** Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` pass through unchanged. If a sample's tokens overflow, image tokens may get dropped while image tensors still describe the full image set. Set `seq_len` to cover your longest sample.
- **Vision encoder frozen by default.** The default LoRA targets do not match Qwen3.5 vision modules. Set `freeze_vision_encoder = false` to fine-tune the encoder; this is incompatible with LoRA because LoRA freezes all non-adapter parameters.
- **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio.
- **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing.
- **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images.
@@ -160,4 +156,4 @@ salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
+30 -3
View File
@@ -17,6 +17,7 @@ This page covers the math and the configurable algorithmic components: the algor
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
@@ -67,6 +68,7 @@ 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). |
| `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. |
@@ -119,13 +121,15 @@ type = "grpo"
[[orchestrator.train.env]]
name = "math"
taskset = { id = "math-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
harness = { id = "null" }
runtime = { type = "subprocess" }
# inherits the top-level grpo
[[orchestrator.train.env]]
name = "terminal"
taskset = { id = "terminal-v1" }
harness = { id = "bash", runtime = { type = "subprocess" } }
harness = { id = "bash" }
runtime = { type = "subprocess" }
algo = { type = "echo" } # this env runs its own algorithm
```
@@ -138,6 +142,7 @@ 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 |
| `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 +179,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`, 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`).
@@ -276,6 +281,7 @@ 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. |
| `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 +303,27 @@ type = "grpo"
type = "linear"
```
### 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.env]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
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
+10 -7
View File
@@ -149,25 +149,28 @@ Training environments are an array of tables — set one per env, optionally wit
```toml
[[orchestrator.train.env]]
name = "gsm8k"
taskset = { id = "gsm8k-v1", split = "train" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
ratio = 3 # 75% of batches
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
ratio = 1 # default — 25% of batches
[[orchestrator.eval.env]]
name = "gsm8k-eval"
taskset = { id = "gsm8k-v1", split = "test" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
Fields in `taskset` configure the V1 taskset. `harness` selects how its tasks are run.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
The same taskset can appear multiple times across train and eval (or with different settings) — useful for evaluating on a held-out split or comparing two configurations side by side. When it is reused, set a distinct `name` on each entry; `name` defaults to the taskset id and must be unique across all envs in the same group.
+13
View File
@@ -14,6 +14,7 @@ This page covers workflows for developing on `prime-rl` itself — running the t
- [Implement the Modeling Code](#implement-the-modeling-code)
- [Register a Mini Preset](#register-a-mini-preset)
- [Run the Smoke Test](#run-the-smoke-test)
- [Adding a Custom VLM Implementation](#adding-a-custom-vlm-implementation)
## Test Suite
@@ -137,3 +138,15 @@ Before merging a new model, you need to ensure the following:
- The small smoke test passes.
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
## Adding a Custom VLM Implementation
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
+11 -7
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,15 +164,15 @@ 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
@@ -177,8 +181,8 @@ 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)
```
- **`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
+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
+7 -5
View File
@@ -59,7 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `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). |
@@ -89,6 +89,7 @@ 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`) |
| `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 |
@@ -156,8 +157,9 @@ enable_thinking = false
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `—` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
@@ -255,7 +257,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/
@@ -267,7 +269,7 @@ 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)
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
@@ -280,7 +282,7 @@ Live tailing from a single point (works on the head node for multi-node runs ove
```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
+16 -13
View File
@@ -46,7 +46,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
@@ -95,12 +95,13 @@ num_turns_weight = 0.0
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.env]]
name = "openseeker"
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"] } }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
[orchestrator.train.env.taskset]
[orchestrator.train.env.env.taskset]
id = "openseeker-v1"
[[orchestrator.train.env.taskset.task.judges]]
[[orchestrator.train.env.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -108,7 +109,7 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.taskset.task.judges]]
# [[orchestrator.train.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
@@ -117,12 +118,13 @@ choices = ["A", "B"]
[[orchestrator.train.env]]
name = "redsearcher"
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"] } }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
[orchestrator.train.env.taskset]
[orchestrator.train.env.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.env.taskset.task.judges]]
[[orchestrator.train.env.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -130,7 +132,7 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.taskset.task.judges]]
# [[orchestrator.train.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
@@ -145,15 +147,16 @@ interval = 20
[[orchestrator.eval.env]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
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"] } }
timeout = { rollout = 3600 }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.taskset]
[orchestrator.eval.env.env.taskset]
id = "browsecomp-v1"
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.taskset.task.judges]]
# [[orchestrator.eval.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
+9 -7
View File
@@ -7,7 +7,7 @@
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
# 2 train + 4 infer nodes. Trainer uses cp=4 (ulysses) plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
# CPU offload, and skip-gather / skip-optimizer checkpointing.
@@ -57,7 +57,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
@@ -99,8 +99,9 @@ thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1", use_prime_registry = true }
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
[orchestrator.prime_monitor]
@@ -111,9 +112,10 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
timeout = { rollout = 3600 }
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
env.agent.timeout = { rollout = 3600 }
# --- Inference ---
+18 -16
View File
@@ -47,7 +47,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
@@ -93,20 +93,21 @@ num_turns_weight = 0.1
[[orchestrator.train.env]]
name = "tmax"
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
[orchestrator.train.env.taskset]
[orchestrator.train.env.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.taskset.judges]]
# [[orchestrator.train.env.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.taskset.judges]]
# [[orchestrator.train.env.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
@@ -120,21 +121,21 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
timeout = { rollout = 3600 }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.taskset]
[orchestrator.eval.env.env.taskset]
id = "swebench-verified-v1"
use_prime_registry = true
# [[orchestrator.eval.env.taskset.judges]]
# [[orchestrator.eval.env.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.taskset.judges]]
# [[orchestrator.eval.env.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
@@ -144,20 +145,21 @@ use_prime_registry = true
[[orchestrator.eval.env]]
name = "terminal-bench-2"
group_size = 4 # avg@4
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
timeout = { rollout = 3600 }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.taskset]
[orchestrator.eval.env.env.taskset]
id = "terminal-bench-2-v1"
# [[orchestrator.eval.env.taskset.judges]]
# [[orchestrator.eval.env.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.taskset.judges]]
# [[orchestrator.eval.env.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
+1 -1
View File
@@ -38,7 +38,7 @@ 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]
[router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 }
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
+4 -3
View File
@@ -37,7 +37,7 @@ decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.router]
[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
@@ -98,8 +98,9 @@ extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.env]]
name = "r2e"
taskset = { id = "r2e-gym-v1" }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "rlm" }
env.agent.runtime = { type = "prime", labels = ["glm5-llmd"] }
[inference]
enable_expert_parallel = true
+3 -2
View File
@@ -73,8 +73,9 @@ interval = 20
[[orchestrator.eval.env]]
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "bash", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] }
[[orchestrator.post_batch_filters]]
type = "gibberish"
+21 -14
View File
@@ -50,32 +50,37 @@ oversampling_factor = 2
[[orchestrator.train.env]]
name = "swe"
ratio = 0.3
taskset = { id = "r2e-gym-v1" }
harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe"] }
[[orchestrator.train.env]]
name = "deepdive"
ratio = 0.2
taskset = { id = "deepdive-v1" }
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
env.taskset = { id = "deepdive-v1" }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"] }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] }
[[orchestrator.train.env]]
name = "math"
ratio = 0.3
taskset = { id = "i3_math_v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.train.env]]
name = "logic"
ratio = 0.2
taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.train.env]]
name = "code"
ratio = 0.2
taskset = { id = "i3_code_v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "i3_code_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
@@ -86,13 +91,15 @@ interval = 25
[[orchestrator.eval.env]]
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] }
[[orchestrator.eval.env]]
name = "aime2025"
taskset = { id = "aime25-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference.parallel]
tp = 8
+6 -4
View File
@@ -51,16 +51,18 @@ max_off_policy_steps = 16
[[orchestrator.train.env]]
name = "swe"
taskset = { id = "r2e-gym-v1" }
harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe"] }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] }
[inference.parallel]
tp = 8
+7 -5
View File
@@ -83,8 +83,9 @@ truncate_history_thinking = false
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1", use_prime_registry = true }
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
[orchestrator.prime_monitor]
@@ -93,9 +94,10 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
timeout = { rollout = 3600 }
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
env.agent.timeout = { rollout = 3600 }
[inference]
enable_expert_parallel = true
+7 -5
View File
@@ -50,16 +50,18 @@ max_completion_tokens = 32768
[[orchestrator.train.env]]
name = "math"
taskset = { id = "i3_math_v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
name = "aime2025"
taskset = { id = "aime25-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference.parallel]
tp = 8
tp = 8
+7 -5
View File
@@ -48,16 +48,18 @@ max_off_policy_steps = 16
[[orchestrator.train.env]]
name = "swe"
taskset = { id = "r2e-gym-v1" }
harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] }
[inference.parallel]
tp = 8
tp = 8
+3 -2
View File
@@ -36,8 +36,9 @@ group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.env]]
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
harness = { id = "null", runtime = { type = "modal" } }
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "modal" }
[inference]
gpu_memory_utilization = 0.85
+3 -2
View File
@@ -33,7 +33,8 @@ max_completion_tokens = 768
[[orchestrator.train.env]]
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference] # Default inference config
+6 -4
View File
@@ -18,16 +18,18 @@ seq_len = 8192
[[orchestrator.train.env]]
name = "hendrycks-math"
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
name = "aime2024"
taskset = { id = "aime24-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
group_size = 32
[trainer.model]
+3 -2
View File
@@ -17,8 +17,9 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+2 -1
View File
@@ -136,7 +136,8 @@ The V1 taskset fixes the question bank and searchable corpus. You can replace it
[[orchestrator.train.env]]
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
+3 -2
View File
@@ -46,8 +46,9 @@ enforce = true
[[orchestrator.train.env]]
name = "wiki-search"
taskset = { id = "wiki-search-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt] # Checkpoint at the end of training
+3 -2
View File
@@ -20,8 +20,9 @@ group_size = 16
[[orchestrator.train.env]]
name = "wordle"
taskset = { id = "wordle-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 1024
+35
View File
@@ -0,0 +1,35 @@
max_steps = 20
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "Qwen/Qwen3.5-0.8B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
[renderer]
name = "auto"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
freeze_vision_encoder = true
[model.lora]
rank = 16
[model.ac]
freq = 1
[data]
type = "sft"
name = "your-org/your-multimodal-dataset"
batch_size = 1
micro_batch_size = 1
seq_len = 16384
[optim]
lr = 1e-5
+55
View File
@@ -0,0 +1,55 @@
# Multimodal (VLM) SFT on a Mixture-of-Experts model — single 8xH200 node.
max_steps = 1000
dist_timeout_seconds = 3600
[model]
name = "Qwen/Qwen3.6-35B-A3B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
attn = "flash_attention_2"
ep = 8 # keep in sync with deployment.num_gpus
[renderer]
name = "auto"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
freeze_vision_encoder = true
[model.lora]
rank = 32
alpha = 32
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"]
# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing
# raises CheckpointError; selective AC excluding routed_experts avoids that.
[model.ac]
mode = "selective"
targets = ["norm", "attn_proj", "linear_attn"]
[data]
type = "sft"
name = "your-org/your-multimodal-dataset"
batch_size = 8
micro_batch_size = 1 # required for VLM SFT
seq_len = 16384
[data.loss_mask]
system = false
user = false
assistant = true
tool = false
[optim]
lr = 1e-5
[ckpt]
interval = 200
[ckpt.weights]
save_adapter_separately = true
[deployment]
type = "single_node"
num_gpus = 8
+3 -3
View File
@@ -6,11 +6,11 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.3.0.dev82",
"renderers>=0.1.8.dev28",
"prime-pydantic-config>=0.4.2",
"renderers>=0.1.8",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.0",
"verifiers>=0.2.1",
]
[build-system]
@@ -232,6 +232,27 @@ 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 OPDAlgoConfig(BaseAlgoConfig):
type: Literal["opd"] = "opd"
"""On-policy distillation: the per-token signal is the reverse KL to
@@ -305,7 +326,7 @@ class SFTAlgoConfig(BaseAlgoConfig):
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | RAEAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
@@ -314,6 +335,7 @@ 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.
- ``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``.
@@ -82,7 +82,7 @@ class ModelConfig(BaseModelConfig):
class WeightBroadcastConfig(BaseConfig):
type: Literal["nccl", "filesystem"] = "filesystem"
type: Literal["nccl", "filesystem", "nixl"] = "filesystem"
"""Weight broadcast transport."""
@@ -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()
@@ -366,7 +360,7 @@ class InferenceConfig(BaseConfig):
gpu_memory_utilization: float = 0.9
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
quantization: Literal["mxfp8", "fp8_per_block"] | None = None
quantization: str | None = None
"""Online inference quantization method. Forwarded as ``--quantization``."""
api_server_count: int = Field(1, ge=0)
@@ -435,29 +429,10 @@ class InferenceConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
return self
@model_validator(mode="after")
def validate_mxfp8_requires_sm100(self):
"""Reject MXFP8 when validation runs on a non-SM100 CUDA host."""
if self.quantization != "mxfp8":
return self
try:
import torch
except ModuleNotFoundError as exc:
raise ValueError("inference.quantization='mxfp8' requires torch to validate SM100 support.") from exc
if torch.cuda.is_available():
capability = torch.cuda.get_device_capability()
if capability != (10, 0):
detected = f"SM{capability[0]}{capability[1]}"
raise ValueError(f"inference.quantization='mxfp8' requires SM100, detected {detected}.")
return self
@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. "
@@ -465,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:
@@ -14,12 +14,13 @@ from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
EnvVars,
FileSystemTransportConfig,
FileMonitorConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
TransportConfig,
WandbWithExtrasConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
@@ -172,24 +173,16 @@ class EnvConfig(vf.EnvServerConfig):
data["pool"] = {"type": "static", "num_workers": num_workers}
return data
@property
def is_legacy(self) -> bool:
"""A v0/legacy env (run via the bridge): an ``id`` is set and no v1 ``taskset`` is."""
return not self.taskset.id
@property
def env_id(self) -> str:
"""The env identifier — the v1 taskset id (v1) or the legacy env id (v0)."""
return self.taskset.id or self.id or ""
@property
def resolved_name(self) -> str:
return self.name or self.env_id
@model_validator(mode="after")
def validate_env(self):
if not self.taskset.id and not self.id:
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or id = "<id>" (v0/legacy)'
)
if self.resolved_name == "agg":
raise ValueError(
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
@@ -200,13 +193,16 @@ class EnvConfig(vf.EnvServerConfig):
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. (``max_seq_len`` is added per train run in
``OrchestratorConfig.resolve_env_config``, which knows ``seq_len``.)"""
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:
if self.timeout.rollout is not None:
self.extra_env_kwargs["timeout_seconds"] = self.timeout.rollout
if self.max_output_tokens is not None:
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_output_tokens
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
if agent.max_output_tokens is not None:
self.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
return self
@@ -397,27 +393,43 @@ class FileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
class NCCLWeightBroadcastConfig(BaseConfig):
type: Literal["nccl"] = "nccl"
class InMemoryWeightBroadcastConfig(BaseConfig):
host: str = "localhost"
"""Host for the NCCL broadcast rendezvous."""
"""Weight transfer host."""
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Weight transfer timeout in seconds."""
inference_world_size: int = Field(1, ge=1)
"""Total inference workers across all servers."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
timeout: int = 1200
"""Timeout in seconds for the NCCL broadcast."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
inference_world_size: int = Field(1, ge=1)
"""Total inference GPUs across all servers. Used by ``init_nccl_broadcast`` to compute per-server rank offsets."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
@@ -482,6 +494,9 @@ class OrchestratorConfig(BaseConfig):
prime_monitor: PrimeMonitorConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, orchestrator metrics are appended to ``<output_dir>/metrics.jsonl``."""
collect_inference_metrics: bool = True
"""Collect inference-server metrics (requires wandb)."""
@@ -494,7 +509,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")
@@ -12,12 +12,17 @@ from prime_rl.configs.orchestrator import (
from prime_rl.configs.orchestrator import (
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NIXLWeightBroadcastConfig as OrchestratorNIXLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
SlurmConfig,
TransportConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
@@ -32,6 +37,9 @@ from prime_rl.configs.trainer import (
from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
@@ -110,20 +118,47 @@ class SharedModelConfig(BaseConfig):
"""VLM configuration. Set this to enable vision-language model support."""
class SharedWeightBroadcastConfig(BaseConfig):
type: Literal["nccl", "filesystem"] = "nccl"
"""Weight broadcast transport."""
class SharedInMemoryWeightBroadcastConfig(BaseConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Timeout in seconds for in-memory weight transfer."""
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for NCCL weight broadcast."""
timeout: int = 1200
"""Timeout in seconds for NCCL weight broadcast."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
SharedWeightBroadcastConfig: TypeAlias = Annotated[
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
class BaseDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
@@ -209,6 +244,9 @@ class RLConfig(BaseConfig):
wandb: SharedWandbConfig | None = None
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
file_monitor: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator. If None, falls back to the sub-config settings."""
model: SharedModelConfig | None = None
"""Shared model config. If None, falls back to the sub-config model settings."""
@@ -223,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``."""
@@ -295,11 +335,11 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def validate_quantize_in_weight_transfer(self):
if self.weight_broadcast is None or not self.weight_broadcast.quantize_in_weight_transfer:
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
return self
if self.weight_broadcast.type != "nccl":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires weight_broadcast.type = 'nccl'.")
if not self.weight_broadcast.quantize_in_weight_transfer:
return self
if self.inference is None:
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
@@ -339,38 +379,39 @@ class RLConfig(BaseConfig):
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference.
Defaults to NCCL broadcast when no ``weight_broadcast`` is configured. Falls back to
filesystem when LoRA is enabled (not yet supported with NCCL) or when no inference
server is configured (NCCL requires a running inference pool).
filesystem when LoRA is enabled (not yet supported by in-memory transfer) or when no
inference server is configured.
"""
if self.weight_broadcast is None:
if self.trainer.model.lora is not None or self.inference is None:
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
self.weight_broadcast = SharedFileSystemWeightBroadcastConfig()
else:
self.weight_broadcast = SharedWeightBroadcastConfig()
if self.weight_broadcast.type == "nccl" and self.trainer.model.lora is not None:
# LoRA adapters are transferred via the filesystem (loaded from disk by the inference
# servers); NCCL broadcast only writes a STABLE marker, so LoRA over NCCL cannot transfer
# an adapter and would hang/fail on the startup weight sync.
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
raise ValueError(
"LoRA training is not yet supported with NCCL weight broadcast. "
"LoRA training is not yet supported with in-memory weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
)
if self.weight_broadcast.type == "nccl":
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
common_config = dict(
host=self.weight_broadcast.host,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
if self.weight_broadcast.type == "nccl":
transport_config = dict(
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
transport_config = dict(session_id=self.weight_broadcast.session_id)
trainer_config_type = TrainerNIXLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
@@ -381,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:
@@ -417,9 +480,6 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
@@ -494,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 "
@@ -504,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 (
@@ -548,7 +614,7 @@ class RLConfig(BaseConfig):
)
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
# Ensure api_server_count matches DP so all workers are created.
# Without this, the NCCL broadcast group expects dp*tp workers
# Without this, in-memory weight transfer expects dp*tp workers
# but only api_server_count*tp exist, causing a deadlock.
dp = self.inference.parallel.dp
if self.inference.api_server_count < dp and not self.inference.enable_lora:
@@ -602,7 +668,7 @@ class RLConfig(BaseConfig):
# Auto-infer DP and api_server_count for standard multi-node inference.
# Without EP, vLLM only creates api_server_count * tp workers per node,
# not gpus_per_node workers. If DP isn't set, the broadcast group expects
# more workers than exist, deadlocking NCCL init.
# more workers than exist, deadlocking in-memory transfer initialization.
if (
self.inference is not None
and not self.inference.enable_expert_parallel
@@ -616,19 +682,20 @@ class RLConfig(BaseConfig):
if self.inference.api_server_count == 1 and dp_per_node > 1:
self.inference.api_server_count = dp_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
# Every allocated inference GPU is a NCCL rank in the weight broadcast.
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
# Every allocated inference GPU is an in-memory transfer worker.
# The external-LB launcher starts dp_per_node (= gpus_per_node / tp)
# TP-sharded servers per node, i.e. gpus_per_node workers per node, so use
# the GPU count directly. Deriving it from api_server_count double-counts:
# api_server_count can resolve to the *global* DP size, making the node
# factor count twice and NCCL wait for ranks that never connect. Matches
# factor count twice and wait for ranks that never connect. Matches
# the disaggregated path below.
total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
assert self.trainer.weight_broadcast.type in ("nccl", "nixl")
if self.trainer.weight_broadcast.type == "nccl":
self.trainer.weight_broadcast.host = "0.0.0.0"
self.trainer.weight_broadcast.inference_world_size = total_infer_workers
assert self.orchestrator.weight_broadcast.type == "nccl"
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl")
self.orchestrator.weight_broadcast.inference_world_size = total_infer_workers
return self
@@ -659,10 +726,10 @@ class RLConfig(BaseConfig):
infer_deploy.num_decode_nodes * stride
)
self.orchestrator.inference_metrics_roles = role_order * self.deployment.num_infer_replicas
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
assert self.trainer.weight_broadcast.type in ("nccl", "nixl")
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
assert self.orchestrator.weight_broadcast.type == "nccl"
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl")
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
return self
@@ -671,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")
@@ -8,6 +8,7 @@ from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
HeartbeatConfig,
SlurmConfig,
TrainerLogConfig,
@@ -191,6 +192,9 @@ class SFTConfig(BaseConfig):
wandb: WandbConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
@@ -301,6 +305,29 @@ class SFTConfig(BaseConfig):
raise ValueError("Validation micro batch size must be 1 when CP is enabled")
return self
@model_validator(mode="after")
def vlm_freeze_incompatible_with_lora(self):
if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None:
raise ValueError(
"freeze_vision_encoder=false is incompatible with LoRA. "
"LoRA freezes all non-adapter parameters including the vision encoder."
)
return self
@model_validator(mode="after")
def validate_vlm_constraints(self):
if self.model.vlm is None:
return self
if self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16":
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
if self.data.micro_batch_size != 1:
raise ValueError("VLM SFT requires data.micro_batch_size = 1.")
if self.val is not None and self.val.data.micro_batch_size != 1:
raise ValueError("VLM SFT requires val.data.micro_batch_size = 1.")
return self
@model_validator(mode="after")
def dont_do_massive_traces(self):
if self.trace_path:
@@ -312,15 +339,6 @@ class SFTConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
if self.model.vlm is not None:
raise ValueError(
"renderer-only SFT does not support VLMs yet. The renderer tokenizes "
"text-only message dicts client-side and cannot handle image inputs."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
@@ -94,7 +94,7 @@ class VLMConfig(BaseConfig):
"""Dotted attribute path to the language model module (e.g. ``model.language_model``)."""
freeze_vision_encoder: bool = True
"""Freeze the vision encoder. When False, it is trainable and FSDP-sharded per-block. No effect with LoRA (LoRA freezes all non-adapter parameters)."""
"""Freeze the vision encoder parameters during training."""
class BaseModelConfig(BaseConfig):
@@ -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."""
@@ -221,6 +218,18 @@ class WandbWithExtrasConfig(WandbConfig):
"""Extras logging configuration. If None, no extras are logged."""
class FileMonitorConfig(BaseConfig):
"""Enable the local JSONL metric sink (``<output_dir>/metrics.jsonl``).
Present (non-None) enables it, mirroring the ``prime_monitor`` pattern. Metrics
are the same scalars sent to W&B; useful for self-hosted dashboards or when W&B
is disabled.
"""
filename: str = "metrics.jsonl"
"""Name of the JSONL file written under the component's ``output_dir``."""
class PrimeMonitorConfig(BaseConfig):
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
"""Base URL for the Prime Intellect monitoring API."""
@@ -7,12 +7,13 @@ from pydantic import Field, model_validator
from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileSystemTransportConfig,
FileMonitorConfig,
HeartbeatConfig,
MetricsServerConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
@@ -236,21 +237,25 @@ class ModelConfig(BaseModelConfig):
return self
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
def vlm_only_with_custom_impl(self):
if self.vlm is not None and self.impl != "custom":
raise ValueError("VLM training requires model.impl='custom'")
return self
@model_validator(mode="after")
def vlm_cp_requires_ulysses(self):
if self.vlm is not None and self.cp > 1 and self.cp_style != "ulysses":
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
return self
@model_validator(mode="after")
def validate_cp(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
if (
self.cp > 1
and self.attn in ("flash_attention_3", "flash_attention_4", "auto")
and self.impl not in ("custom", "auto")
):
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
# `_flash_attention_forward` which only wraps FA2.
if self.cp > 1 and self.impl not in ("custom", "auto"):
raise ValueError(
f"CP with {self.attn} requires model.impl='custom' or 'auto' "
"(FA3/FA4 paths are only implemented for the custom model attention class)"
"Context parallelism requires model.impl='custom' or 'auto' "
"(resolved to a custom PrimeRL implementation)"
)
return self
@@ -516,28 +521,44 @@ class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
"""Weight checkpoint serialization format."""
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Host for the NCCL broadcast rendezvous."""
"""Weight transfer host."""
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Timeout in seconds for the NCCL broadcast."""
"""Weight transfer timeout in seconds."""
# TODO: Should not be configurable, but auto-inferred
inference_world_size: int = 1
"""Number of GPUs used for inference."""
"""Number of inference workers."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
@@ -561,13 +582,16 @@ 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()
wandb: WandbConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, trainer metrics are appended to ``<output_dir>/metrics.jsonl``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
@@ -686,9 +710,8 @@ class TrainerConfig(BaseConfig):
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
# TODO: Support NCCL broadcast with LoRA
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
raise ValueError("In-memory weight broadcast does not support LoRA yet.")
return self
@model_validator(mode="after")
@@ -106,6 +106,9 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
# differ between sub-configs (auto-derived from model names, which may
@@ -123,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")
@@ -172,7 +178,7 @@ def propagate_shared_fields(data: Any) -> Any:
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
# parent-class validator converts it, which happens after this one.
for key in ("ckpt", "wandb"):
for key in ("ckpt", "wandb", "file_monitor"):
if isinstance(get(key), dict):
fill(f"trainer.{key}", {})
fill(f"orchestrator.{key}", {})
+3 -5
View File
@@ -23,7 +23,7 @@ dependencies = [
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"ring-flash-attn>=0.1.8",
"prime>=0.6.4",
"prime>=0.6.19",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.0",
"verifiers[harbor]>=0.2.1",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -44,6 +44,7 @@ dependencies = [
"pandas>=2.0",
"msgspec>=0.18",
"torchao>=0.17.0",
"modelexpress==0.3.0",
]
[project.scripts]
@@ -76,9 +77,6 @@ disagg = [
gpt-oss = [
"kernels",
]
modelexpress = [
"modelexpress==0.3.0",
]
quack = [
"quack-kernels>=0.4.1",
]
+1 -1
View File
@@ -61,7 +61,7 @@ if [ -n "$PRIME_RL_REF" ]; then
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra gpt-oss --extra modelexpress \
--extra gpt-oss \
--group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
+3 -4
View File
@@ -297,12 +297,11 @@ def verify(arch: str, model_dir: Path) -> None:
# Roundtrip weight conversion: HF -> PrimeRL -> HF
# Normalize both through the same roundtrip to handle expert format differences
prime_cls = preset["prime_model_class"]
with torch.no_grad():
roundtrip_sd = prime_cls.convert_to_hf(dict(prime_model.state_dict()))
roundtrip_sd = prime_model.convert_to_hf(dict(prime_model.state_dict()))
orig_sd = dict(hf_model.state_dict())
prime_cls.convert_to_prime(orig_sd)
prime_cls.convert_to_hf(orig_sd)
prime_model.convert_to_prime(orig_sd)
prime_model.convert_to_hf(orig_sd)
for key in orig_sd:
assert key in roundtrip_sd, f"Missing key after roundtrip: {key}"
+5 -4
View File
@@ -43,17 +43,18 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
```toml
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
```
CLI: `--orchestrator.train.env.0.taskset.id reverse-text-v1`.
CLI: `--orchestrator.train.env.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" | "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`.
**`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
+14 -11
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
```
@@ -126,7 +126,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)
```
@@ -137,21 +137,24 @@ curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
```
JSONL files of `vf.Trace` records (training tensors excluded). `all` gets every completed
rollout the moment it arrives — errored, filtered, and never-batched ones included — so it's
crash-durable; `effective` gets the clean subset that went into the step's train batch (eval:
the non-errored epoch cohort; multiple eval envs share the step file). Each record carries
`run` (`{type, id, step}`; for eval, `step` is the trigger step), `verifiers` (producing build),
`agent` (model, sampling, harness), and `runtime` (config + provisioned resource id, e.g. the
sandbox id), plus `env_name`, `group_id`, and `policy_version` under `info`.
JSONL files of `vf.Trace` records (training tensors excluded), one line per trace — a
multi-agent env's episode contributes several lines sharing one `info.episode_id`. `all`
gets every completed rollout the moment it arrives — errored, filtered, and never-batched
ones included — so it's crash-durable; `effective` gets the clean trainable subset that went
into the step's train batch (eval: the non-errored trainable epoch cohort; multiple eval envs
share the step file) — untrainable traces (a frozen judge's) appear only in `all`. Each record carries `run` (`{type, id, step}`; for eval, `step` is the trigger step),
`verifiers` (producing build), `agent` (model, sampling, harness, `name`, `trainable`), `ok`
(the success sentinel — `errors` alone keeps retry history even after a recovery), and
`runtime` (config + provisioned resource id, e.g. the sandbox id), plus `env_name`,
`group_id`, `episode_id`, and `policy_version` under `info`.
```bash
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.errors != []) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/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
+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
+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):
+12 -4
View File
@@ -73,8 +73,12 @@ 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)
def rl_local(config: RLConfig):
@@ -414,7 +418,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,6 +435,7 @@ 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,
)
@@ -445,15 +451,17 @@ 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,
+3 -1
View File
@@ -68,6 +68,7 @@ def models(request: Request) -> OpenAIServingModels:
WORKER_EXTENSION_CLS = {
"nccl": "prime_rl.inference.vllm.worker.nccl.NCCLWeightUpdateWorker",
"filesystem": "prime_rl.inference.vllm.worker.filesystem.FileSystemWeightUpdateWorker",
"nixl": "prime_rl.inference.vllm.worker.nixl.NIXLWeightUpdateWorker",
}
@@ -143,9 +144,10 @@ async def init_broadcaster(request: Request):
rank_offset = data.get("rank_offset")
inference_world_size = data.get("inference_world_size")
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
session_id = data.get("session_id", "default")
await engine_client(request).collective_rpc(
"init_broadcaster",
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer, session_id),
)
return {"status": "ok"}
@@ -100,6 +100,7 @@ class NCCLWeightUpdateWorker(Worker):
inference_world_size: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
session_id: str = "default",
) -> None:
"""Initialize the NCCL broadcast receiver.
@@ -107,6 +108,7 @@ class NCCLWeightUpdateWorker(Worker):
rank_offset: Starting GPU offset for this server in the global inference group.
inference_world_size: Total number of inference GPUs across all servers.
"""
del session_id
self.quantize_in_weight_transfer = quantize_in_weight_transfer
# Use the worker's device index directly as the local rank.
# The previous dp_group-based computation broke in vLLM v1 multiprocess
+648
View File
@@ -0,0 +1,648 @@
"""vLLM worker extension for composed, sharded NIXL weight pulls."""
from __future__ import annotations
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from functools import wraps
from math import prod
from threading import Event
from typing import TYPE_CHECKING, Any, cast
import torch
import torch.nn as nn
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
from prime_rl.trainer.rl.broadcast.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.trainer.rl.broadcast.nixl.cuda_malloc_memory import (
size_cuda_buffers,
use_cuda_malloc_pool,
)
from prime_rl.trainer.rl.broadcast.nixl.graph import (
Destination,
OperationChain,
RecordedCopy,
TensorReplayPlan,
WeightLoadRecorder,
apply_chain,
make_hf_lazy_weights,
plan_tensor_replay,
)
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.trainer.rl.broadcast.nixl.tensor_routing import route_sharded_tensor
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensorTable
if TYPE_CHECKING:
from vllm.v1.worker.gpu_worker import Worker
else:
Worker = object
logger = init_logger("vllm.inference.vllm.worker_nixl")
_BUFFER_POLL_INTERVAL = 0.01
@dataclass
class TensorCopyPlan:
recorded_copy: RecordedCopy
staging_tensor: torch.Tensor
replay_ops: OperationChain
@dataclass
class LayerWeightTransferPlan:
reload_layer: nn.Module | None
copies: list[TensorCopyPlan]
persistent_copies: list[TensorCopyPlan]
@property
def destination_names(self) -> set[str]:
return {plan.recorded_copy.destination_name for plan in self.copies}
@dataclass
class WeightTransferGroup:
name: str
layers: list[LayerWeightTransferPlan]
pulls: list[tuple[Any, Any, list[int]]]
@dataclass
class WeightTransferPlan:
receive_arenas: dict[torch.dtype, torch.Tensor]
receive_buffer_count: int
groups: list[WeightTransferGroup]
class NIXLWeightUpdateWorker(Worker):
@property
def raw_model(self) -> nn.Module:
return cast(nn.Module, self.model_runner.get_model())
def liveness_probe(self) -> None:
return None
def init_broadcaster(
self,
host: str,
port: int,
rank_offset: int,
inference_world_size: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
session_id: str = "default",
) -> None:
del inference_world_size, quantize_in_weight_transfer
global_rank = rank_offset + self.device.index
server_url = f"{host}:{port}"
set_ucx_env_defaults()
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
self.model_express = ModelExpressSession(
client=MxClient(server_url=server_url),
role="inference",
rank=global_rank,
session_id=session_id,
worker_id=f"inference-{global_rank}",
)
self.weight_transfer_timeout = timeout
self.weight_transfer_plan: WeightTransferPlan | None = None
logger.info(
"NIXL worker configured: global_rank=%d, ModelExpress=%s, session=%s",
global_rank,
server_url,
session_id,
)
@torch.no_grad()
def initialize_transfer(self) -> WeightTransferPlan:
if self.weight_transfer_plan is not None:
return self.weight_transfer_plan
trainer_ref = self.model_express.wait_for(
"trainer",
count=1,
status=None,
timeout=self.weight_transfer_timeout,
)[0]
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
copies = self.trace_weight_loads(table)
plan = self.build_transfer_plan(table, copies)
self.buffer_sessions = []
for buffer_index in range(table.staging_buffer_count):
session = ModelExpressSession(
client=self.model_express.client,
role="inference",
rank=self.model_express.rank,
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
)
session.publish()
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.buffer_sessions.append(session)
# Join the current generation directly. Publishing a transient READY
# before the first pull would let the trainer mistake initialization
# for a completed acknowledgement.
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.weight_transfer_plan = plan
logger.info(
"Initialized NIXL transfer plan on rank %d with %d groups",
self.model_express.rank,
len(plan.groups),
)
return plan
def trace_weight_loads(
self,
table: TrainerTensorTable,
) -> list[RecordedCopy]:
"""Trace vLLM weight loading into source-to-destination copies."""
from vllm.model_executor.model_loader.reload.layerwise import (
_get_original_loader,
initialize_layerwise_reload,
)
from vllm.model_executor.model_loader.reload.meta import SKIP_TENSORS
from vllm.model_executor.model_loader.reload.utils import get_layer_tensors
model = self.raw_model
recorder = WeightLoadRecorder()
regular_by_layer: dict[int, list[RecordedCopy]] = defaultdict(list)
persistent: list[RecordedCopy] = []
original_loaders: list[tuple[torch.Tensor, Any]] = []
with torch.device(self.device), set_current_vllm_config(self.vllm_config):
initialize_layerwise_reload(model)
try:
for module in model.modules():
for name, tensor in get_layer_tensors(module).items():
destination = Destination(module, name, tensor)
if not tensor.is_meta:
recorder.register_destination_storage(destination)
loader = _get_original_loader(tensor)
original_loaders.append((tensor, loader))
tensor.weight_loader = self.wrap_weight_loader_for_recording(
recorder,
destination,
loader,
)
model.load_weights(
make_hf_lazy_weights(
table,
device=self.device,
recorder=recorder,
hf_config=self.model_runner.model_config.hf_text_config,
)
)
for copy in recorder.copies:
if copy.is_persistent or copy.destination_name in SKIP_TENSORS:
copy.is_persistent = True
persistent.append(copy)
else:
regular_by_layer[id(copy.destination_module)].append(copy)
finally:
try:
for tensor, loader in reversed(original_loaders):
tensor.weight_loader = loader
finally:
self._restore_layerwise_state(model)
regular = [copy for copies in regular_by_layer.values() for copy in copies]
return regular + persistent
@staticmethod
def wrap_weight_loader_for_recording(
recorder: WeightLoadRecorder,
destination: Destination,
loader: Any,
):
@wraps(loader)
def recording_loader(*args, **kwargs):
recorder.active_destination = destination
try:
return loader(*args, **kwargs)
finally:
recorder.active_destination = None
return recording_loader
@staticmethod
def _restore_layerwise_state(model: nn.Module) -> None:
from vllm.model_executor.model_loader.reload.layerwise import LAYERWISE_INFO, _place_kernel_tensors
for layer in model.modules():
info = LAYERWISE_INFO.get(layer)
if info is not None and info.can_load():
if info.kernel_tensors is not None:
_place_kernel_tensors(layer, info)
info.reset()
if hasattr(model, "_original_do_torchao_reload"):
model._do_torchao_reload = model._original_do_torchao_reload
def build_transfer_plan(
self,
table: TrainerTensorTable,
copies: list[RecordedCopy],
) -> WeightTransferPlan:
replay_plans = self.plan_tensor_replays(table, copies)
receive_buffer_elements = self.calculate_receive_buffer_elements(
table,
copies,
replay_plans,
)
receive_buffer_count = self.choose_receive_buffer_count(
receive_buffer_elements,
table.staging_buffer_count,
)
receive_arenas = self.allocate_receive_arenas(
receive_buffer_elements,
receive_buffer_count,
)
groups = self.build_transfer_groups(
table,
copies,
replay_plans,
receive_buffer_elements,
receive_arenas,
receive_buffer_count,
)
return WeightTransferPlan(
receive_arenas=receive_arenas,
receive_buffer_count=receive_buffer_count,
groups=groups,
)
def plan_tensor_replays(
self,
table: TrainerTensorTable,
copies: list[RecordedCopy],
) -> dict[int, TensorReplayPlan]:
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
replay_plans: dict[int, TensorReplayPlan] = {}
for copy in copies:
source = tensors[copy.source_name]
replay_plans[id(copy)] = plan_tensor_replay(
tuple(source.shape),
getattr(torch, source.wire_dtype),
copy.ops,
)
return replay_plans
def calculate_receive_buffer_elements(
self,
table: TrainerTensorTable,
copies: list[RecordedCopy],
replay_plans: dict[int, TensorReplayPlan],
) -> dict[torch.dtype, int]:
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
tensor_groups = {
tensor.name: group_index for group_index, group in enumerate(table.groups) for tensor in group.tensors
}
group_elements: dict[torch.dtype, list[int]] = defaultdict(lambda: [0] * len(table.groups))
for copy in copies:
source = tensors[copy.source_name]
source_dtype = getattr(torch, source.wire_dtype)
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
def choose_receive_buffer_count(
self,
receive_buffer_elements: dict[torch.dtype, int],
staging_buffer_count: int,
) -> int:
receive_buffer_bytes = max(
1,
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
)
allocated_bytes = torch.cuda.memory_allocated(self.device)
peak_growth_bytes = max(
0,
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
)
free_bytes, _ = torch.cuda.mem_get_info(self.device)
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
torch.cuda.empty_cache()
return size_cuda_buffers(
receive_buffer_bytes,
max_receive_buffers,
self.device,
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
)
def allocate_receive_arenas(
self,
receive_buffer_elements: dict[torch.dtype, int],
receive_buffer_count: int,
) -> dict[torch.dtype, torch.Tensor]:
with use_cuda_malloc_pool():
receive_arenas = {
dtype: torch.empty(
receive_buffer_count * elements,
dtype=dtype,
device=self.device,
)
for dtype, elements in receive_buffer_elements.items()
if elements
}
for arena in receive_arenas.values():
self.nixl_agent.register_tensor(arena)
return receive_arenas
def build_transfer_groups(
self,
table: TrainerTensorTable,
copies: list[RecordedCopy],
replay_plans: dict[int, TensorReplayPlan],
receive_buffer_elements: dict[torch.dtype, int],
receive_arenas: dict[torch.dtype, torch.Tensor],
receive_buffer_count: int,
) -> list[WeightTransferGroup]:
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
tensor_groups = {
tensor.name: group_index for group_index, group in enumerate(table.groups) for tensor in group.tensors
}
copies_by_group: dict[int, list[RecordedCopy]] = defaultdict(list)
for copy in copies:
copies_by_group[tensor_groups[copy.source_name]].append(copy)
reload_layers: dict[int, nn.Module] = {}
for copy in copies:
if not copy.is_persistent:
reload_layers.setdefault(id(copy.destination_module), copy.destination_module)
reload_layer_groups: dict[int, int] = {}
for copy in copies:
layer_id = id(copy.destination_module)
if layer_id not in reload_layers:
continue
source_group = tensor_groups[copy.source_name]
previous_group = reload_layer_groups.setdefault(layer_id, source_group)
if previous_group != source_group:
raise RuntimeError(
f"vLLM reload layer {type(copy.destination_module).__name__} reads trainer groups "
f"{table.groups[previous_group].name!r} and {table.groups[source_group].name!r}"
)
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
peer_names: dict[int, str] = {}
transfer_groups: list[WeightTransferGroup] = []
for group_index, group in enumerate(table.groups):
copy_plans_by_layer: dict[int, list[TensorCopyPlan]] = defaultdict(list)
persistent_plans_by_layer: dict[int, list[TensorCopyPlan]] = defaultdict(list)
local_descs: dict[int, list[MemDesc]] = defaultdict(list)
remote_descs: dict[int, list[MemDesc]] = defaultdict(list)
cursors = {
dtype: (group_index % receive_buffer_count) * elements
for dtype, elements in receive_buffer_elements.items()
}
for copy in copies_by_group[group_index]:
replay_plan = replay_plans[id(copy)]
source = tensors[copy.source_name]
source_dtype = getattr(torch, source.wire_dtype)
numel = prod(replay_plan.source_shape)
cursor = cursors[source_dtype]
staging_tensor = receive_arenas[source_dtype].narrow(0, cursor, numel).view(replay_plan.source_shape)
cursors[source_dtype] += numel
copy_plan = TensorCopyPlan(
recorded_copy=copy,
staging_tensor=staging_tensor,
replay_ops=replay_plan.replay_ops,
)
plans = persistent_plans_by_layer if copy.is_persistent else copy_plans_by_layer
plans[id(copy.destination_module)].append(copy_plan)
for route in route_sharded_tensor(replay_plan, source, staging_tensor):
local_descs[route.agent].append((route.destination_addr, route.nbytes, self.device.index))
remote_descs[route.agent].append((route.source_addr, route.nbytes, agent_devices[route.agent]))
transfer_groups.append(
WeightTransferGroup(
name=group.name,
layers=self.build_layer_transfer_plans(
reload_layers,
copy_plans_by_layer,
persistent_plans_by_layer,
),
pulls=self.prepare_group_pulls(
table,
local_descs,
remote_descs,
peer_names,
),
)
)
return transfer_groups
def build_layer_transfer_plans(
self,
reload_layers: dict[int, nn.Module],
copy_plans_by_layer: dict[int, list[TensorCopyPlan]],
persistent_plans_by_layer: dict[int, list[TensorCopyPlan]],
) -> list[LayerWeightTransferPlan]:
layer_plans: list[LayerWeightTransferPlan] = []
for layer_id, layer in reload_layers.items():
copies = copy_plans_by_layer.get(layer_id, [])
persistent_copies = persistent_plans_by_layer.get(layer_id, [])
if copies:
layer_plans.append(
LayerWeightTransferPlan(
reload_layer=layer,
copies=copies,
persistent_copies=persistent_copies,
)
)
elif persistent_copies:
layer_plans.append(
LayerWeightTransferPlan(
reload_layer=None,
copies=[],
persistent_copies=persistent_copies,
)
)
remaining_persistent = [
plan
for layer_id, plans in persistent_plans_by_layer.items()
if layer_id not in reload_layers
for plan in plans
]
if remaining_persistent:
layer_plans.append(
LayerWeightTransferPlan(
reload_layer=None,
copies=[],
persistent_copies=remaining_persistent,
)
)
return layer_plans
def prepare_group_pulls(
self,
table: TrainerTensorTable,
local_descs: dict[int, list[MemDesc]],
remote_descs: dict[int, list[MemDesc]],
peer_names: dict[int, str],
) -> list[tuple[Any, Any, list[int]]]:
pulls: list[tuple[Any, Any, list[int]]] = []
for agent_index, remote in sorted(remote_descs.items()):
peer_name = peer_names.get(agent_index)
if peer_name is None:
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
self.nixl_agent.make_connection(peer_name)
peer_names[agent_index] = peer_name
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
return pulls
@torch.no_grad()
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
del weight_dir
plan = self.initialize_transfer()
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.model_express.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_READY,
timeout=self.weight_transfer_timeout,
)
started = time.perf_counter()
self.apply_transfer_plan(plan)
update_mla_absorbed_weights(self.raw_model)
torch.cuda.synchronize(self.device)
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
logger.info(
"Applied NIXL policy update on rank %d in %.2fs",
self.model_express.rank,
time.perf_counter() - started,
)
def apply_transfer_plan(self, plan: WeightTransferPlan) -> None:
from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
from vllm.model_executor.model_loader.reload.layerwise import (
LAYERWISE_INFO,
_copy_and_restore_kernel_tensors,
finalize_layerwise_reload,
initialize_layerwise_reload,
)
from vllm.model_executor.model_loader.reload.meta import materialize_layer
from vllm.model_executor.model_loader.reload.utils import get_layer_tensors
model = self.raw_model
cancelled = Event()
def pull_group(group_index: int) -> WeightTransferGroup:
transfer_group = plan.groups[group_index]
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
session.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_READY,
timeout=self.weight_transfer_timeout,
poll_interval=_BUFFER_POLL_INTERVAL,
cancelled=cancelled.is_set,
)
for local, remote, indices in transfer_group.pulls:
handle = self.nixl_agent.post_read(local, indices, remote)
self.nixl_agent.wait(
handle,
context=f"weight pull for {transfer_group.name}",
timeout=self.weight_transfer_timeout,
cancelled=cancelled.is_set,
)
return transfer_group
def acknowledge_group(group_index: int) -> None:
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
session.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.weight_transfer_timeout,
poll_interval=_BUFFER_POLL_INTERVAL,
cancelled=cancelled.is_set,
)
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
def prefetch_group(group_index: int) -> WeightTransferGroup:
torch.cuda.set_device(self.device)
transfer_group = pull_group(group_index)
acknowledge_group(group_index)
return transfer_group
def replay_group(transfer_group: WeightTransferGroup) -> None:
for layer_plan in transfer_group.layers:
layer = layer_plan.reload_layer
if layer is None:
for copy_plan in layer_plan.persistent_copies:
self.replay_tensor_copy(copy_plan)
continue
info = LAYERWISE_INFO[layer]
materialize_layer(layer, info)
# Match loader semantics for destinations with unwritten padding.
destination_names = layer_plan.destination_names
for name, tensor in get_layer_tensors(layer).items():
if name in destination_names and not tensor.is_meta:
tensor.zero_()
for copy_plan in layer_plan.copies:
self.replay_tensor_copy(copy_plan)
for copy_plan in layer_plan.persistent_copies:
self.replay_tensor_copy(copy_plan)
if hasattr(layer, "_already_called_process_weights_after_loading"):
delattr(layer, "_already_called_process_weights_after_loading")
quant_method = getattr(layer, "quant_method", None)
if isinstance(quant_method, QuantizeMethodBase):
quant_method.process_weights_after_loading(layer)
if info.kernel_tensors is not None:
_copy_and_restore_kernel_tensors(layer, info)
info.reset()
with torch.device(self.device), set_current_vllm_config(self.vllm_config):
initialize_layerwise_reload(model)
pipelined = plan.receive_buffer_count > 1
executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="nixl-prefetch") if pipelined else None
try:
pull = executor.submit(prefetch_group, 0) if executor is not None else None
for group_index in range(len(plan.groups)):
transfer_group = pull.result() if pull is not None else pull_group(group_index)
torch.cuda.synchronize(self.device)
if executor is not None and group_index + 1 < len(plan.groups):
pull = executor.submit(prefetch_group, group_index + 1)
replay_group(transfer_group)
torch.cuda.synchronize(self.device)
if not pipelined:
acknowledge_group(group_index)
finally:
cancelled.set()
if executor is not None:
executor.shutdown(wait=True, cancel_futures=True)
finalize_layerwise_reload(model, self.model_runner.model_config)
@staticmethod
def replay_tensor_copy(plan: TensorCopyPlan) -> None:
copy = plan.recorded_copy
parameter = getattr(copy.destination_module, copy.destination_name)
destination = parameter.as_strided(
copy.destination_shape,
copy.destination_stride,
copy.destination_offset,
)
value = apply_chain(plan.staging_tensor, plan.replay_ops)
destination.copy_(value)
+4 -1
View File
@@ -5,7 +5,7 @@ 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``,
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``, ``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
@@ -34,6 +34,7 @@ from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
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 +49,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
"grpo": GRPOAlgorithm,
"echo": EchoAlgorithm,
"max_rl": MaxRLAlgorithm,
"rae": RAEAlgorithm,
"opd": OPDAlgorithm,
"opsd": OPSDAlgorithm,
"sft": SFTDistillAlgorithm,
@@ -72,6 +74,7 @@ __all__ = [
"MaxRLAlgorithm",
"OPDAlgorithm",
"OPSDAlgorithm",
"RAEAlgorithm",
"Rollout",
"SFTDistillAlgorithm",
"build_algorithm",
+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 | None, 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
+52 -29
View File
@@ -3,8 +3,8 @@
- Capacity (``max_inflight_rollouts``) is shared across train + eval.
A group-scoring task that runs N rollouts in one call reserves N permits.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched rollout eventually reaches
``out_q`` exactly once as a ``Rollout``. Failures
- Emit-everything invariant: every dispatched env-rollout eventually reaches
``out_q`` exactly once, as one episode (a ``list[Rollout]``). Failures
(env error, empty trajectory, task exception, off-policy cancel) carry
``trace.error`` set; sinks decide drop / partial-train policy.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
@@ -152,8 +152,9 @@ class RolloutDispatcher:
self.inflight: dict[asyncio.Task, InflightRollout] = {}
self.groups: dict[uuid.UUID, GroupState] = {}
# Bounded so the dispatcher backpressures on a slow sink
self.out_q: asyncio.Queue[Rollout] = asyncio.Queue(maxsize=max(8, self.max_inflight))
# Bounded so the dispatcher backpressures on a slow sink. One entry per
# episode — the sinks count episodes, never loose traces.
self.out_q: asyncio.Queue[list[Rollout]] = asyncio.Queue(maxsize=max(8, self.max_inflight))
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
# Set by the orchestrator after the final train step; pipeline then
@@ -386,6 +387,7 @@ class RolloutDispatcher:
kind=kind,
env_name=env_name,
task_idx=example["task_idx"],
task=example.get("task"),
rollouts_to_schedule=group_size,
target_rollouts=group_size,
eval_step=eval_step,
@@ -393,7 +395,7 @@ class RolloutDispatcher:
)
async def schedule_group_rollout(self, group_id: uuid.UUID, group: GroupState) -> bool:
"""Dispatch one ``run_rollout`` / ``run_group`` task for this group.
"""Dispatch one ``run`` / ``run_group`` task for this group.
Returns False only if we couldn't even schedule one rollout (no clients
ready, no permits). Returns True after issuing one task — the caller
@@ -437,6 +439,7 @@ class RolloutDispatcher:
cache_salt = None
if env.requires_group_scoring:
# Legacy-only route (a v1 env never group-scores) — addressed by row.
permits = group.rollouts_to_schedule
group.rollouts_to_schedule = 0
await self.acquire(permits)
@@ -450,15 +453,20 @@ class RolloutDispatcher:
)
)
else:
# A v1 env takes the task itself; the legacy bridge its dataset row.
if group.task is not None:
addressing = {"task_data": group.task.data.model_dump(mode="json")}
else:
addressing = {"task_idx": group.task_idx}
permits = 1
group.rollouts_to_schedule -= 1
await self.acquire(permits)
task = asyncio.create_task(
env.run_rollout(
env.run(
client=client,
task_idx=group.task_idx,
model_name=model_name,
cache_salt=cache_salt,
**addressing,
)
)
@@ -485,11 +493,13 @@ class RolloutDispatcher:
self.inflight_permits -= n
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
"""Emit every dispatched rollout exactly once to ``out_q``. Task
exceptions synthesize ``meta.rollout_count`` error markers so the
sink's count-to-``group_size`` finalization still triggers.
Cancelled tasks (popped by ``drop_group``) raise ``CancelledError``
and are discarded — ``drop_group`` already emitted their markers.
"""Emit every dispatched env-rollout 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
still triggers. Cancelled tasks (popped by ``drop_group``) raise
``CancelledError`` and are discarded — ``drop_group`` already emitted
their markers.
"""
meta = self.inflight.pop(task, None)
if meta is None:
@@ -501,6 +511,8 @@ class RolloutDispatcher:
try:
result = task.result()
rollouts: list[Rollout] = result if isinstance(result, list) else [result]
if not rollouts:
raise RuntimeError("env run returned an empty episode (no traces)")
except asyncio.CancelledError:
return
except Exception as exc:
@@ -517,20 +529,28 @@ class RolloutDispatcher:
for r in rollouts:
if not r.has_error and r.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure
# treats it like any other failure (``has_error`` reads ``ok``)
r.errors.append(vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps"))
r.ok = False
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:
if not is_synth_exception and r.error is not None:
get_logger().warning(
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.error.type}: {r.error.message}"
)
await self.emit_rollout(meta, group, r)
if meta.rollout_count == 1:
# A ``run`` task: the whole result is one episode.
await self.emit_episode(meta, group, rollouts)
else:
# A legacy ``run_group`` task: one single-trace episode per trace.
for r in rollouts:
await self.emit_episode(meta, group, [r])
async def emit_rollout(self, meta: InflightRollout, group: GroupState | None, rollout: Rollout) -> None:
"""Stamp prime-rl metadata onto the completed rollout and put it on ``out_q``.
Pops the group from ``self.groups`` once every member has been emitted."""
async def emit_episode(self, meta: InflightRollout, group: GroupState | None, rollouts: list[Rollout]) -> None:
"""Stamp prime-rl metadata onto one completed episode and put it on
``out_q``. Pops the group from ``self.groups`` once every owed episode
has been emitted."""
eval_step = meta.eval_step
policy_version = meta.policy_version
if group is not None:
@@ -540,15 +560,16 @@ class RolloutDispatcher:
if group.emitted >= group.target_rollouts:
self.groups.pop(meta.group_id, None)
rollout.kind = meta.kind
rollout.env_name = meta.env_name
rollout.group_id = meta.group_id
rollout.policy_version = policy_version
rollout.off_policy_steps = meta.off_policy_steps
if meta.kind == "eval":
assert eval_step is not None, "eval rollout missing eval_step"
rollout.eval_step = eval_step
await self.out_q.put(rollout)
for rollout in rollouts:
rollout.kind = meta.kind
rollout.env_name = meta.env_name
rollout.group_id = meta.group_id
rollout.policy_version = policy_version
rollout.off_policy_steps = meta.off_policy_steps
if meta.kind == "eval":
assert eval_step is not None, "eval rollout missing eval_step"
rollout.eval_step = eval_step
await self.out_q.put(rollouts)
async def drop_group(self, group_id: uuid.UUID) -> int:
"""Cancel remaining in-flight tasks for this group and emit a
@@ -578,10 +599,11 @@ class RolloutDispatcher:
for _ in range(meta.rollout_count):
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_rollout(meta, group, trace)
await self.emit_episode(meta, group, [trace])
# For non-group-scoring envs, the group may have rollouts that
# were never dispatched (``rollouts_to_schedule > 0``). Emit
@@ -604,10 +626,11 @@ class RolloutDispatcher:
for _ in range(unscheduled_cancelled):
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_rollout(fallback_meta, group, trace)
await self.emit_episode(fallback_meta, group, [trace])
cancelled = inflight_cancelled + unscheduled_cancelled
if cancelled > 0:
@@ -1,7 +1,7 @@
from functools import partial
from verifiers.v1 import pool_serve_kwargs
from verifiers.v1.serve import serve_env
from verifiers.v1.serve import env_config_data, serve_env
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.orchestrator.utils import setup_env_server_logging
@@ -15,13 +15,13 @@ 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
# the bridge, a v1 env is a native taskset — both serve vf.Trace over the same protocol,
# 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": env}
else {"config_data": env_config_data(env.env)}
)
serve_env(
**pool_serve_kwargs(env.pool),
+86 -38
View File
@@ -2,15 +2,19 @@
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
orchestrator never *runs* an environment: it asks the server for ``info``
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
**task index**. The server returns a ``Trace`` (a plain ``model_dump`` — derived values are
properties, not serialized) which we validate into a ``Trace[WireTaskData]`` — a real ``vf.Trace``
(never a loose dict) whose task keeps the env's
task-specific fields as extras (``WireTaskData`` allows them). The orchestrator never imports the
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
and a full ``task.model_dump``, both of which ``WireTaskData`` preserves.)
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
(``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
cache — and gives the orchestrator real tasks to cycle, shuffle, and filter. Only
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
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
"""
from __future__ import annotations
@@ -22,12 +26,13 @@ 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
from verifiers.v1.serve import EnvClient, env_config_data
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
@@ -40,9 +45,8 @@ 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. The child
# loads the taskset (possibly downloading a dataset) before reporting, so this
# is generous.
# 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
@@ -78,14 +82,20 @@ def _run_env_server(
class Env:
"""Wraps a v1 env server + client. The orchestrator never loads the env."""
"""Wraps a v1 env server + client. The orchestrator owns the taskset (loaded once,
client-side); the server owns agent/harness execution."""
def __init__(self, config: EnvConfig):
self.config = config
self.sampling_args: dict = {}
self.num_tasks: int | None = 0
"""Task count reported by the server; ``None`` means the taskset is infinite."""
"""Task count; ``None`` means the taskset is infinite."""
self.requires_group_scoring: bool = False
self.tasks: Iterator[vf.Task] | None = None
"""The env's tasks, client-side; ``None`` for legacy (its dataset lives on the
server). A finite taskset is materialized at ``start()`` (``num_tasks`` is its
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
@@ -100,25 +110,36 @@ class Env:
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 cache its ``info``."""
"""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 + loading,
# so it's up — the untimed ``info`` below is enough. An external server has
# no such handshake, so poll until it answers before we block on ``info``.
# 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()
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
if self.config.is_legacy:
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
else:
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
self.tasks = iter(taskset.load())
self.num_tasks = None
else:
# Materialize off the event loop — load() may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} 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 loads the env; we never do).
The server binds an OS-assigned port (``:0``) and reports the concrete
"""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)."""
@@ -135,7 +156,8 @@ class Env:
extra_env_kwargs=self.config.extra_env_kwargs,
)
if self.config.is_legacy
else dict(legacy=False, config=self.config)
# 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,
@@ -168,17 +190,40 @@ class Env:
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
return vf.SamplingConfig(**sampling)
async def run_rollout(
self, client: vf.ClientConfig, task_idx: int, model_name: str, cache_salt: str | None
) -> Rollout:
"""Run a single rollout for ``task_idx``; return a typed Trace."""
wire = await self.env_client.run_rollout(
async def run(
self,
client: vf.ClientConfig,
model_name: str,
cache_salt: str | None,
task_data: dict | None = None,
task_idx: int | None = None,
) -> list[Rollout]:
"""Run one episode; return its typed Traces. A v1 env takes the task itself
(``task_data``); the legacy bridge is addressed by dataset row (``task_idx``).
A zero-trace episode raises (the dispatcher synthesizes the error marker); a
not-``ok`` episode marks its clean traces failed so partial episodes never
train."""
episode = await self.env_client.run(
task_data=task_data,
task_idx=task_idx,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
)
return ROLLOUT_TYPE.model_construct(**dict(wire))
if not episode.traces:
error = episode.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}")
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(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
rollout.errors = [*rollout.errors, error]
rollout.ok = False
return rollouts
async def run_group(
self, client: vf.ClientConfig, task_idx: int, model_name: str, group_size: int, cache_salt: str | None
@@ -220,13 +265,16 @@ class EvalEnv(Env):
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)
if self.num_tasks is None:
if self.config.num_examples < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
n = self.config.num_examples
else:
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
self.examples = [{"task_idx": i} for i in range(n)]
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)
self.examples = [{"task_idx": i} for i in range(count)]
return
if self.num_tasks is None and n < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
# A fixed eval set, pulled off the tasks once and reused every epoch.
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
self.examples = [{"task_idx": task.data.idx, "task": task} for task in tasks]
EnvT = TypeVar("EnvT", bound=Env)
+29 -21
View File
@@ -3,12 +3,13 @@
Same shape as ``TrainSink``, but no tokenization / advantages / filters:
1. ``process_rollout`` — no-op.
2. ``process_group`` — at ``group_size`` arrivals, move the rollouts
2. ``process_group`` — at ``group_size`` episodes, move the rollouts
(errored ones included) into the ``(env, eval_step)`` bucket.
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, return an
3. ``process_batch`` — at ``num_examples × group_size`` episodes, return an
``EvalBatch`` with the full returned cohort (metrics are computed downstream).
``add()`` returns ``EvalBatch | None``.
``add()`` takes one episode (``list[Rollout]``) and returns ``EvalBatch | None``;
all accounting counts episodes, never loose traces.
"""
from __future__ import annotations
@@ -28,20 +29,24 @@ class EvalSink:
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
# Bucket size IS the arrival count — ``process_group`` flushes
# everything in without filtering
# Episodes arrived per group / per batch bucket — the finalization counts.
self.pending_group_episodes: dict[uuid.UUID, int] = defaultdict(int)
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
self.pending_batch_episodes: dict[tuple[str, int], int] = defaultdict(int)
def add(self, rollout: Rollout) -> EvalBatch | None:
"""Process one arrival; finalize the group on the ``group_size``-th
arrival and the per-env epoch on the ``num_examples × group_size``-th."""
env_name = rollout.env_name
self.process_rollout(rollout)
bkey = (env_name, rollout.eval_step)
self.pending_groups[rollout.group_id].append(rollout)
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
self.process_group(rollout.group_id)
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
def add(self, episode: list[Rollout]) -> EvalBatch | None:
"""Process one episode arrival; finalize the group on the ``group_size``-th
episode and the per-env epoch on the ``num_examples × group_size``-th."""
env_name = episode[0].env_name
group_id = episode[0].group_id
for rollout in episode:
self.process_rollout(rollout)
bkey = (env_name, episode[0].eval_step)
self.pending_groups[group_id].extend(episode)
self.pending_group_episodes[group_id] += 1
if self.pending_group_episodes[group_id] >= self.group_size_for(env_name):
self.process_group(group_id)
if self.pending_batch_episodes[bkey] >= self.batch_size_for(env_name):
return self.process_batch(bkey)
return None
@@ -49,7 +54,7 @@ class EvalSink:
return self.eval_envs.get(env_name).config.group_size
def batch_size_for(self, env_name: str) -> int:
"""``num_examples × group_size`` — total rollouts expected for one
"""``num_examples × group_size`` — total episodes expected for one
epoch of ``env_name``."""
env = self.eval_envs.get(env_name)
return len(env.examples) * env.config.group_size
@@ -57,18 +62,18 @@ class EvalSink:
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
"""One entry per accumulating ``(env, eval_step)`` batch:
``(env_name, eval_step, batch_count, expected, buffered)``.
``batch_count`` is finalized-group survivors in ``pending_batches``;
``buffered`` is partial-group arrivals from non-group-scoring envs."""
batch_counts: dict[tuple[str, int], int] = {bkey: len(bucket) for bkey, bucket in self.pending_batches.items()}
``batch_count`` is finalized-group episodes in ``pending_batches``;
``buffered`` is partial-group episode arrivals from non-group-scoring envs."""
batch_counts: dict[tuple[str, int], int] = dict(self.pending_batch_episodes)
buffered: dict[tuple[str, int], int] = {}
for rollouts in self.pending_groups.values():
for group_id, rollouts in self.pending_groups.items():
if not rollouts:
continue
env_name = rollouts[0].env_name
if self.eval_envs.get(env_name).requires_group_scoring:
continue
bkey = (env_name, rollouts[0].eval_step)
buffered[bkey] = buffered.get(bkey, 0) + len(rollouts)
buffered[bkey] = buffered.get(bkey, 0) + self.pending_group_episodes.get(group_id, 0)
return [
(
env_name,
@@ -93,6 +98,7 @@ class EvalSink:
def process_group(self, group_id: uuid.UUID) -> None:
group = self.pending_groups.pop(group_id, [])
episodes = self.pending_group_episodes.pop(group_id, 0)
if not group:
return
env_name = group[0].env_name
@@ -100,6 +106,7 @@ class EvalSink:
eval_step = group[0].eval_step
bucket = self.pending_batches[(env_name, eval_step)]
bucket.extend(group)
self.pending_batch_episodes[(env_name, eval_step)] += episodes
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
@@ -117,4 +124,5 @@ class EvalSink:
does no aggregation."""
env_name, step = key
rollouts = self.pending_batches.pop(key, [])
self.pending_batch_episodes.pop(key, None)
return EvalBatch(env_name=env_name, step=step, rollouts=EvalRollouts(rollouts))
+24 -14
View File
@@ -12,7 +12,7 @@ is flat over the rollout list except the solve rates, which group by ``group_id`
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
@@ -134,16 +134,20 @@ class TimingMetrics(StatGroup):
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 averaged over the rollouts that report the key. ``value`` extracts the
float from each 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(getattr(r, self.attr)[name]) for r in self.rollouts if name in getattr(r, self.attr)]
)
for name in names
}
@@ -188,8 +192,9 @@ class RolloutMetrics:
@property
def rewards(self) -> CustomMetrics:
"""Per-component reward breakdown, keyed by name (summed into the scalar ``reward``)."""
return CustomMetrics(self.rollouts, "rewards")
"""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)
# Boolean rate metrics (0/1 distributions — ``.mean()`` is the rate)
@property
@@ -337,8 +342,9 @@ class EvalMetrics(RolloutMetrics):
class TrainRollouts:
"""A list of train rollouts (everything that came back, errored + filtered included). ``effective``
is the clean subset (a view of the same traces); ``metrics`` builds ``TrainMetrics`` over them."""
"""A list of train rollouts (everything that came back, errored + filtered + untrainable
included). ``effective`` is the clean trainable subset (a view of the same traces);
``metrics`` builds ``TrainMetrics`` over them."""
def __init__(self, rollouts: list[Rollout] | None = None) -> None:
self.rollouts = rollouts if rollouts is not None else []
@@ -354,7 +360,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])
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered and r.trainable])
def by_env(self) -> dict[str, TrainRollouts]:
grouped: dict[str, list[Rollout]] = {}
@@ -368,7 +374,8 @@ class TrainRollouts:
class EvalRollouts:
"""A list of eval rollouts (errored included). ``effective`` is the non-errored subset (a view).
"""A list of eval rollouts (errored + untrainable included). ``effective`` is the
non-errored trainable subset (a view).
``group_size`` (rollouts per example, the ``avg@k`` k) is derived from the full epoch and carried
onto ``effective`` so both subsets share one stable key; ``metrics`` builds ``EvalMetrics``."""
@@ -384,18 +391,21 @@ class EvalRollouts:
@property
def group_size(self) -> int:
"""The largest group (equals the configured group size whenever one example kept all its
rollouts); a subview carries its parent's value so ``avg@k`` doesn't drift across subsets."""
"""The largest group in trainable (policy) traces — equals the configured group size
whenever one example kept all its rollouts; untrainable traces don't count, so a
multi-agent episode doesn't inflate ``k``. A subview carries its parent's value so
``avg@k`` doesn't drift across subsets."""
if self._group_size is not None:
return self._group_size
counts: dict = {}
for r in self.rollouts:
counts[r.group_id] = counts.get(r.group_id, 0) + 1
if r.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], group_size=self.group_size)
return EvalRollouts([r for r in self.rollouts if not r.has_error and r.trainable], group_size=self.group_size)
@property
def metrics(self) -> EvalMetrics:
+110 -36
View File
@@ -28,6 +28,8 @@ from typing import TYPE_CHECKING
import tomli_w
import verifiers.v1 as vf
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
if TYPE_CHECKING:
from renderers.base import Renderer
@@ -70,9 +72,10 @@ from prime_rl.orchestrator.utils import (
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
from prime_rl.utils.config import to_toml_dict
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
@@ -173,6 +176,8 @@ class Orchestrator:
self.eval_triggered_at = {}
self.consecutive_empty_batches = 0
self.gate_closed_at = None
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
self.version_advanced = asyncio.Event()
self.wait_for_policy_time = 0.0
self.component_tasks = []
@@ -189,6 +194,7 @@ class Orchestrator:
self.lora_name = None
self.resume_step = None
self.lag_task = None
self.model_express = None
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -227,6 +233,7 @@ class Orchestrator:
self.monitor = setup_monitor(
wandb_config=config.wandb,
prime_config=config.prime_monitor,
file_config=config.file_monitor,
output_dir=config.output_dir,
tokenizer=self.tokenizer,
run_config=config,
@@ -308,6 +315,24 @@ class Orchestrator:
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
elif config.weight_broadcast.type == "nixl":
await init_nixl_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
config.weight_broadcast.inference_world_size,
config.weight_broadcast.session_id,
)
self.model_express = ModelExpressSession(
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
role="orchestrator",
rank=0,
session_id=config.weight_broadcast.session_id,
worker_id="orchestrator",
)
self.model_express.publish()
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
get_logger().info(f"Initializing training batch sender ({config.rollout_transport})")
self.sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
@@ -325,18 +350,31 @@ class Orchestrator:
get_logger().info("Training from scratch")
# Sync inference to the incoming policy before the first step when resuming or when using
# NCCL, which rendezvouses with the trainer's first-step broadcast (train.py). A fresh
# filesystem run needs no sync (the base model IS policy v0) and must not wait for a
# startup broadcast: runs registered after the trainer's first step never receive one.
if self.resume_step is not None or config.weight_broadcast.type == "nccl":
# an in-memory transport, which rendezvouses with the trainer's startup broadcast.
if self.resume_step is not None or config.weight_broadcast.type in ("nccl", "nixl"):
sync_version = self.resume_step if self.resume_step is not None else 0
check_exists = config.weight_broadcast.type != "nccl"
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
weights_path = get_weight_dir(
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
)
if config.weight_broadcast.type == "nixl":
weights_path = None
else:
check_exists = config.weight_broadcast.type == "filesystem"
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
weights_path = get_weight_dir(
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
)
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
# Complete the startup rendezvous before the watcher begins its next cycle.
await asyncio.to_thread(
self.model_express.wait_for,
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=config.weight_broadcast.timeout,
)
if self.lora_name is not None:
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
@@ -385,6 +423,7 @@ class Orchestrator:
observers=[self.dispatcher, self],
lora_name=self.lora_name,
ckpt_step=self.policy.version,
model_express=self.model_express,
)
# Single periodic logger for the whole pipeline. It's the only
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
@@ -466,7 +505,7 @@ class Orchestrator:
trim_process_memory()
async def main_loop(self) -> None:
"""Consume ``Rollout``\\ s from the dispatcher and route them
"""Consume episodes (``list[Rollout]``) from the dispatcher and route them
to the train / eval sink. Both sinks return a finalized batch (or
``None``) from ``add()``; we just dispatch on the result."""
while not self.stopped.is_set():
@@ -476,7 +515,7 @@ class Orchestrator:
break
try:
rollout: Rollout = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
episode: list[Rollout] = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
except asyncio.TimeoutError:
continue
@@ -484,33 +523,36 @@ class Orchestrator:
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
# Train rollouts belong to the batch window currently collecting (``progress.step``),
# eval rollouts to the step whose eval triggered them.
step = rollout.eval_step if rollout.kind == "eval" else self.progress.step
kind = episode[0].kind
step = episode[0].eval_step if kind == "eval" else self.progress.step
assert step is not None
run: vf.RunInfo = (
vf.EvalRunInfo(id=self.monitor.run_id, step=step)
if rollout.kind == "eval"
if kind == "eval"
else vf.TrainRunInfo(id=self.monitor.run_id, step=step)
)
rollout.stamp(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
policy_version=rollout.policy_version,
)
for rollout in episode:
rollout.stamp(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await asyncio.to_thread(
save_rollouts,
[rollout.to_record()],
get_trace_path(self.config.output_dir, step, rollout.kind, "all"),
[rollout.to_record() for rollout in episode],
get_trace_path(self.config.output_dir, step, kind, "all"),
)
if rollout.kind == "eval":
if kind == "eval":
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
eval_batch = self.eval_sink.add(rollout)
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
continue
train_batch = await self.train_sink.add(rollout)
train_batch = await self.train_sink.add(episode)
# In drain mode any late-arriving train batch is dropped — we
# don't want to ship past ``max_steps``
if train_batch is not None and not self.draining and not self.stopped.is_set():
@@ -562,6 +604,35 @@ class Orchestrator:
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
)
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
# Without this, fast envs fill batches from buffered rollouts, the
# orchestrator finishes early, and its teardown strands the trainer inside
# an in-memory broadcast handshake that needs the live weight watcher.
# Always satisfiable: the trainer skips only the final TARGET_LAG+1
# in-memory broadcasts. Bench runs have no trainer, so they ship freely.
required_version = step - 1 - TARGET_LAG
if not config.bench and self.policy.version < required_version:
get_logger().info(
f"Holding batch {step} until the trainer publishes policy v{required_version} "
f"(currently v{self.policy.version})"
)
hold_start = time.perf_counter()
while True:
self.version_advanced.clear()
if self.policy.version >= required_version:
break
await self.version_advanced.wait()
self.wait_for_policy_time += time.perf_counter() - hold_start
# Stamp each rollout's true staleness: batch ``step`` trains on policy
# v{step-1}, so a rollout generated from v{k} is (step-1)-k versions
# off-policy — queue time included, unlike the dispatcher's in-flight
# counter, which only sees weight updates during generation. Frozen-
# sourced rollouts stay 0 (their sampler doesn't follow the policy).
for r in batch.rollouts:
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
r.off_policy_steps = (step - 1) - r.policy_version
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
# 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
@@ -840,18 +911,16 @@ class Orchestrator:
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
count is ``progress.step - 1``."""
lead = (self.progress.step - 1) - self.policy.version
# The trainer skips the final NCCL weight broadcast (inference group is
# torn down), so policy.version never reaches the last step. Without this
# the gate deadlocks waiting for a version that will never be published.
# The last batch uses the penultimate policy anyway, so let it through.
building_final_batch_nccl = (
self.config.weight_broadcast.type == "nccl"
# The trainer skips the final in-memory weight broadcasts, so policy.version never
# reaches the last step. Let the final batch through instead of waiting for it.
building_final_batch_without_update = (
self.config.weight_broadcast.type in ("nccl", "nixl")
and self.config.max_steps is not None
and self.progress.step >= self.config.max_steps - 1
)
gate = self.dispatcher.dispatch_allowed
was_set = gate.is_set()
if lead > TARGET_LAG and not building_final_batch_nccl:
if lead > TARGET_LAG and not building_final_batch_without_update:
if was_set:
get_logger().info(
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
@@ -867,12 +936,17 @@ class Orchestrator:
gate.set()
async def on_version_pending(self, step: int) -> None:
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
the new policy version is live."""
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
``policy.version`` already carries the new version, so wake a held ship."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
self.version_advanced.set()
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
"""``VersionObserver`` hook: the weight update completed;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.update_dispatch_gate()
async def stop(self) -> None:
+36 -37
View File
@@ -3,15 +3,17 @@
1. ``process_rollout`` — eager per-rollout tokenization (overlaps with
dispatcher producing more rollouts), then the env algorithm's
``finalize_rollout`` (rollout-local scoring + any reference I/O). Errored
rollouts skip this.
2. ``process_group`` — filters errored rollouts, hands survivors to the env
algorithm's ``finalize_group`` (advantages + per-sample wire stamping),
runs the pre-batch filter pass.
and untrainable rollouts skip this.
2. ``process_group`` — filters errored rollouts, hands the trainable
survivors to the env algorithm's ``finalize_group`` (advantages +
per-sample wire stamping), runs the pre-batch filter pass.
3. ``process_batch`` — applies post-batch filter annotations and assembles
the trainer-bound ``TrainingSample`` list. Returns a ``TrainBatch``.
``add()`` returns ``TrainBatch | None``. I/O concerns (ship to trainer,
save_rollouts, monitor.log) live on the orchestrator.
``add()`` takes one episode (``list[Rollout]``) and returns
``TrainBatch | None``; group accounting counts episodes, never loose traces.
I/O concerns (ship to trainer, save_rollouts, monitor.log) live on the
orchestrator.
"""
from __future__ import annotations
@@ -78,6 +80,9 @@ class TrainSink:
# isn't unique — the same task can be re-sampled while an
# earlier group is still in flight
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
# Episodes arrived per group — the finalization count (an episode may
# add several traces to ``pending_groups`` but counts once here).
self.pending_group_episodes: dict[uuid.UUID, int] = defaultdict(int)
self.pending_batch: list[Rollout] = []
# Running payload-token total of ``pending_batch`` (token-batched
# runs), kept in sync on append/pop so the readiness check never
@@ -92,22 +97,6 @@ class TrainSink:
def group_size_for(self, env_name: str) -> int:
return self.train_envs.get(env_name).config.group_size
def in_progress_groups(self) -> list[list[Rollout]]:
"""Per-rollout groups currently accumulating in ``pending_groups`` —
i.e. groups that haven't hit ``group_size`` yet, so the pipeline log
can reflect partial-group progress. Skips group-scoring envs (whose
rollouts only make sense as a unit — the user expects per-group
fill, not per-rollout, for those)."""
out: list[list[Rollout]] = []
for rollouts in self.pending_groups.values():
if not rollouts:
continue
env_name = rollouts[0].env_name
if self.train_envs.get(env_name).requires_group_scoring:
continue
out.append(rollouts)
return out
def batch_progress(self) -> tuple[int, int, str]:
"""``(current, target, unit)`` for the train batch — counts only
``pending_batch`` (survivors of finalized groups, queued for the
@@ -119,9 +108,13 @@ class TrainSink:
return self.pending_tokens, self.token_batch_size, "tokens"
def buffered_count(self) -> int:
"""Rollouts that have arrived but sit in not-yet-complete groups
"""Episodes that have arrived but sit in not-yet-complete groups
(non-group-scoring envs) — buffered in the sink ahead of the batch."""
return sum(len(group) for group in self.in_progress_groups())
return sum(
self.pending_group_episodes.get(group_id, 0)
for group_id, rollouts in self.pending_groups.items()
if rollouts and not self.train_envs.get(rollouts[0].env_name).requires_group_scoring
)
def pending_batch_by_env(self) -> dict[str, int]:
"""Per-env breakdown of ``batch_progress()`` (``pending_batch`` only);
@@ -131,17 +124,20 @@ class TrainSink:
counts[r.env_name] += 1
return dict(counts)
async def add(self, rollout: Rollout) -> TrainBatch | None:
"""Process one arrival; finalize the group on the ``group_size``-th
arrival; return a ``TrainBatch`` if the finalization pushed (or left)
the batch over its threshold. Arrivals into still-incomplete groups
never ship a batch."""
await self.process_rollout(rollout)
env_name = rollout.env_name
self.pending_groups[rollout.group_id].append(rollout)
if len(self.pending_groups[rollout.group_id]) < self.group_size_for(env_name):
async def add(self, episode: list[Rollout]) -> TrainBatch | None:
"""Process one episode arrival; finalize the group on the
``group_size``-th episode; return a ``TrainBatch`` if the finalization
pushed (or left) the batch over its threshold. Arrivals into
still-incomplete groups never ship a batch."""
group_id = episode[0].group_id
env_name = episode[0].env_name
for rollout in episode:
await self.process_rollout(rollout)
self.pending_groups[group_id].extend(episode)
self.pending_group_episodes[group_id] += 1
if self.pending_group_episodes[group_id] < self.group_size_for(env_name):
return None
await self.process_group(rollout.group_id)
await self.process_group(group_id)
# ``pending_batch`` only grows on group finalization, so readiness is
# only re-checked here — the window of a shipped batch then always
# contains at least the group that finalized it.
@@ -158,8 +154,8 @@ class TrainSink:
"""Build training samples from the rollout's Trace (one per branch), walking the
message graph. Training is renderer-only across all modes (RL/OPD student, SFT teacher),
so every node already carries its tokens. Errored rollouts are dropped at the group
level, so skip them here."""
if rollout.has_error:
level, so skip them here; untrainable traces never become training data."""
if rollout.has_error or not rollout.trainable:
return
samples = await asyncio.to_thread(
trace_to_samples,
@@ -178,6 +174,7 @@ class TrainSink:
when ``requires_group_scoring`` and any failed), assign advantages,
run pre-batch filters, append survivors to ``pending_batch``."""
group = self.pending_groups.pop(group_id, [])
self.pending_group_episodes.pop(group_id, None)
if not group:
return
# Window membership follows group finalization, not arrival: a rollout
@@ -200,10 +197,12 @@ class TrainSink:
f"rollouts={len(group)} (errored={num_errored}) | dropped: group-scored partial"
)
return
# Untrainable traces carry no samples and must not skew the group baseline.
survivors = [r for r in survivors if r.trainable]
if not survivors:
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | dropped: all failed"
f"rollouts={len(group)} (errored={num_errored}) | dropped: no trainable survivors"
)
return
+24 -15
View File
@@ -1,14 +1,18 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). A finite env serves a shuffled task-index table, reshuffled on
cursor exhaustion; an infinite env (``num_tasks is None``) streams a
monotonic ``task_idx`` — the server generates tasks on demand, so every
pull is a fresh task and there are no epochs to shuffle."""
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*."""
from __future__ import annotations
import random
from collections.abc import Iterator
import verifiers.v1 as vf
from prime_rl.orchestrator.envs import TrainEnvs
@@ -17,7 +21,8 @@ class TrainSource:
"""``next_example(available_permits)`` picks a weighted-RR env and
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``."""
Returned dicts carry ``env_name`` + ``task_idx`` (+ ``task`` for v1 envs,
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)
@@ -25,22 +30,26 @@ class TrainSource:
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
# A finite env's shuffled index table; ``None`` for an infinite env,
# whose cursor alone is the (monotonic) task_idx stream.
# A finite env's shuffled example table; ``None`` for an infinite env,
# whose generator (``self.iters``) is pulled per example.
self.examples: dict[str, list[dict] | None] = {}
self.iters: dict[str, Iterator[vf.Task]] = {}
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:
# The orchestrator never loads the env: sample over the task-index
# range the server reported via info() (num_tasks; None = infinite).
if env.num_tasks is None:
self.examples[env.name] = None
else:
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
elif env.num_tasks is None: # infinite: pull the generator per example
self.examples[env.name] = 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.cursors[env.name] = 0
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
@@ -53,9 +62,9 @@ class TrainSource:
return None
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if rows is None: # infinite env: the cursor is the task_idx
self.cursors[env_name] = cursor + 1
return {"task_idx": cursor, "env_name": env_name}
if rows is None: # infinite env: pull the next generated task
task = next(self.iters[env_name])
return {"task_idx": task.data.idx, "task": task, "env_name": env_name}
if cursor >= len(rows):
self.rng.shuffle(rows)
cursor = 0
+7 -1
View File
@@ -41,7 +41,7 @@ RolloutKind = Literal["train", "eval"]
@dataclass
class InflightRollout:
"""Per-task scheduling state in the dispatcher; one entry per in-flight
``run_rollout`` / ``run_group`` task."""
``run`` / ``run_group`` task."""
kind: RolloutKind
env_name: str
@@ -63,6 +63,9 @@ class GroupState:
task_idx: int
rollouts_to_schedule: int
target_rollouts: int
task: vf.Task | None = None
"""The group's task (v1 envs — its data is shipped on every dispatch). ``None`` for
legacy envs, which are addressed by ``task_idx`` alone."""
emitted: int = 0
eval_step: int | None = None
pinned_client: vf.ClientConfig | None = None
@@ -88,6 +91,9 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
kind: RolloutKind = Field(default="train", exclude=True)
env_name: str = Field(default="", exclude=True)
group_id: uuid.UUID = Field(default_factory=uuid.uuid4, exclude=True)
# Links the traces of one episode; stamped into ``info`` on arrival so
# saved records keep their grouping.
episode_id: str = Field(default="", exclude=True)
policy_version: int = Field(default=0, exclude=True)
off_policy_steps: int = Field(default=0, exclude=True)
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)

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