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
113 changed files with 1575 additions and 409 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"
+2 -1
View File
@@ -35,7 +35,8 @@ max_completion_tokens = 768
[[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", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt] # Checkpoint at the end of training
+2 -1
View File
@@ -22,7 +22,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", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.model]
seq_len = 16384
+2 -1
View File
@@ -25,7 +25,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+2 -1
View File
@@ -43,7 +43,8 @@ max_completion_tokens = 512
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt] # Checkpoint at the end of training
+2 -1
View File
@@ -24,7 +24,8 @@ group_size = 8
[[orchestrator.train.env]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 1024
+2 -1
View File
@@ -25,7 +25,8 @@ max_completion_tokens = 384
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
@@ -29,7 +29,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
enable_lora = true
@@ -28,7 +28,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
enable_lora = true
@@ -28,7 +28,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
gpu_memory_utilization = 0.7
@@ -17,7 +17,8 @@ max_completion_tokens = 128
[[train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt]
interval = 10
@@ -40,7 +40,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -52,7 +53,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
@@ -46,7 +46,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -58,7 +59,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
@@ -26,7 +26,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference]
@@ -25,7 +25,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
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"
@@ -23,7 +23,8 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer]
+2 -1
View File
@@ -27,7 +27,8 @@ alpha = 0.1
[[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", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 512
+4 -2
View File
@@ -24,7 +24,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -36,7 +37,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+4 -2
View File
@@ -24,7 +24,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -36,7 +37,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+6 -3
View File
@@ -34,12 +34,14 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text-grpo"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.train.env]]
name = "reverse-text-opd"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.env.algo]
type = "opd"
@@ -58,7 +60,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+4 -2
View File
@@ -36,7 +36,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -48,7 +49,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+4 -2
View File
@@ -36,7 +36,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -48,7 +49,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
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
+4 -2
View File
@@ -32,7 +32,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -44,7 +45,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+4 -2
View File
@@ -41,7 +41,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -53,7 +54,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
+4 -2
View File
@@ -41,7 +41,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
@@ -53,7 +54,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[trainer.optim]
lr = 1e-4
+1 -1
+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
+6 -3
View File
@@ -150,19 +150,22 @@ Training environments are an array of tables — set one per env, optionally wit
[[orchestrator.train.env]]
name = "gsm8k"
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
ratio = 3 # 75% of batches
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
ratio = 1 # default — 25% of batches
[[orchestrator.eval.env]]
name = "gsm8k-eval"
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
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.
+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
+5 -4
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 |
@@ -256,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/
@@ -268,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
@@ -281,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
+7 -4
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,7 +95,8 @@ num_turns_weight = 0.0
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.env]]
name = "openseeker"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
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.env.taskset]
id = "openseeker-v1"
@@ -117,7 +118,8 @@ choices = ["A", "B"]
[[orchestrator.train.env]]
name = "redsearcher"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
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.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
@@ -145,7 +147,8 @@ interval = 20
[[orchestrator.eval.env]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.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.env.taskset]
+6 -4
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
@@ -100,7 +100,8 @@ thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
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]
@@ -112,7 +113,8 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
env.agent.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 ---
+7 -4
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,7 +93,8 @@ num_turns_weight = 0.1
[[orchestrator.train.env]]
name = "tmax"
env.agent.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.env.taskset]
id = "tmax-v1"
@@ -120,7 +121,8 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.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.env.taskset]
@@ -143,7 +145,8 @@ id = "swebench-verified-v1"
[[orchestrator.eval.env]]
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.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.env.taskset]
+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 }
+3 -2
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
@@ -99,7 +99,8 @@ extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.env]]
name = "r2e"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
env.agent.harness = { id = "rlm" }
env.agent.runtime = { type = "prime", labels = ["glm5-llmd"] }
[inference]
enable_expert_parallel = true
+2 -1
View File
@@ -74,7 +74,8 @@ interval = 20
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] }
[[orchestrator.post_batch_filters]]
type = "gibberish"
+14 -7
View File
@@ -51,31 +51,36 @@ oversampling_factor = 2
name = "swe"
ratio = 0.3
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe"] }
[[orchestrator.train.env]]
name = "deepdive"
ratio = 0.2
env.taskset = { id = "deepdive-v1" }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
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
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.train.env]]
name = "logic"
ratio = 0.2
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.train.env]]
name = "code"
ratio = 0.2
env.taskset = { id = "i3_code_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
@@ -87,12 +92,14 @@ interval = 25
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] }
[[orchestrator.eval.env]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference.parallel]
tp = 8
+4 -2
View File
@@ -52,7 +52,8 @@ max_off_policy_steps = 16
[[orchestrator.train.env]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe"] }
[orchestrator.eval]
interval = 25
@@ -60,7 +61,8 @@ interval = 25
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] }
[inference.parallel]
tp = 8
+4 -2
View File
@@ -84,7 +84,8 @@ truncate_history_thinking = false
[[orchestrator.train.env]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
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]
@@ -94,7 +95,8 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
env.agent.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]
+5 -3
View File
@@ -51,7 +51,8 @@ max_completion_tokens = 32768
[[orchestrator.train.env]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 25
@@ -59,7 +60,8 @@ interval = 25
[[orchestrator.eval.env]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference.parallel]
tp = 8
tp = 8
+5 -3
View File
@@ -49,7 +49,8 @@ max_off_policy_steps = 16
[[orchestrator.train.env]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] }
[orchestrator.eval]
interval = 25
@@ -57,7 +58,8 @@ interval = 25
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] }
[inference.parallel]
tp = 8
tp = 8
+2 -1
View File
@@ -37,7 +37,8 @@ max_off_policy_steps = 32
[[orchestrator.train.env]]
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
env.agent.harness = { id = "null", runtime = { type = "modal" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "modal" }
[inference]
gpu_memory_utilization = 0.85
+2 -1
View File
@@ -34,6 +34,7 @@ max_completion_tokens = 768
[[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", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference] # Default inference config
+4 -2
View File
@@ -19,7 +19,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", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 50
@@ -27,7 +28,8 @@ interval = 50
[[orchestrator.eval.env]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
group_size = 32
[trainer.model]
+2 -1
View File
@@ -18,7 +18,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
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
+2 -1
View File
@@ -47,7 +47,8 @@ enforce = true
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt] # Checkpoint at the end of training
+2 -1
View File
@@ -21,7 +21,8 @@ group_size = 16
[[orchestrator.train.env]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 1024
@@ -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``.
@@ -190,9 +190,6 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
port: int = 8000
"""Port the router listens on — becomes the client-facing router URL."""
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
@@ -202,9 +199,6 @@ class LlmdRouterConfig(BaseConfig):
type: Literal["llm-d"] = "llm-d"
port: int = 8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers: dict[str, float] = {
"prefix-cache-scorer": 3.0,
"active-request-scorer": 2.0,
@@ -254,12 +248,6 @@ class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
backend_port: int = 8100
"""Port for the per-rank vLLM backend instances."""
router: RouterConfig = VllmRouterConfig()
"""Router fronting the per-rank endpoints."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["single_node"] = "single_node"
@@ -331,6 +319,12 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
router: RouterConfig | None = Field(default_factory=VllmRouterConfig)
"""Router fronting the engine(s). Every deployment runs a single global router as the client-facing endpoint on ``server.port``, with the engines listening on ``backend_port``. Set to ``None`` to run a bare engine on ``server.port`` without a router (the SLURM launchers do this for per-rank engine processes; the sbatch script starts the router)."""
backend_port: int = 8100
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
model: ModelConfig = Field(default_factory=ModelConfig)
parallel: ParallelConfig = ParallelConfig()
@@ -438,8 +432,7 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
if self.router is not None and self.router.type == "llm-d" and self.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
@@ -447,6 +440,21 @@ class InferenceConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_router_deployment(self):
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node":
raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.")
if self.router is None and self.deployment.type in ("multi_node", "disaggregated"):
raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.")
return self
@model_validator(mode="after")
def auto_setup_backend_port(self):
if self.router is not None and "backend_port" not in self.model_fields_set:
self.backend_port = self.server.port + 100
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
@@ -15,12 +15,12 @@ from prime_rl.configs.shared import (
ClientConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
TransportConfig,
WandbWithExtrasConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
@@ -509,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")
@@ -22,6 +22,7 @@ from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
SlurmConfig,
TransportConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
@@ -260,6 +261,8 @@ class RLConfig(BaseConfig):
weight_broadcast: SharedWeightBroadcastConfig | None = None
rollout_transport: TransportConfig | None = None
bench: bool = False
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
@@ -419,6 +422,28 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_rollout_transport(self):
"""Resolve the shared ``rollout_transport`` from the sub-configs so the launcher can
gate multi-node ZMQ host injection on it (mirrors ``auto_setup_weight_broadcast``).
``rollout_transport`` may be set either as the shared block (propagated down to both
sub-configs by ``propagate_shared_fields``) or directly on
``trainer.rollout_transport`` / ``orchestrator.rollout_transport`` (the documented
fallback). Either way the shared field must reflect the resolved per-component
transport, otherwise the launcher would leave ZMQ trainers connecting to localhost.
"""
if self.trainer.rollout_transport.type != self.orchestrator.rollout_transport.type:
raise ValueError(
"trainer.rollout_transport.type "
f"({self.trainer.rollout_transport.type!r}) != orchestrator.rollout_transport.type "
f"({self.orchestrator.rollout_transport.type!r}); set the shared [rollout_transport] "
"block or make both sub-configs the same type."
)
if self.rollout_transport is None:
self.rollout_transport = self.trainer.rollout_transport
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.enable_eplb:
@@ -529,7 +554,7 @@ class RLConfig(BaseConfig):
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = getattr(self.inference.deployment, "router", None)
router = self.inference.router
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
@@ -539,6 +564,12 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_multi_node_requires_router(self):
if self.deployment.type == "multi_node" and self.inference is not None and self.inference.router is None:
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -707,27 +738,27 @@ class RLConfig(BaseConfig):
def auto_setup_inference_client(self):
"""Auto-configure the orchestrator policy client from the inference server config.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there. When no train env samples from
the policy (e.g. sft_distill), also set base_url — policy-sourced
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
When no train env samples from the policy (e.g. sft_distill), set
base_url. Policy-sourced algorithms rely on the ClientConfig default
(``["http://localhost:8000/v1"]``), which already matches the
auto-launched policy router at inference.server.port = 8000.
"""
if self.inference is None:
return self
client = self.orchestrator.model.client
if "dp_rank_count" not in client.model_fields_set:
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
if (
self.deployment.type == "single_node"
and self.inference.router is not None
and "admin_base_url" not in client.model_fields_set
):
# Admin ops (pause/update_weights/resume) must bypass the router and hit
# the engine directly; multi-node runs get ADMIN_URLS from the sbatch.
host = self.inference.server.host or "localhost"
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
return self
@model_validator(mode="after")
@@ -322,8 +322,6 @@ class SFTConfig(BaseConfig):
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
if self.model.cp > 1 and self.model.cp_style != "ulysses":
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
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:
@@ -141,9 +141,6 @@ class ClientConfig(BaseConfig):
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
dp_rank_count: int = Field(1, ge=1)
"""Number of data-parallel ranks behind each base URL. When > 1, each URL is expanded into ``dp_rank_count`` logical clients pinned via the ``X-data-parallel-rank`` header, so every request within a rollout hits the same DP engine and reuses KV cache. Auto-set from the inference config when using the RL entrypoint."""
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
@@ -8,12 +8,12 @@ from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
@@ -242,6 +242,12 @@ class ModelConfig(BaseModelConfig):
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"]:
@@ -576,7 +582,7 @@ class TrainerConfig(BaseConfig):
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to broadcast updated weights from trainer to inference."""
rollout_transport: TransportConfig = FileSystemTransportConfig()
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
log: TrainerLogConfig = TrainerLogConfig()
@@ -126,6 +126,9 @@ def propagate_shared_fields(data: Any) -> Any:
"inference.model.chat_template",
)
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
# Top-level scalars.
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
+3 -2
View File
@@ -44,7 +44,8 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
```
CLI: `--orchestrator.train.env.0.env.taskset.id reverse-text-v1`.
@@ -53,7 +54,7 @@ CLI: `--orchestrator.train.env.0.env.taskset.id reverse-text-v1`.
**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
+3 -3
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)
```
@@ -154,7 +154,7 @@ jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
```
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
### Common failure modes
+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,
+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
+11 -6
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
+35 -1
View File
@@ -176,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 = []
@@ -602,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
@@ -905,11 +936,14 @@ class Orchestrator:
gate.set()
async def on_version_pending(self, step: int) -> None:
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
``policy.version`` already carries the new version, so wake a held ship."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
self.version_advanced.set()
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the 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)
+13 -2
View File
@@ -64,6 +64,12 @@ class WeightWatcher:
async def stop(self) -> None:
self.stopped.set()
# Let an in-flight apply finish before dying: the trainer blocks inside
# its in-memory broadcast until the apply completes, so cancelling
# mid-apply would strand it. The orchestrator's global teardown budget
# bounds this wait.
async with self.update_lock:
pass
if self.task is not None:
await safe_cancel(self.task)
self.task = None
@@ -103,6 +109,13 @@ class WeightWatcher:
await wait_for_path(stable_marker)
self.last_wait_for_ckpt_time = time.perf_counter() - t0
# Publish confirmed: the policy version advances here, before the
# apply — inference pauses during the update, so nothing can generate
# under the new number from the old weights, and a ship held on this
# version releases without waiting out the inference weight reload.
self.ckpt_step = next_step
self.policy.version = next_step
# Drain off-policy rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
# ``_reqs_not_processed``), which is only propagated to the workers
@@ -128,8 +141,6 @@ class WeightWatcher:
self.update_count += 1
get_logger().debug(f"Updated weights to step {next_step} in {format_time(self.last_update_weights_time)}")
self.ckpt_step = next_step
self.policy.version = next_step
if self.lora_name is not None:
self.inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
+34 -18
View File
@@ -1,21 +1,23 @@
{# Shared router launch helper, included once per template and called by the
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
chosen here via router.type, so the call sites stay router-agnostic.
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
{# Shared launch helper for the single global router, included once per template
and called by inference node 0. The router backend (vllm-router vs llm-d
EPP+Envoy) is chosen here via router.type, so the call sites stay
router-agnostic. llm-d endpoint discovery enumerates every inference node:
all nodes for regular mode; for disaggregated mode all prefill nodes across
replicas, then all decode nodes (matching the logical node order in
endpoints.yaml). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log>
launch_router() {
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5"
{%- if router.type == "llm-d" %}
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port" | tee "$log"
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd"
mkdir -p "$LLMD_DIR"
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if is_disaggregated %}
{%- set ep_disaggregated = true %}
{%- set ep_num_prefill = num_prefill_nodes %}
{%- set ep_num_decode = num_decode_nodes %}
{%- set ep_num_prefill = num_prefill_nodes * (num_infer_replicas | default(1)) %}
{%- set ep_num_decode = num_decode_nodes * (num_infer_replicas | default(1)) %}
{%- set ep_dp = dp_per_node %}
{%- set ep_prefill_port = prefill_port %}
{%- set ep_sidecar_port = router.decode_sidecar_port %}
@@ -25,12 +27,22 @@ LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local node=0 ip
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
local node=0 ip reps=${NUM_INFER_REPLICAS:-1} span=${NODES_PER_INFER_REPLICA:-$((NUM_PREFILL_NODES + NUM_DECODE_NODES))}
for ((rr=0; rr<reps; rr++)); do
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
ip=$(getent hosts "${HOSTNAMES[$((rr * span + p))]}" | awk "{print \$1}")
sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1))
done
done
for ((rr=0; rr<reps; rr++)); do
for ((d=0; d<NUM_DECODE_NODES; d++)); do
ip=$(getent hosts "${HOSTNAMES[$((rr * span + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}")
sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1))
done
done
{%- else %}
{%- set ep_disaggregated = false %}
{%- set ep_num_nodes = infer_nodes_per_replica %}
{%- set ep_num_nodes = num_infer_nodes | default(num_nodes) %}
{%- set ep_dp = dp_per_node %}
{%- set ep_backend_port = backend_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
@@ -40,13 +52,16 @@ LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local ip
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
for ((n=0; n<{{ ep_num_nodes }}; n++)); do
ip=$(getent hosts "${HOSTNAMES[$n]}" | awk "{print \$1}")
sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"
done
{%- endif %}
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
{% include 'llmd/envoy.yaml.j2' %}
LLMD_EOF
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
# shares node 0 with the EPP, so 9003 would fail to bind and kill the EPP.
epp --pool-name prime-rl --pool-namespace slurm \
--config-file "$LLMD_DIR/epp.yaml" \
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
@@ -55,9 +70,10 @@ LLMD_EOF
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
{%- else %}
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
echo "Starting $tag on $LOCAL_IP:$port" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
--request-id-headers x-session-id
--prometheus-port "$((port + 21000))"
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
cmd+=(--vllm-pd-disaggregation $worker_args)
+21 -30
View File
@@ -38,13 +38,13 @@ export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
export ROUTER_PORT={{ router.port }}
export ROUTER_PORT={{ router_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- elif num_nodes > 1 %}
export ROUTER_PORT={{ router.port }}
export ROUTER_PORT={{ router_port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- endif %}
@@ -77,32 +77,24 @@ uv sync --all-extras --all-packages
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if is_disaggregated -%}
# Build per-replica router URLs
INFER_URLS=""
ALL_ROUTER_ARGS=""
for ((r=0; r<NUM_NODES/NODES_PER_REPLICA; r++)); do
replica_base=$((r * NODES_PER_REPLICA))
router_host="${HOSTNAMES[$replica_base]}"
INFER_URLS="${INFER_URLS:+$INFER_URLS,}http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
host="${HOSTNAMES[$((replica_base + p))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
# Single global router on node 0 fronts every per-rank endpoint.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
ROUTER_ARGS=""
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
host="${HOSTNAMES[$p]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
ROUTER_ARGS="$ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
host="${HOSTNAMES[$((replica_base + NUM_PREFILL_NODES + d))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
host="${HOSTNAMES[$((NUM_PREFILL_NODES + d))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
ROUTER_ARGS="$ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
export INFER_URLS
export ALL_ROUTER_ARGS
export ROUTER_ARGS
{%- elif num_nodes > 1 %}
# External LB: one router on node 0; one endpoint per DP rank (BACKEND_PORT + dp_local) on every node.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
@@ -273,10 +265,9 @@ srun --kill-on-bad-exit=1 bash -c '
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
# Start the single global router on node 0 (external LB across all per-rank endpoints)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
@@ -318,9 +309,9 @@ srun --kill-on-bad-exit=1 bash -c '
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
# Start the single global router on node 0 (balances across per-rank endpoints — no intra-node DP header)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
+1 -1
View File
@@ -7,7 +7,7 @@ admin:
static_resources:
listeners:
- name: prime_rl
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
address: { socket_address: { address: 0.0.0.0, port_value: {{ router_port }} } }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
+26 -41
View File
@@ -32,7 +32,7 @@ export NODES_PER_INFER_REPLICA={{ nodes_per_infer_replica }}
export NUM_INFER_REPLICAS={{ num_infer_replicas }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if num_infer_nodes > 0 -%}
export ROUTER_PORT={{ router.port }}
export ROUTER_PORT={{ router_port }}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
@@ -75,58 +75,43 @@ export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if num_infer_nodes > 0 -%}
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
# Build per-replica router URLs, admin URLs, and backend args for the router
INFER_URLS=""
# Single global router on inference node 0 fronts every per-rank endpoint;
# admin URLs bypass it and hit each rank directly.
INFER_URLS="http://${INFER_HOSTS[0]}:${ROUTER_PORT}/v1"
ADMIN_URLS=""
ALL_ROUTER_ARGS=""
ROUTER_ARGS=""
{% if is_disaggregated -%}
# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node.
for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
replica_base=$((r * NODES_PER_INFER_REPLICA))
router_host="${INFER_HOSTS[$replica_base]}"
INFER_URLS="${INFER_URLS:+$INFER_URLS }http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
node_idx=$((replica_base + p))
host="${INFER_HOSTS[$node_idx]}"
host="${INFER_HOSTS[$((replica_base + p))]}"
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((PREFILL_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
ROUTER_ARGS="$ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
host="${INFER_HOSTS[$node_idx]}"
host="${INFER_HOSTS[$((replica_base + NUM_PREFILL_NODES + d))]}"
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((DECODE_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
ROUTER_ARGS="$ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
{%- else -%}
for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
head_idx=$((r * NODES_PER_INFER_REPLICA))
router_host="${INFER_HOSTS[$head_idx]}"
INFER_URLS="${INFER_URLS:+$INFER_URLS }http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
for ((n=0; n<NODES_PER_INFER_REPLICA; n++)); do
node_idx=$((head_idx + n))
host="${INFER_HOSTS[$node_idx]}"
# External-LB: one endpoint per DP rank (BACKEND_PORT + dp_local) on each node.
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:$((BACKEND_PORT + k))"
done
# External-LB: one endpoint per DP rank (BACKEND_PORT + dp_local) on each node.
for ((n=0; n<NUM_INFER_NODES; n++)); do
host="${INFER_HOSTS[$n]}"
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + k))/v1"
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + k))"
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
{%- endif %}
export INFER_URLS
export ADMIN_URLS
export ALL_ROUTER_ARGS
export ROUTER_ARGS
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
echo "INFER_URLS=${INFER_URLS}"
echo "ADMIN_URLS=${ADMIN_URLS}"
@@ -310,10 +295,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
| tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
# Start the single global router on inference node 0 (PD mode, external LB across all per-rank endpoints)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
@@ -348,10 +332,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
done
{%- else -%}
# Start the router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$((REPLICA_IDX * NODES_PER_INFER_REPLICA))" "$NODES_PER_INFER_REPLICA"
# Start the single global router on inference node 0 (external LB across all per-rank endpoints)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
@@ -407,7 +390,8 @@ else
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.toml \
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
{% if use_zmq_transport %}--rollout_transport.host $MASTER_ADDR \
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
{% if num_infer_nodes > 0 %} fi{% endif %}
{% if num_infer_nodes > 0 %}
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
@@ -426,6 +410,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
{%- endfor %}
{%- endif %}
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $MASTER_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
fi
+67 -20
View File
@@ -94,11 +94,25 @@ def _truncate_mm(
return cut, sliced
def multimodal_sample_error(sample: TrainingSample) -> str | None:
mm_token_type_ids = sample.mm_token_type_ids
if mm_token_type_ids is not None and len(mm_token_type_ids) != len(sample.token_ids):
return (
"mm_token_type_ids length must match token_ids length "
f"({len(mm_token_type_ids)} != {len(sample.token_ids)})"
)
if sample.mm_kwargs is not None and "image_grid_thw" in sample.mm_kwargs and mm_token_type_ids is None:
return "image_grid_thw multimodal samples require mm_token_type_ids"
return None
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
"""
Prepare a problem for sequence packing training.
Tokenize and prepare tensors.
"""
if error := multimodal_sample_error(training_example):
raise ValueError(error)
input_ids = training_example.token_ids
loss_mask = training_example.mask
inference_logprobs = training_example.logprobs
@@ -186,10 +200,6 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
)
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
if mm_token_type_ids is not None:
assert len(mm_token_type_ids) == len(input_ids), (
f"mm_token_type_ids: {len(mm_token_type_ids)}, input_ids: {len(input_ids)}"
)
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
return MicroBatch(
@@ -230,17 +240,45 @@ class _MicroBatchBin:
def first_sample(self) -> MicroBatch:
return self.samples[0][1]
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
@property
def first_lora_idx(self) -> int:
return self.samples[0][0]
@property
def first_multimodal_sample(self) -> MicroBatch | None:
for _, sample in self.samples:
if _is_multimodal_sample(sample):
return sample
return None
def can_add(self, sample: MicroBatch, max_seq_len: int, lora_idx: int) -> bool:
# Loss routing is per token (component weight streams), so samples of
# different loss types pack together freely — only modality, length and
# routed-experts presence constrain packing.
# different loss types pack together freely. Multimodal packing is still
# constrained by modality sidecars, length, routed experts, and LoRA/run.
first_sample = self.first_sample
return (
not _is_multimodal_sample(first_sample)
and not _is_multimodal_sample(sample)
and self.length + len(sample.input_ids) <= max_seq_len
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
)
if self.length + len(sample.input_ids) > max_seq_len:
return False
if (first_sample.routed_experts is None) != (sample.routed_experts is None):
return False
sample_is_mm = _is_multimodal_sample(sample)
existing_mm_sample = self.first_multimodal_sample
if existing_mm_sample is None and not sample_is_mm:
return True
if self.first_lora_idx != lora_idx:
return False
if existing_mm_sample is not None and sample_is_mm:
dst = existing_mm_sample.mm_kwargs
src = sample.mm_kwargs
assert dst is not None and src is not None, "multimodal samples must carry mm_kwargs"
return set(dst) == set(src) and all(
dst[key].dtype == src[key].dtype
and len(dst[key].shape) > 0
and len(dst[key].shape) == len(src[key].shape)
and dst[key].shape[1:] == src[key].shape[1:]
for key in dst
)
return True
def add(self, lora_idx: int, sample: MicroBatch) -> None:
self.samples.append((lora_idx, sample))
@@ -285,6 +323,7 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
env_names: list[str] = []
ref_logprobs: list[float] | None = [] if has_ref_logprobs else None
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
mm_kwargs: dict[str, EncodedTensor] | None = None
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
seq_lens: list[int] = []
routed_experts: RoutedExperts | None = None
@@ -318,13 +357,19 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
routed_experts.data += sample.routed_experts.data
routed_experts.shape[0] += sample.routed_experts.shape[0]
if sample.mm_kwargs is not None:
if mm_kwargs is None:
mm_kwargs = copy.deepcopy(sample.mm_kwargs)
else:
for key in mm_kwargs:
mm_kwargs[key].data += sample.mm_kwargs[key].data
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
seq_lens.extend(sample.seq_lens)
lora_num_tokens[lora_idx] += sample_len
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
assert sum(seq_lens) == len(input_ids), (seq_lens, len(input_ids))
first_sample = bin_content.first_sample
return MicroBatch(
input_ids=input_ids,
@@ -339,7 +384,7 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
mm_kwargs=mm_kwargs,
rl_weights=streams["rl_weights"],
ce_weights=streams["ce_weights"],
ref_kl_weights=streams["ref_kl_weights"],
@@ -354,7 +399,7 @@ def _expand_bins_by_splitting(
candidates = [
(bin_content.workload(bin_cost), idx)
for idx, bin_content in enumerate(bins)
if len(bin_content.samples) > 1
if len(bin_content.samples) > 1 and bin_content.first_multimodal_sample is None
]
if not candidates:
break
@@ -376,8 +421,9 @@ def packed_samples_into_micro_bs(
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
With per-token temperatures, samples can be packed together regardless of their temperature values.
NOTE: Multimodal samples (with mm_kwargs) are NOT packed together as they have variable-sized
vision data that doesn't pack well. Each multimodal sample becomes its own micro batch.
Multimodal samples pack with text spans from the same run/LoRA and with
compatible eager ``mm_kwargs`` samples. Packed batches preserve sample
boundaries in ``seq_lens``.
"""
# Sort by (lora_idx, -length) for packing efficiency
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
@@ -385,9 +431,10 @@ def packed_samples_into_micro_bs(
bins: list[_MicroBatchBin] = []
for idx, sample in samples:
# Try to find a bin that can fit this sequence (only pack text-only samples)
# Try to find a bin that can fit this sequence. Multimodal samples only
# pack when their sidecar tensors are compatible.
for bin_content in bins:
if bin_content.can_add(sample, max_seq_len):
if bin_content.can_add(sample, max_seq_len, idx):
bin_content.add(idx, sample)
break
else:
+5 -2
View File
@@ -937,7 +937,10 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
model_keys = dict.fromkeys(model.state_dict().keys())
if model.is_hf_state_dict(snapshot_keys) and model.is_prime_state_dict(model_keys):
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
if snapshot_is_hf and not snapshot_is_prime and model.is_prime_state_dict(model_keys):
logger.warning(
"Found HF weight format in snapshot state dict and PrimeRL weight format in model state dict. Trying to auto-convert..."
)
@@ -951,7 +954,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
save_state_dict(snapshot_state_dict, snapshot_path)
del snapshot_state_dict
elif model.is_prime_state_dict(snapshot_keys) and model.is_hf_state_dict(model_keys):
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
logger.warning(
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
)
@@ -124,8 +124,10 @@ class LlamaPreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
"""Check if the state dict is in PrimeRL training format."""
return True
# Dense models use identical key names in HF and PrimeRL format, so we
# never claim to be in a separate PrimeRL format. This disables the
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
return False
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -107,7 +107,10 @@ class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
# Dense models use identical key names in HF and PrimeRL format, so we
# never claim to be in a separate PrimeRL format. This disables the
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
return False
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -160,7 +160,10 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
# Dense models use identical key names in HF and PrimeRL format, so we
# never claim to be in a separate PrimeRL format. This disables the
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
return False
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -371,6 +374,7 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
self._is_vlm = hasattr(config, "vision_config")
self.supports_packed_multimodal_training = self._is_vlm
if self._is_vlm:
self.model = Qwen3_5VLMModel(config)
@@ -892,6 +892,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
self._is_vlm = hasattr(config, "vision_config")
self.supports_packed_multimodal_training = self._is_vlm
if self._is_vlm:
self.model = Qwen3_5MoeVLMModel(config)
@@ -92,9 +92,10 @@ def is_view_of(value: torch.Tensor, root: torch.Tensor) -> bool:
def plan_tensor_replay(shape: tuple[int, ...], dtype: torch.dtype, ops: OperationChain) -> TensorReplayPlan:
"""Resolve a directly transferable source view and local replay suffix.
The prefix must remain a same-dtype view of the trainer root and can
therefore be addressed by RDMA. The first materializing or dtype-changing
operation and everything after it is replayed on the receive arena.
The prefix must remain a contiguous, same-dtype view of the trainer root
and can therefore be transferred in large RDMA runs. The first strided,
materializing, or dtype-changing operation and everything after it is
replayed on the receive arena.
"""
root = torch.empty(shape, dtype=dtype, device="meta")
prefix_len = 0
@@ -105,7 +106,7 @@ def plan_tensor_replay(shape: tuple[int, ...], dtype: torch.dtype, ops: Operatio
if candidate_len < len(ops) and ops[candidate_len].name == "tuple_getitem":
continue
candidate = apply_chain(root, ops[:candidate_len])
if candidate.dtype != dtype or not is_view_of(candidate, root):
if candidate.dtype != dtype or not is_view_of(candidate, root) or not candidate.is_contiguous():
break
prefix_len = candidate_len
source_view = candidate
+3 -1
View File
@@ -6,7 +6,7 @@ from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Callable, Sequence
from prime_rl.trainer.batch import prepare_batch
from prime_rl.trainer.batch import multimodal_sample_error, prepare_batch
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.transport import (
MicroBatch,
@@ -177,6 +177,8 @@ class MultiPacker(BasePacker):
False,
f"Run wrote a sample with ref logprobs length != sample length ({len(sample.ref_logprobs)} != {sample_length})",
)
if error := multimodal_sample_error(sample):
return False, error
return True, None
def _get_batch(self) -> None:
+7 -1
View File
@@ -10,6 +10,7 @@ from torch import Tensor
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
from prime_rl.utils.logger import get_logger
SCHEMA_VERSION = 1
@@ -93,7 +94,12 @@ class TokenExporter:
ready_run_ids = ready_run_ids or set()
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
for stable_dir in self._pending_stable_dirs.pop(run_id):
(stable_dir / "STABLE").touch()
try:
(stable_dir / "STABLE").touch()
except FileNotFoundError:
# A multi-run run dir can be deleted while its tail steps are
# still flushing (mirrors the broadcast paths' guard)
get_logger().warning(f"Run dir for {run_id} is deleted, skipping token-export STABLE marker")
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
if run_id is not None:
+26 -18
View File
@@ -154,6 +154,9 @@ def train(config: TrainerConfig):
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
logger.info(f"Setting up loss function ({config.loss})")
rl_loss_fn = setup_rl_loss_fn(config.loss)
@@ -368,6 +371,11 @@ def train(config: TrainerConfig):
# tensor to CUDA and let the model's forward sort them.
mm_kwargs_raw = micro_batch.get("mm_kwargs")
mm_kwargs = {k: v.to("cuda") for k, v in mm_kwargs_raw.items()} if mm_kwargs_raw else None
if mm_kwargs is not None and config.model.vlm is None:
raise ValueError(
"Received multimodal samples but [model.vlm] is not set. "
"Set [model.vlm] to train on multimodal samples."
)
mm_token_type_ids = (
micro_batch["mm_token_type_ids"].to("cuda")
if micro_batch.get("mm_token_type_ids") is not None
@@ -378,30 +386,30 @@ def train(config: TrainerConfig):
labels = shift_tensor_left(input_ids)
# VLM + CP is not supported: MRoPE requires global positions but CP shards the sequence
if cp_enabled and mm_kwargs is not None:
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
seq_lens_are_pre_shard = False
if cp_enabled:
input_ids, forward_position_ids = setup_cp_params(
input_ids,
position_ids,
cp_rank,
cp_size,
cp_group,
seq_lens=seq_lens,
cp_style=config.model.cp_style,
)
# MRoPE batches must merge image embeddings before sharding.
defer_vlm_cp_to_model = mm_kwargs is not None and "image_grid_thw" in mm_kwargs
if not defer_vlm_cp_to_model:
input_ids, position_ids = setup_cp_params(
input_ids,
position_ids,
cp_rank,
cp_size,
cp_group,
seq_lens=seq_lens,
cp_style=config.model.cp_style,
)
seq_lens_are_pre_shard = True
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
if routed_experts is not None:
if routed_experts is not None and not defer_vlm_cp_to_model:
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
else:
forward_position_ids = position_ids
if config.model.lora:
lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda")
if cp_enabled:
chunk_size = input_ids.shape[1]
chunk_size = labels.shape[1]
# Convert to cumsum, adjust for CP chunk, convert back to num_tokens
cu_offsets = lora_num_tokens.cumsum(dim=0, dtype=torch.int32)
adjusted_cu = torch.clip(cu_offsets - chunk_size * cp_rank, min=0, max=chunk_size)
@@ -421,13 +429,13 @@ def train(config: TrainerConfig):
out = forward(
model,
input_ids,
forward_position_ids,
position_ids,
labels=labels,
temperature=temperatures,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
seq_lens=seq_lens,
seq_lens_are_pre_shard=cp_enabled,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
routed_experts=routed_experts,
)
+22 -19
View File
@@ -10,7 +10,7 @@ from typing import Protocol, runtime_checkable
import httpx
import verifiers.v1 as vf
from httpx import AsyncClient
from openai import AsyncOpenAI, NotFoundError
from openai import AsyncOpenAI
from renderers import RendererConfig
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from verifiers.v1.clients.config import EvalClientConfig, TrainClientConfig
@@ -18,15 +18,12 @@ from verifiers.v1.clients.config import EvalClientConfig, TrainClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
# Identity tuple used by ``select_train_client`` to key load counts. ``base_url``
# distinguishes servers; ``X-data-parallel-rank`` distinguishes DP shards within a
# server, since the router uses that header to route to specific GPU ranks.
ClientIdentity = tuple[str, str | None]
ClientIdentity = str
def client_identity(client: vf.ClientConfig) -> ClientIdentity:
"""Stable identity for load balancing across inference clients."""
return (client.base_url, client.headers.get("X-data-parallel-rank"))
return client.base_url
@runtime_checkable
@@ -137,6 +134,13 @@ class StaticInferencePool:
)
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
self._admin_clients = setup_admin_clients(client_config)
# When admin URLs bypass a router, also health-check the client-facing
# (router) endpoint - it only starts serving once its workers are healthy.
self._router_clients = (
setup_admin_clients(client_config.model_copy(update={"admin_base_url": None}))
if client_config.admin_base_url
else []
)
self._skip_model_check = client_config.skip_model_check
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
self._eval_cycle = cycle(self._eval_clients)
@@ -168,7 +172,8 @@ class StaticInferencePool:
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
await check_health(
self._admin_clients, timeout=timeout if timeout is not None else self._wait_for_ready_timeout
self._admin_clients + self._router_clients,
timeout=timeout if timeout is not None else self._wait_for_ready_timeout,
)
await maybe_check_has_model(self._admin_clients, model_name, skip_model_check=self._skip_model_check)
@@ -222,7 +227,7 @@ def setup_clients(
renderer_model_name: str | None = None,
pool_size: int | None = None,
) -> list[vf.ClientConfig]:
"""Build v1 client configs (one per base_url × DP rank). ``client_type``
"""Build one v1 client config per base URL. ``client_type``
``renderer`` → token-in/out (``TrainClientConfig``, with the renderer the env
server should use forwarded as a serialized config so it doesn't fall back to the
default renderer); otherwise plain chat-completions (``EvalClientConfig``)."""
@@ -240,13 +245,10 @@ def setup_clients(
}
clients: list[vf.ClientConfig] = []
for base_url in client_config.base_url:
for dp_rank in range(client_config.dp_rank_count):
headers = {**client_config.headers, **env_headers}
if client_config.dp_rank_count > 1:
headers["X-data-parallel-rank"] = str(dp_rank)
clients.append(
config_cls(base_url=base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra)
)
headers = {**client_config.headers, **env_headers}
clients.append(
config_cls(base_url=base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra)
)
return clients
@@ -306,12 +308,13 @@ async def check_health(
logger.debug("Starting pinging /health to check health")
while wait_time < timeout:
try:
await admin_client.get("/health")
response = await admin_client.get("/health")
if response.status_code == 404:
logger.warning("The route /health does not exist. Skipping health check.")
return
response.raise_for_status()
logger.debug(f"Inference pool is ready after {wait_time} seconds")
return
except NotFoundError:
logger.warning("The route /health does not exist. Skipping health check.")
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.warning(
-1
View File
@@ -203,7 +203,6 @@ class ElasticInferencePool:
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
headers_from_env=self.client_config.headers_from_env,
dp_rank_count=self.client_config.dp_rank_count,
extra_headers_from_state=self.client_config.extra_headers_from_state,
)
self._train_clients = (
+27 -18
View File
@@ -298,8 +298,9 @@ class WandbMonitor(Monitor):
OVERVIEW_NAME = "overview"
# Per-rollout metrics (under "<scope>/all/") shown for BOTH train and eval. Only the reward metric
# differs — train uses "reward/mean", eval uses "avg@k" — and each section builder prepends its own.
# Per-rollout metrics (under "<scope>/all/") shown for BOTH train and eval. Only the reward metrics
# differ — train uses "reward/mean", eval uses "avg@k", each shown for the all and effective
# subsets — and each section builder prepends its own.
COMMON_METRICS = [
"has_error/mean",
"is_truncated/mean",
@@ -328,10 +329,11 @@ ROWS = 6
def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LinePlot]:
# inference/* is logged against wall time (step_metric="_timestamp") → "WallTime" (== W&B's
# "_timestamp"); everything else on "step" (prime-rl's logged training step, not internal "Step").
# inference/* is logged against time (step_metric="_timestamp"), plotted on "RelativeTime(Wall)"
# (== W&B's "_absolute_runtime", seconds since run start) so runs started at different times
# overlay; everything else on "step" (prime-rl's logged training step, not internal "Step").
# x is set per-panel because LinePlot defaults it to "Step", which overrides the workspace x_axis.
return [wr.LinePlot(x="WallTime" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
return [wr.LinePlot(x="RelativeTime(Wall)" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
wr.LinePlot(x="step", metric_regex=r) for r in regexes
]
@@ -346,15 +348,20 @@ def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ())
def train_section(name: str, scope: str) -> ws.Section:
return section(name, metrics=[f"{scope}/all/reward/mean"] + [f"{scope}/all/{m}" for m in COMMON_METRICS])
return section(
name,
metrics=[f"{scope}/all/reward/mean", f"{scope}/effective/reward/mean"]
+ [f"{scope}/all/{m}" for m in COMMON_METRICS],
)
def eval_section(name: str, env_pattern: str) -> ws.Section:
# Same metrics as train, but eval's reward is "avg@k" (dynamic k → regex). Everything is a regex so
# one section can also serve any env (env_pattern=".*"). Only the "all" subset, like train.
# one section can also serve any env (env_pattern=".*").
return section(
name,
regexes=[f"eval/{env_pattern}/all/avg@.*"] + [f"eval/{env_pattern}/all/{m}" for m in COMMON_METRICS],
regexes=[f"eval/{env_pattern}/all/avg@.*", f"eval/{env_pattern}/effective/avg@.*"]
+ [f"eval/{env_pattern}/all/{m}" for m in COMMON_METRICS],
)
@@ -395,15 +402,16 @@ def list_views(entity: str, project: str) -> list[tuple[str, str]]:
return [(e["node"]["displayName"], e["node"]["name"]) for e in edges if e.get("node")]
def env_signature(train_envs: Sequence[str], eval_envs: Sequence[str]) -> tuple:
return (tuple(sorted(train_envs)), tuple(sorted(eval_envs)))
def view_env_signature(sections: Sequence[ws.Section]) -> tuple:
"""Reconstruct the ``(train, eval)`` env set a view was built for from its section names."""
def view_signature(sections: Sequence[ws.Section]) -> tuple:
train = sorted(s.name[len("train/") :] for s in sections if s.name.startswith("train/") and s.name != "train/agg")
evals = sorted(s.name[len("eval/") :] for s in sections if s.name.startswith("eval/"))
return (tuple(train), tuple(evals))
panels = {
(getattr(p.x, "name", p.x), tuple(getattr(m, "name", m) for m in p.y or ()), p.metric_regex)
for s in sections
for p in s.panels
if isinstance(p, wr.LinePlot)
}
return (tuple(train), tuple(evals), tuple(sorted(panels, key=str)))
def next_overview_name(base: str, existing: Sequence[str]) -> str:
@@ -424,13 +432,14 @@ def ensure_overview_view(
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
target = env_signature(train_envs, eval_envs)
sections = build_sections(train_envs, eval_envs)
target = view_signature(sections)
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
for _, internal_name in overviews:
slug = internal_name.removeprefix("nw-").removesuffix("-v")
try:
existing = ws.Workspace.from_url(f"https://wandb.ai/{entity}/{project}?nw={slug}")
matches = view_env_signature(existing.sections) == target
matches = view_signature(existing.sections) == target
except Exception as e:
# A single unreadable view must not abort reuse detection / versioning for the rest.
get_logger().warning(f"Could not inspect overview view {internal_name} - {e}")
@@ -441,7 +450,7 @@ def ensure_overview_view(
entity=entity,
project=project,
name=next_overview_name(name, [dn for dn, _ in overviews]),
sections=build_sections(train_envs, eval_envs),
sections=sections,
auto_generate_panels=False,
settings=ws.WorkspaceSettings(x_axis="step"),
)
+2 -3
View File
@@ -1,5 +1,4 @@
import os
import shutil
import signal
import socket
import subprocess
@@ -74,11 +73,11 @@ def branch_name() -> str:
@pytest.fixture(scope="session")
def output_dir(tmp_path_factory: pytest.TempPathFactory) -> Generator[Path, None, None]:
"""Fixture for temporary output directory for tests with automatic cleanup"""
"""Fixture for the tests' output directory. Never deleted — CI uploads run logs
from it on failure; runs start with ``--clean-output-dir`` for a fresh workspace."""
output_dir = Path(os.environ.get("PYTEST_OUTPUT_DIR", tmp_path_factory.mktemp("outputs")))
output_dir.mkdir(parents=True, exist_ok=True)
yield output_dir
shutil.rmtree(output_dir, ignore_errors=True)
@pytest.fixture(scope="session")
+1
View File
@@ -38,6 +38,7 @@ def rl_process(
"rl",
"@",
"configs/ci/integration/alphabet_sort.toml",
"--clean-output-dir",
"--wandb.project",
wandb_project,
"--wandb.name",

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