Compare commits

...
Author SHA1 Message Date
JannikStandGitHub 4df5b6229f fix: probe github ssh auth directly in install.sh (#2613)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: probe github ssh auth directly in install.sh

The previous `has_ssh_access` probe ran `git ls-remote` against the
public prime-rl repo, which can return success under SSH connection
multiplexing, cached creds, or other states without the local key
actually being registered with a GitHub user. When that happens, the
HTTPS `insteadOf` rewrite is never applied and private-submodule
clones fail with "Permission denied (publickey)".

Use `ssh -T git@github.com` and grep for the canonical
"successfully authenticated" string instead. This is a direct check
of the precondition (your key is registered with a GitHub user) and
matches the pattern git itself recommends.

* fix: capture ssh output to var so pipefail doesn't mask success

`ssh -T git@github.com` always exits 1 (GitHub denies shell access
after authenticating), and install.sh has `set -o pipefail` at the
top, so the previous pipeline made has_ssh_access return failure even
for developers with valid keys. Capture stdout/stderr into a variable
first, then grep — keeps pipefail intact for the rest of the script.

* fix: use universal ssh options in github auth probe

`StrictHostKeyChecking=accept-new` requires OpenSSH 7.6+ (Sep 2017).
On older systems ssh errors with 'Bad configuration option' and the
probe wrongly reports no SSH auth, forcing HTTPS even when SSH would
have worked.

Use `StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null`
instead, which works on all OpenSSH versions. Safe for a probe-only
flow: no key material is exchanged, and a hostile MITM at worst
makes the probe wrongly report 'no SSH', causing HTTPS fallback for
public repos.

* fix: rely on ensure_known_hosts and default ssh host key checking

Previous commit disabled `StrictHostKeyChecking` and `UserKnownHostsFile`
to side-step OpenSSH version requirements, but that made the auth probe
trust any host that returns the "successfully authenticated" string —
a MITM could steer the script into using their SSH for submodule
clones.

`ensure_known_hosts` already runs (line 116) before any
`has_ssh_access` call and populates github.com via ssh-keyscan, so
default host key checking is both safe and sufficient. Drop the
options entirely; keep `BatchMode=yes` to suppress prompts.

* fix: propagate insteadOf to submodule clones via GIT_CONFIG_* env

`git submodule--helper clone` spawns fresh `git clone` processes
that read only ~/.gitconfig and env vars — not the parent repo's
local .git/config. So setting `url..insteadOf` locally never reached
the submodule clones, and they kept attempting SSH despite the probe
correctly reporting no auth.

Use `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` which
propagate the rewrite to every child git process for the duration of
this script, with no persistent state in ~/.gitconfig.
2026-05-24 04:58:21 +02:00
Mika SenghaasandGitHub ae1461e7a1 docs: fix stale slurm config examples and references (#2619)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The docs and a couple of example READMEs described slurm usage that
no longer matches the real config system - users following them would
hit validation errors.

- docs/slurm.md: drop bogus `toml_files = [...]` (not a pydantic-config
  feature) and document the real `@ base.toml @ overlay.toml` compose
  syntax. Rename `[orchestrator.sampling]` and `[[orchestrator.env]]`
  to the current `train`-scoped paths, swap `max_tokens` for
  `max_completion_tokens`, repoint dead `examples/hendrycks_math/`
  links to `examples/multinode/`, fix the inference example filename
  and `--dry-run` flag usage
- examples/hendrycks_sanity/README.md: the slurm command was invoking
  the overlay alone (which fails validation), compose base + overlay
- examples/wiki_search/README.md: stale `[[orchestrator.env]]` path
2026-05-23 19:56:41 -07:00
7e8355003a chore(orchestrator): backfill rollout tokens only when needed (#2610)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(orchestrator): gate pretokenize_rollout_trajectory on SFT mode

Only call the pretokenize fallback in sft mode. The renderer-backed and
MITO rollout clients populate step["tokens"] from vLLM's prompt_token_ids
and token_ids extensions, so the call is a no-op there. sft from an
external teacher (e.g. openai/gpt-5-mini via PI inference) does still
need the fallback because external APIs return no token IDs.

Verified on examples/reverse_text/rl.toml @ 5 steps:
- renderer (default):                  reward 0.11 → 0.24
- MITO (--no-orchestrator.use-renderer): reward 0.11 → 0.20
- sft external (configs/debug/training_modes/sft_external.toml): reward ~0.92, all 5 steps complete

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

* chore(orchestrator): gate pretokenize on tokens-missing, log when it runs

Replace the training_mode == "sft" gate with a behavioral check on
step["tokens"] is None. This skips the 256-way to_thread fanout for
SFT against a local vLLM teacher too (vLLM populates tokens via
prompt_token_ids/token_ids), not just RL/OPD. Only the external teacher
API path (OpenAI/etc.) actually needs the fallback. Log inside the
guard so it's visible when the work runs.

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

* refactor(orchestrator): rename pretokenize_rollout_trajectory -> backfill_rollout_tokens

"Pretokenize" was misleading - the function is a backfill that fills in
step["tokens"] for any step where it's None, run only when the rollout
source (e.g. external teacher API) didn't return token IDs.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:18:14 -07:00
81822debb6 feat(orchestrator): default X-Session-ID header to trajectory_id (#2615)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): default X-Session-ID header to trajectory_id

Switch the auto-injected `X-Session-ID` sticky-routing header from
`example_id` to `trajectory_id` so each rollout (rather than each
dataset example) pins to a single inference engine.

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

* chore: bump configs/private submodule

Pin to the research-configs branch dropping the explicit
`X-Session-ID = example_id` override on `rlm5/{prod,glm5-swe}`
so they pick up the new `trajectory_id` default.

See: PrimeIntellect-ai/research-configs#2

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:18:07 -07:00
8e978063b4 perf(orchestrator): reduce event-loop lag (#2609)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* perf(transport): offload TrainingBatch send to a worker thread

Make FileSystemTrainingBatchSender.send async and run the msgspec encode
+ disk write in asyncio.to_thread. Keeps the orch event loop responsive
during step transitions when the batch payload is large.

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

* perf(orchestrator): await async sender; to_thread advantages+filters+uvloop

- await training_batch_sender.send(training_batch) since sender is async (O1+O2)
- compute_advantages and apply_filters wrapped in asyncio.to_thread (O3+O4):
  both iterate ~2k rollouts in pure Python and release the GIL on every
  bytecode tick, so threading actually helps unlike the C-extension encode
- main() installs uvloop (O7) — lower scheduler overhead matters when the
  orchestrator is juggling many concurrent rollouts + the HTTP client to
  inference; measurably reduces tail latency.

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

* perf(orchestrator): log p99 event-loop lag in metrics + busy-loop warning

p90 alone undersells the long tail we see at step boundaries. p99 is the
metric we actually compare across runs, so surface it in the wandb dict
(`event_loop_lag/p99`) and in the busy-loop warning line.

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

* perf(orchestrator): defer routed_experts concat in interleave_rollout

extend_sample's previous implementation unpacked the accumulated
routed_experts bytes, mutated one boundary entry, np.concatenated the new
step's routings, then re-packed to bytes — every extension. For an N-turn
rollout reaching seq_len 60k, the accumulated buffer reached ~23 MB and was
fully read+written N times, giving O(N²) byte work (~2.3 GB of memcpy per
rollout). At 256 rollouts/step this dominated the orch's step-boundary
event-loop stalls more than the encode path we'd already fixed.

Defer the concat: track per-sample `chunks: list[np.ndarray]` during the
extension loop and finalize once at the end. The "boundary token" entry
that vLLM omits for each request is appended as its own one-entry chunk
between consecutive steps' contributions, so the final concat is a
straight join — no destructive writes to prior chunks.

Verified byte-exact against the old implementation on a 50-step extension
chain. Per-rollout work drops from O(N²) → O(N): ~100× less memcpy in the
realistic regime.

This makes use_process_pool unnecessary for the residual orch lag: each
rollout's process_rollout cost drops below the IPC pickle cost, so the
threaded path is strictly better.

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

* perf(orchestrator): orjson save_rollouts + dedup bool conversion

- save_rollouts: json.dump -> orjson.dumps + bytes write. The pure-Python
  serializer held the GIL for the whole save phase (multi-second spikes
  on big steps); orjson serializes in C and releases the GIL.
- prepare/make/extend mask handling: [bool(i) for i in mask] was the
  remaining per-turn GIL-held Python loop. make_sample/extend_sample
  swapped to list(...) / direct extend; prepare_step_tokens uses
  list(map(bool, ...)). Together drops gather wallclock 5-10% on
  long-tail rollouts.

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

* perf(orchestrator): skip pretokenize fanout when nothing needs work; 10Hz lag monitor

- Pretokenize was a no-op for router-replay (every step already has
  tokens populated by the renderer client), but the 256-way to_thread
  fanout starved the loop for ~2 s per step. Short-circuit when no
  rollout's trajectory has unpopulated tokens. Offline attribution:
  pretokenize lag drops 2050 ms → 11 ms.
- EventLoopLagMonitor sampling 1 Hz → 10 Hz (mirrors verifiers'
  monitor). 1 Hz was missing sub-second spikes that show up clearly
  at 10 Hz.

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

* chore(deps): bump verifiers submodule to a930f2e5 (post-1453 main)

Pulls in the env_worker / env_router event-loop lag fixes that just
landed on verifiers main via PR 1453 — required for the orch-side
gains in this PR to surface under realistic 256-rollout concurrency.

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

---------

Co-authored-by: Sami <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 18:34:42 -07:00
Matej SirovatkaandGitHub 934c014bec Pin CUDA 12 routed experts vLLM wheel (#2611)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-24 02:56:02 +02:00
20f6449e1f refactor: rename rollouts_per_example to group_size (#2599)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Renames the orchestrator-level, [orchestrator.eval] group-level, and per-env
[[orchestrator.eval.env]] fields. The old name still parses as a validation
alias in both TOML and CLI, so existing configs keep working unchanged.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 16:47:02 -07:00
1e0fe9637d [R3]: Move to new vLLM routed experts format (#2487)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: wire r3 v3 routed experts stack

* feat: reset routing caches on policy update

* fix: rely on native vllm routed experts

* fix: pin routed experts dependencies for ci

* fix: update scheduler tests for prefix reset

* fix: clean routed experts replay integration

* fix: keep routed experts transport first class

* fix: keep routed experts on samples

* fix: use upstream vllm nightly wheel

* fix: pin latest routed experts verifiers

* fix: pin routed experts dependencies

* fix: allow routed experts with nixl

* style: format nixl patch

* Use raw uint8 routed experts payloads

* Remove unrelated rlm-swe dependency

* Pin vllm-router 0.1.25 wheel

* Keep verifiers routed experts opaque

* Forward renderer thinking preservation config

* Avoid duplicate routed experts in token responses

* [codex] Guard checkpoint disk metrics mkdir (#2523)

* Guard checkpoint disk metrics mkdir

* Remove test_trainer_utils.py per review feedback

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

* Simplify ckpt disk metrics guard

Drop the rank-0 gate and the disk_usage path fallback per review feedback.
Catching FileExistsError on mkdir is sufficient: every rank that races on
mkdir either wins or harmlessly catches the BeegFS race, and shutil.disk_usage
can then operate on the now-existing ckpt_dir.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Pin verifiers routed experts sidecar

* Pin cleaned verifiers routed experts handling

* Pin rebased verifiers routed experts handling

* fix: remove unrelated prime-rl changes

* fix: pack routed experts as typed payloads

* refactor: inline routed experts trajectory packing

* fix: restore trajectory tokenization helpers

* refactor: simplify routed experts packing

* chore: pin vllm router wheel

* chore: update renderers and verifiers

* Pin vLLM PR39568 backport wheel

* Pin vLLM revert42434 PR39568 wheel

---------

Co-authored-by: Sami <sami@primeintellect.ai>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:39:40 +02:00
samsjaandGitHub badd2b0fe2 feat: write token exports per step (#2596)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-21 21:09:57 -07:00
86 changed files with 667 additions and 403 deletions
+1
View File
@@ -2,6 +2,7 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
+4 -4
View File
@@ -17,7 +17,7 @@ name = "stage1"
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
@@ -32,15 +32,15 @@ interval = 50
[[orchestrator.eval.env]]
id = "math500"
rollouts_per_example = 1
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
rollouts_per_example = 32
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
rollouts_per_example = 32
group_size = 32
[trainer.model.ac]
+4 -4
View File
@@ -18,7 +18,7 @@ name = "stage2"
[orchestrator]
batch_size = 2048
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
temperature = 0.6
@@ -33,15 +33,15 @@ interval = 50
[[orchestrator.eval.env]]
id = "math500"
rollouts_per_example = 1
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
rollouts_per_example = 32
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
rollouts_per_example = 32
group_size = 32
[trainer.model.ac]
+2 -2
View File
@@ -11,7 +11,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
@@ -28,7 +28,7 @@ interval = 50
id = "alphabet-sort"
name = "alphabet-sort"
num_examples = 50
rollouts_per_example = 4
group_size = 4
args = { min_turns = 2, max_turns = 2 }
[trainer]
+1 -1
View File
@@ -11,7 +11,7 @@ lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 384
@@ -12,7 +12,7 @@ lr = 3e-6
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -11,7 +11,7 @@ lr = 3e-6
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -18,7 +18,7 @@ save_adapter_separately = true
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -17,7 +17,7 @@ save_adapter_separately = true
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -14,7 +14,7 @@ impl = "custom"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -1,7 +1,7 @@
# Orchestrator config for multi-run RL integration test
# model.lora.name and output_dir are set via CLI
batch_size = 128
rollouts_per_example = 16
group_size = 16
seq_len = 2048
max_steps = 20
@@ -17,7 +17,7 @@ name = "ci-rl-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.renderer]
name = "qwen3"
@@ -17,7 +17,7 @@ name = "ci-rl-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -15,7 +15,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
@@ -15,7 +15,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
+1 -1
View File
@@ -18,7 +18,7 @@ name = "debug-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.renderer]
name = "qwen3"
+1 -1
View File
@@ -18,7 +18,7 @@ name = "debug-opd-lora"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.renderer]
name = "qwen3"
+1 -1
View File
@@ -11,7 +11,7 @@ name = "debug-rl"
[orchestrator]
training_mode = "rl"
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.renderer]
name = "qwen3"
+1 -1
View File
@@ -18,7 +18,7 @@ name = "debug-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
group_size = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -17,7 +17,7 @@ name = "debug-sft-external"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
group_size = 4
[orchestrator.train.sampling]
max_completion_tokens = 2048
+1 -1
View File
@@ -18,7 +18,7 @@ name = "debug-sft-lora"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
group_size = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -17,7 +17,7 @@ interval = 100
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
+1 -1
View File
@@ -18,7 +18,7 @@ resume_step = 500
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
+1 -1
View File
@@ -18,7 +18,7 @@ resume_step = 1000
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
+1 -1
View File
@@ -30,7 +30,7 @@ lr = 1e-5
[orchestrator]
batch_size = 512
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
+1 -1
View File
@@ -14,7 +14,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[[orchestrator.train.env]]
id = "math-env"
+1 -1
View File
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-0.6B"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 2048
+2 -2
View File
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 2048
@@ -33,7 +33,7 @@ max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[trainer] # Default trainer config
+2 -2
View File
@@ -10,7 +10,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
rollouts_per_example = 8
group_size = 8
[[orchestrator.train.env]]
id = "math-env"
@@ -23,7 +23,7 @@ interval = 50
[[orchestrator.eval.env]]
id = "aime2024"
name = "aime2024"
rollouts_per_example = 16
group_size = 16
[trainer.model.ac]
+2 -2
View File
@@ -9,7 +9,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 256
rollouts_per_example = 8
group_size = 8
[[orchestrator.train.env]]
id = "math-env"
@@ -34,7 +34,7 @@ interval = 50
id = "aime2024"
name = "aime2024"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[trainer.model]
seq_len = 4096
+1 -1
View File
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
+3 -3
View File
@@ -6,7 +6,7 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
# -- train envs --
@@ -36,13 +36,13 @@ max_completion_tokens = 512
id = "reverse-text"
name = "eval-default"
num_examples = 32
rollouts_per_example = 4
group_size = 4
[[orchestrator.eval.env]]
id = "reverse-text"
name = "eval-custom"
num_examples = 16
rollouts_per_example = 2
group_size = 2
interval = 10
[orchestrator.eval.env.sampling]
+1 -1
View File
@@ -10,7 +10,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
@@ -38,7 +38,7 @@ gpus_per_node = 2
[orchestrator]
batch_size = 16
rollouts_per_example = 8
group_size = 8
use_renderer = true
# Track zero-advantage groups but don't drop them — we're validating the
@@ -64,7 +64,7 @@ args = { images_per_turn = 2, max_turns = 2, num_examples = 100, seed = 42 }
[orchestrator.renderer]
name = "auto"
# 64 concurrent rollouts (batch_size=16 × rollouts_per_example=4) want
# 64 concurrent rollouts (batch_size=16 × group_size=4) want
# more than one tokenizer slot to avoid serialization queueing. The
# image processor (CPU-bound) dominates for VLMs so returns diminish
# past 4; bump to 4 as the default for multimodal runs.
@@ -11,7 +11,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 16
rollouts_per_example = 2
group_size = 2
[orchestrator.train.sampling]
max_completion_tokens = 32
+2 -2
View File
@@ -46,7 +46,7 @@ max_inflight_activations = 5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 2048
@@ -69,7 +69,7 @@ max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[inference.parallel]
tp = 8
+2 -2
View File
@@ -45,7 +45,7 @@ freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 4096
@@ -68,7 +68,7 @@ max_completion_tokens = 4096
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[inference.parallel]
tp = 4
+1 -1
View File
@@ -27,7 +27,7 @@ target_modules = [
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
oversampling_factor = 2.0
[orchestrator.train.sampling]
+1 -1
+1 -1
+1 -1
View File
@@ -70,7 +70,7 @@ kwargs = { clip_eps = 0.2 }
## 2. Custom Advantage Functions
Advantages are computed **per-group** (one example × N rollouts). You provide a function that computes advantages for a single group; the framework calls it once per group and stitches the results back together. Groups may have fewer than `rollouts_per_example` rollouts when some rollouts in the group errored (partial-group training).
Advantages are computed **per-group** (one example × N rollouts). You provide a function that computes advantages for a single group; the framework calls it once per group and stitches the results back together. Groups may have fewer than `group_size` rollouts when some rollouts in the group errored (partial-group training).
### Interface
+13 -14
View File
@@ -8,16 +8,14 @@ The `rl`, `sft`, and `inference` entrypoints all have built-in SLURM support. Ad
# Local run
uv run rl @ examples/reverse_text/rl.toml
# SLURM run (same entrypoint, just add [slurm] to the config)
uv run rl @ examples/reverse_text/slurm_rl.toml
# SLURM run — overlay slurm_rl.toml on top of the base config
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
```
The SLURM config is a thin overlay that inherits from a base config and adds `[slurm]` + `[deployment]` sections:
The SLURM config is a thin overlay that adds `[slurm]` (and optionally `[deployment]`) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [`configs.md`](configs.md) for details.
```toml
# examples/reverse_text/slurm_rl.toml
toml_files = ["rl.toml"]
output_dir = "outputs/reverse-text-rl"
[slurm]
@@ -138,12 +136,12 @@ freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
@@ -153,7 +151,7 @@ tp = 4
dp = 2
```
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
See [`examples/multinode/rl.toml`](../examples/multinode/rl.toml) for the full example.
---
@@ -202,7 +200,7 @@ batch_size = 128
seq_len = 8192
```
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
See [`examples/multinode/sft.toml`](../examples/multinode/sft.toml) for the full example.
---
@@ -213,6 +211,7 @@ See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) fo
Run a vLLM server on a single allocated node:
```toml
# my_inference.toml
output_dir = "/shared/outputs/my-inference"
[model]
@@ -226,7 +225,7 @@ job_name = "my-inference"
```
```bash
uv run inference @ inference_slurm.toml
uv run inference @ my_inference.toml
```
### Multi-node SLURM
@@ -255,10 +254,10 @@ After submission, the SLURM template prints the inference URLs for all nodes (on
### Dry run
Use `dry_run = true` to generate the sbatch script without submitting:
Use `--dry-run` (or `dry_run = true` in TOML) to generate the sbatch script without submitting:
```bash
uv run inference @ config.toml --dry-run true
uv run inference @ config.toml --dry-run
```
---
+1 -1
View File
@@ -26,7 +26,7 @@ lr = 1e-5
[orchestrator]
batch_size = 512
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
+1 -1
View File
@@ -62,7 +62,7 @@ weight_decay = 0.1
[orchestrator]
batch_size = 4096
rollouts_per_example = 16
group_size = 16
oversampling_factor = 3
max_off_policy_steps = 16
+1 -1
View File
@@ -19,7 +19,7 @@ uv run rl @ examples/hendrycks_sanity/rl.toml \
Or schedule the same training via SLURM
```bash
uv run rl @ examples/hendrycks_sanity/slurm_rl.toml \
uv run rl @ examples/hendrycks_sanity/rl.toml @ examples/hendrycks_sanity/slurm_rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
+2 -2
View File
@@ -13,7 +13,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
rollouts_per_example = 8
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
@@ -27,7 +27,7 @@ interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
name = "aime2024"
rollouts_per_example = 32
group_size = 32
[trainer.model]
seq_len = 16384
+1 -1
View File
@@ -36,7 +36,7 @@ freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 2048
+1 -1
View File
@@ -10,7 +10,7 @@ name = "reverse-text"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -155,7 +155,7 @@ The wiki-search environment supports several configuration options:
You can pass these via the `--env-args` flag in `vf-eval` or configure them in your `rl.toml`:
```toml
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/wiki-search"
args = { max_turns = 5, judge_model = "gpt-4.1" }
```
+1 -1
View File
@@ -31,7 +31,7 @@ target_modules = [
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
oversampling_factor = 2.0
[orchestrator.model.lora]
+1 -1
View File
@@ -16,7 +16,7 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 1024
rollouts_per_example = 16
group_size = 16
[[orchestrator.train.env]]
id = "primeintellect/wordle"
@@ -250,8 +250,8 @@ class EvalEnvConfig(EnvConfig):
num_examples: int = -1
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
rollouts_per_example: int = Field(1, ge=1)
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``rollouts_per_example=8`` enables pass@1 through pass@8)."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
interval: int = Field(100, ge=1)
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
@@ -316,7 +316,7 @@ class EvalConfig(BaseConfig):
num_examples: int = -1
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
rollouts_per_example: int = Field(1, ge=1)
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Default rollouts per example. Can be overridden per env."""
num_workers: int | Literal["auto"] = "auto"
@@ -330,7 +330,7 @@ class EvalConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, rollouts_per_example, and interval. Then resolve auto num_workers."""
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, group_size, and interval. Then resolve auto num_workers."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
@@ -340,20 +340,20 @@ class EvalConfig(BaseConfig):
env.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in env.model_fields_set:
env.num_examples = self.num_examples
if "rollouts_per_example" not in env.model_fields_set:
env.rollouts_per_example = self.rollouts_per_example
if "group_size" not in env.model_fields_set:
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
if "num_workers" not in env.model_fields_set:
env.num_workers = self.num_workers
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
# Resolve auto num_workers now that num_examples and rollouts_per_example are set
# Resolve auto num_workers now that num_examples and group_size are set
if env.num_workers == "auto":
if env.num_examples == -1:
env.num_workers = 4
else:
max_concurrent = env.num_examples * env.rollouts_per_example
max_concurrent = env.num_examples * env.group_size
env.num_workers = max(1, math.ceil(max_concurrent / 256))
return self
@@ -622,7 +622,7 @@ class OrchestratorConfig(BaseConfig):
max_inflight_rollouts: int | None = Field(None, ge=1)
"""Maximum number of rollouts kept in-flight. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
rollouts_per_example: int = Field(1, ge=1)
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Output sequences returned per example during training."""
seq_len: int = 2048
@@ -760,7 +760,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
return self
@model_validator(mode="after")
@@ -907,11 +907,11 @@ class OrchestratorConfig(BaseConfig):
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.rollouts_per_example != 0:
if self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_rollouts = max(
self.rollouts_per_example,
self.group_size,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
@@ -921,7 +921,7 @@ class OrchestratorConfig(BaseConfig):
if self.max_inflight_rollouts is None:
self.max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
# Resolve train env num_workers from max_inflight_rollouts
@@ -484,6 +484,19 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
self.trainer.enable_router_replay
and self.inference is not None
and self.inference.kv_cache_offload is not None
):
raise ValueError(
"Router replay with inference.kv_cache_offload is not supported. "
"External KV cache hits do not carry routed-expert decisions."
)
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "single_node": # single-node
@@ -138,7 +138,7 @@ class ClientConfig(BaseConfig):
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
extra_headers_from_state: dict[str, str] = {}
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "example_id"}`` enables sticky routing at the inference router."""
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "trajectory_id"}`` enables sticky routing at the inference router."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
@@ -482,9 +482,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
class TokenExportConfig(BaseConfig):
"""Configures per-token rollout exports from the RL trainer."""
path: Path | None = None
"""JSONL output file. If unset, writes to ``<output_dir>/token_exports/rank_<rank>.jsonl``. Relative paths are resolved under output_dir."""
class TrainerExperimentalConfig(BaseConfig):
token_export: TokenExportConfig | None = None
+4 -2
View File
@@ -36,6 +36,7 @@ dependencies = [
"tilelang>=0.1.8",
"flash-linear-attention",
"nvidia-ml-py>=12.575.51",
"pybase64>=1.4.2",
]
[project.scripts]
@@ -178,6 +179,7 @@ override-dependencies = [
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
# PrimeIntellect-published on PyPI (trusted publisher)
prime = false
@@ -230,9 +232,9 @@ dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
prime-pydantic-config = { workspace = true }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
+19 -5
View File
@@ -44,11 +44,19 @@ assert_supported_platform() {
}
has_ssh_access() {
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
# We try a quick ls-remote to avoid cloning on failure.
# Disable -e for the probe so the script doesn't exit on a failed test.
# Probe GitHub SSH auth directly. `ssh -T git@github.com` returns
# "successfully authenticated" only when the local key is registered
# with a GitHub user, which is the precondition for cloning private
# submodules over SSH. The previous `git ls-remote` probe could
# spuriously succeed (cached creds, public-repo edge cases) and
# leave submodule clones to fail later.
#
# Note: ssh -T git@github.com always exits 1 (GitHub denies shell
# access after authenticating), so we capture stdout/stderr to a var
# first and grep the var. Piping directly would trigger pipefail.
set +e
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
out=$(timeout 5s ssh -o BatchMode=yes -T git@github.com 2>&1)
echo "$out" | grep -q "successfully authenticated"
rc=$?
set -e
return $rc
@@ -122,7 +130,13 @@ main() {
fi
if ! has_ssh_access; then
git config url."https://github.com/".insteadOf "git@github.com:"
# Propagate the rewrite via env vars so it reaches `git submodule--helper clone`,
# which spawns fresh `git clone` processes that do not read the parent repo's
# local `.git/config`. Local `git config url..insteadOf` is invisible to them.
log_info "Routing git@github.com: SSH URLs to HTTPS for this run."
export GIT_CONFIG_COUNT=1
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
export GIT_CONFIG_VALUE_0="git@github.com:"
fi
log_info "Initializing submodules..."
+1 -3
View File
@@ -62,12 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
[trainer.experimental.token_export]
# Optional. Relative paths resolve under trainer.output_dir.
path = "token_exports/sample.jsonl"
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
+45
View File
@@ -21,6 +21,51 @@ def transformers_v5_compat():
monkey_patch_dp_engine_core_pause_resume_deadlock()
monkey_patch_vllm_layerwise_reload_alias_buffers()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm import envs
from vllm.config.vllm import VllmConfig
from vllm.logger import init_logger
logger = init_logger(__name__)
original_post_init = VllmConfig.__post_init__
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
return
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
kv_transfer_config = config.kv_transfer_config
return (
config.model_config is not None
and config.model_config.enable_return_routed_experts
and kv_transfer_config is not None
and kv_transfer_config.kv_connector == "NixlConnector"
and kv_transfer_config.is_kv_transfer_instance
)
def _post_init(config: VllmConfig):
if not _is_nixl_routed_experts_pd_config(config):
return original_post_init(config)
if config.parallel_config.pipeline_parallel_size > 1:
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if envs.VLLM_USE_V2_MODEL_RUNNER:
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
# vLLM rejects every KV connector, but our P/D path uses NIXL and
# stitches prefill/decode routed experts in the router. CPU KV offload
# remains rejected by prime-rl config validation.
config.model_config.enable_return_routed_experts = False
try:
return original_post_init(config)
finally:
config.model_config.enable_return_routed_experts = True
_post_init._prime_rl_allows_nixl_routed_experts = True
VllmConfig.__post_init__ = _post_init
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
def monkey_patch_vllm_layerwise_reload_alias_buffers():
@@ -0,0 +1,40 @@
from __future__ import annotations
from collections.abc import AsyncIterator
from typing import Any
import numpy as np
import pybase64
from vllm.outputs import RequestOutput
def serialize_routed_experts(routed_experts: Any) -> dict[str, Any] | None:
if routed_experts is None:
return None
array = np.asarray(routed_experts)
assert array.ndim == 3
assert np.issubdtype(array.dtype, np.integer)
if array.size:
assert array.min() >= 0
assert array.max() <= np.iinfo(np.uint8).max
compact = np.ascontiguousarray(array.astype(np.uint8, copy=False))
return {
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
"shape": list(compact.shape),
}
class RoutedExpertsCapture:
def __init__(self, generator: AsyncIterator[RequestOutput]):
self._generator = generator
self.routed_experts: dict[int, dict[str, Any]] = {}
async def __aiter__(self):
async for request_output in self._generator:
for output in request_output.outputs:
encoded = serialize_routed_experts(getattr(output, "routed_experts", None))
if encoded is not None:
self.routed_experts[output.index] = encoded
yield request_output
+18 -57
View File
@@ -10,9 +10,9 @@ we subclass it to add them back:
header and forwarded to ``engine_client.generate``. The DP-replicated
inference servers prime-RL runs need this to target a specific replica.
2. ``routed_experts`` per-token export — when the engine emits routing
decisions (``enable_return_routed_experts``), surface them on each choice.
This is what the trainer's router-replay path consumes.
2. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
source fork.
3. Server-side ``max_tokens`` defaulting — ``ServingTokens`` hands the
client-supplied ``SamplingParams`` to the engine verbatim, and
@@ -30,13 +30,11 @@ delegates to upstream so we track future vLLM changes for free.
from __future__ import annotations
import base64
from collections.abc import AsyncGenerator
from functools import cached_property
from typing import Any
import numpy as np
from fastapi import Request
from pydantic import Field
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
from vllm.entrypoints.serve.disagg.protocol import (
GenerateRequest,
@@ -48,64 +46,29 @@ from vllm.entrypoints.utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
routed_experts: dict | None = Field(
default=None,
description=(
"Per-token expert routing decisions (base85-encoded int32 array + shape). "
"Populated only when the engine was launched with "
"``enable_return_routed_experts=True``; otherwise ``None``."
),
)
routed_experts: dict[str, Any] | None = None
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
def encode_routed_experts(arr: np.ndarray) -> dict:
return {
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
"shape": list(arr.shape),
}
class _RoutedExpertsCaptureBase:
"""Wraps the engine result generator and accumulates a
``{output_index: encoded_experts}`` map as outputs stream. Subclasses
implement ``post_process`` to fold the captured map into the response
in whatever shape the endpoint returns (in-place vs rebuilt)."""
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
self._generator = generator
self.routed_experts: dict[int, dict] = {}
async def __aiter__(self):
async for request_output in self._generator:
for output in request_output.outputs:
if output.routed_experts is not None:
self.routed_experts[output.index] = encode_routed_experts(output.routed_experts)
yield request_output
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
"""Generate-endpoint variant: rebuilds the response with
``PrimeRlGenerateResponseChoice`` because upstream's
``GenerateResponseChoice`` isn't ``extra='allow'``, so an attribute
set after construction wouldn't survive serialization."""
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
def post_process(self, response: GenerateResponse) -> PrimeRlGenerateResponse:
new_choices = [
choices = [
PrimeRlGenerateResponseChoice(
**choice.model_dump(),
**choice.model_dump(exclude={"routed_experts"}),
routed_experts=self.routed_experts.get(choice.index),
)
for choice in response.choices
]
return PrimeRlGenerateResponse(
request_id=response.request_id,
choices=new_choices,
choices=choices,
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
@@ -135,7 +98,7 @@ async def _client_set_max_tokens(raw_request: Request | None) -> bool:
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + DP-rank routing + routed_experts export + max_tokens defaulting."""
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
@cached_property
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
@@ -298,15 +261,13 @@ class PrimeRlServingTokens(ServingTokens):
model_name: str,
request_metadata: RequestResponseMetadata,
) -> ErrorResponse | GenerateResponse:
# Wrap the result generator to capture routed_experts as it streams,
# defer the rest to upstream, then post-process the response into our
# PrimeRlGenerateResponse subclass so the encoded experts surface in
# the JSON. Skipping the wrapper when the engine isn't producing routed
# experts keeps us a no-op subclass on the common path.
capture: _RoutedExpertsCapture | None = None
# Capture routed_experts as vLLM streams request outputs, then post-process
# the final response into our GenerateResponse subclass so the encoded
# experts surface in the JSON.
capture: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
capture = _RoutedExpertsCapture(result_generator)
result_generator = capture # type: ignore[assignment]
capture = _GenerateRoutedExpertsCapture(result_generator)
result_generator = capture
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
+12 -14
View File
@@ -142,12 +142,12 @@ class Env:
client: vf.ClientConfig,
example: dict,
model_name: str,
rollouts_per_example: int,
group_size: int,
cache_salt: str,
) -> list[vf.RolloutOutput]:
"""Run a group of rollouts for an example. Required for group-scoring envs."""
return await self.env.run_group(
[vf.RolloutInput(**example) for _ in range(rollouts_per_example)],
[vf.RolloutInput(**example) for _ in range(group_size)],
client=client,
model=model_name,
sampling_args=self._sampling_args_with_salt(cache_salt),
@@ -191,30 +191,30 @@ class EvalEnv(Env):
cache_salt: str,
) -> list[vf.RolloutOutput]:
num_examples = len(self.examples)
rollouts_per_example = self.config.rollouts_per_example
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {rollouts_per_example=})")
total_rollouts = num_examples * rollouts_per_example
group_size = self.config.group_size
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {group_size=})")
total_rollouts = num_examples * group_size
pbar = ProgressTracker(total=total_rollouts, desc=f"Evaluating {self.name}")
eval_start = time.perf_counter()
if self.requires_group_scoring:
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
"""Run rollouts_per_example rollouts as a scored group for one example."""
"""Run group_size rollouts as a scored group for one example."""
try:
client = await get_client()
outputs = await self.run_group(
client=client,
example=example,
model_name=model_name,
rollouts_per_example=rollouts_per_example,
group_size=group_size,
cache_salt=cache_salt,
)
pbar.update(rollouts_per_example)
pbar.update(group_size)
return outputs
except Exception as e:
get_logger().warning(f"Group failed: {e}")
pbar.update(rollouts_per_example)
pbar.update(group_size)
return None
coros = [run_with_progress(example) for example in self.examples]
@@ -235,7 +235,7 @@ class EvalEnv(Env):
pbar.update(1)
return None
coros = [run_with_progress(example) for example in self.examples for _ in range(rollouts_per_example)]
coros = [run_with_progress(example) for example in self.examples for _ in range(group_size)]
try:
results = await asyncio.gather(*coros)
@@ -291,9 +291,7 @@ class EvalEnv(Env):
pass_at_k = None
get_logger().warning("Skipping computing pass@k rates because the task rewards appear to be non-binary")
message = (
f"Evaluated {self.name} in {eval_time:.2f}s (Avg@{rollouts_per_example}={results_df.reward.mean():.4f}"
)
message = f"Evaluated {self.name} in {eval_time:.2f}s (Avg@{group_size}={results_df.reward.mean():.4f}"
if could_be_binary:
assert pass_at_k is not None
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
@@ -307,7 +305,7 @@ class EvalEnv(Env):
get_logger().success(message)
eval_metrics = {
f"avg@{rollouts_per_example}": float(results_df.reward.mean()),
f"avg@{group_size}": float(results_df.reward.mean()),
"no_response/mean": float(results_df.no_response.mean()),
"no_response/count": int(results_df.no_response.sum()),
"completion_len/mean": results_df.completion_len.mean().item(),
+12 -10
View File
@@ -11,24 +11,24 @@ class EventLoopLagMonitor:
def __init__(
self,
interval: float = 1.0,
interval: float = 0.1,
max_window_size: int = 10000,
warn_med_lag_threshold: float = 0.5,
warn_p90_lag_threshold: float = 1.0,
warn_max_lag_threshold: float = 5.0,
warn_p99_lag_threshold: float = 5.0,
warn_max_lag_threshold: float = 30.0,
):
assert (
interval > 0
and max_window_size > 0
and warn_max_lag_threshold > 0
and warn_med_lag_threshold > 0
and warn_p90_lag_threshold > 0
and warn_p99_lag_threshold > 0
and warn_max_lag_threshold > 0
)
self.interval = interval
self.max_window_size = max_window_size
self.warn_max_lag_threshold = warn_max_lag_threshold
self.warn_med_lag_threshold = warn_med_lag_threshold
self.warn_p90_lag_threshold = warn_p90_lag_threshold
self.warn_p99_lag_threshold = warn_p99_lag_threshold
self.warn_max_lag_threshold = warn_max_lag_threshold
self.logger = get_logger()
self.lags = []
@@ -61,15 +61,16 @@ class EventLoopLagMonitor:
mean_lag = float(np.mean(last_lags))
med_lag = float(np.median(last_lags))
p90_lag = float(np.percentile(last_lags, 90))
p99_lag = float(np.percentile(last_lags, 99))
min_lag = float(np.min(last_lags))
max_lag = float(np.max(last_lags))
if (
med_lag > self.warn_med_lag_threshold
or p90_lag > self.warn_p90_lag_threshold
p90_lag > self.warn_p90_lag_threshold
or p99_lag > self.warn_p99_lag_threshold
or max_lag > self.warn_max_lag_threshold
):
self.logger.warning(
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, p99={p99_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
)
return {
@@ -77,5 +78,6 @@ class EventLoopLagMonitor:
"event_loop_lag/mean": mean_lag,
"event_loop_lag/med": med_lag,
"event_loop_lag/p90": p90_lag,
"event_loop_lag/p99": p99_lag,
"event_loop_lag/max": max_lag,
}
+28 -19
View File
@@ -13,9 +13,9 @@ from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
from prime_rl.orchestrator.trajectories import (
backfill_rollout_tokens,
interleave_rollout,
offload_images_to_disk,
pretokenize_rollout_trajectory,
)
from prime_rl.transport import TrainingBatch, TrainingSample, setup_training_batch_sender
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
@@ -428,10 +428,10 @@ async def orchestrate(config: OrchestratorConfig):
# Compute advantages (in-place)
num_rollouts = len(train_rollouts)
num_unique_examples = len({(r["env_name"], r["example_id"]) for r in train_rollouts})
compute_advantages(train_rollouts, config.advantage)
await asyncio.to_thread(compute_advantages, train_rollouts, config.advantage)
# Apply rollout filters — sets rollout["filters"] and rollout["is_filtered"]
apply_filters(rollout_filters, train_rollouts)
await asyncio.to_thread(apply_filters, rollout_filters, train_rollouts)
n_trainable = sum(1 for r in train_rollouts if not r["is_filtered"])
if n_trainable > 0:
@@ -482,22 +482,28 @@ async def orchestrate(config: OrchestratorConfig):
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
# Pretokenize is a no-op when the renderer client already populated
# ``tokens`` on each trajectory step (renderer path); the fallback
# tokenizer-only branch handles text-only rollouts whose tokens
# were not pre-rendered. Run on threads so CPU work overlaps with
# inference for the next batch (via max_async_level >= 2).
await asyncio.gather(
*(
asyncio.to_thread(
pretokenize_rollout_trajectory,
rollout,
tokenizer,
renderer=renderer,
# We only expect to backfill tokens for training_mode=sft against an
# external teacher API (OpenAI/etc.), which returns no token IDs —
# reconstruct via tokenizer/renderer. The vLLM-served paths (RL/OPD
# renderer + MITO, and training_mode=sft against a local vLLM teacher)
# already populate tokens via prompt_token_ids/token_ids, so we
# short-circuit the 256-way fanout.
needs_backfill = any(step["tokens"] is None for rollout in train_rollouts for step in rollout["trajectory"])
if needs_backfill:
logger.info(
"Backfilling tokens for rollout trajectories (expected for training_mode=sft against an external teacher API)"
)
await asyncio.gather(
*(
asyncio.to_thread(
backfill_rollout_tokens,
rollout,
tokenizer,
renderer=renderer,
)
for rollout in train_rollouts
)
for rollout in train_rollouts
)
)
# Process rollouts in parallel
results = await asyncio.gather(
@@ -564,7 +570,7 @@ async def orchestrate(config: OrchestratorConfig):
step=progress.step,
)
training_batch_sender.send(training_batch)
await training_batch_sender.send(training_batch)
step_time = time.perf_counter() - step_start_time
@@ -614,7 +620,7 @@ async def orchestrate(config: OrchestratorConfig):
"""Compute solve_none, solve_all, effective_batch_size for a set of rollouts."""
reward_per_problem = df.groupby(["env_name", "example_id"]).reward.sum()
solve_none = (reward_per_problem == 0).mean()
solve_all = (reward_per_problem == config.rollouts_per_example).mean()
solve_all = (reward_per_problem == config.group_size).mean()
return solve_none, solve_all, 1 - solve_none - solve_all
# Group by (env_name, example_id) to average across rollouts within each problem
@@ -863,6 +869,9 @@ async def orchestrate(config: OrchestratorConfig):
def main():
"""Main entry-point for orchestrator. Run using `uv run orchestrator`"""
set_proc_title("Orchestrator")
import uvloop
uvloop.install()
asyncio.run(orchestrate(cli(OrchestratorConfig)))
+8 -8
View File
@@ -80,7 +80,7 @@ class Scheduler:
self.config = config
self.batch_size = config.batch_size
self.token_batch_size = config.token_batch_size
self.rollouts_per_example = config.rollouts_per_example
self.group_size = config.group_size
self.max_inflight_rollouts = max_inflight_rollouts
self.max_async_level = max_async_level
self.max_off_policy_steps = max_off_policy_steps
@@ -219,7 +219,7 @@ class Scheduler:
client=client_config,
example=group.example,
model_name=self.model_name,
rollouts_per_example=rollout_count,
group_size=rollout_count,
cache_salt=cache_salt,
)
)
@@ -266,13 +266,13 @@ class Scheduler:
await self.schedule_rollout(group_id=group_id)
return True
if remaining_capacity < self.rollouts_per_example:
if remaining_capacity < self.group_size:
return False
example = self.buffer.sample_examples(n=1)[0]
group_id = self.next_group_id
self.next_group_id += 1
self.groups[group_id] = GroupState(example=example, rollouts_to_schedule=self.rollouts_per_example)
self.groups[group_id] = GroupState(example=example, rollouts_to_schedule=self.group_size)
await self.schedule_rollout(group_id=group_id)
return True
@@ -475,16 +475,16 @@ class Scheduler:
# Wait until every dispatched rollout has come back (succeeded
# or failed) before finalizing. The group may finalize as a
# partial group (< rollouts_per_example) when some rollouts
# partial group (< group_size) when some rollouts
# errored - downstream advantage computation groups by
# (env_name, example_id), so variable-size groups are fine.
if len(group.completed_rollouts) + group.failed_rollouts < self.rollouts_per_example:
if len(group.completed_rollouts) + group.failed_rollouts < self.group_size:
continue
if not group.completed_rollouts:
self.dropped_groups_by_env[env_name] += 1
self.logger.warning(
f"Dropping group {group_id} ({env_name}) - all {self.rollouts_per_example} rollouts failed"
f"Dropping group {group_id} ({env_name}) - all {self.group_size} rollouts failed"
)
self.groups.pop(group_id, None)
continue
@@ -492,7 +492,7 @@ class Scheduler:
if group.failed_rollouts > 0:
self.logger.warning(
f"Partial group {group_id} ({env_name}) - "
f"{len(group.completed_rollouts)}/{self.rollouts_per_example} valid "
f"{len(group.completed_rollouts)}/{self.group_size} valid "
f"({group.failed_rollouts} failed)"
)
+94 -37
View File
@@ -3,11 +3,13 @@ import hashlib
from pathlib import Path
from typing import Any
import numpy as np
import pybase64
import torch
import verifiers as vf
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.transport import TrainingSample
from prime_rl.transport import RoutedExperts, TrainingSample
from prime_rl.utils.chat_template import (
common_prefix_len,
deserialize_tool_calls,
@@ -21,25 +23,26 @@ from prime_rl.utils.logger import get_logger
# primitives are immutable. mm_kwargs payloads are not mutated after creation.
def _align_routed_experts(
routed_experts: list[list[list[int]]] | None,
def align_routed_experts(
routed_experts: np.ndarray | None,
expected_len: int,
) -> list[list[list[int]]] | None:
) -> np.ndarray | None:
"""Align routed_experts length with the expected token count.
VLLM's capturer uses `num_tokens - 1` slot mappings because the final
generated token was never fed as input to a forward pass and has no
routing decision. Append zero-filled entries for the missing positions.
"""
if routed_experts is None or not routed_experts:
if routed_experts is None:
return routed_experts
deficit = expected_len - len(routed_experts)
assert routed_experts.ndim == 3
if routed_experts.shape[0] > expected_len:
return np.ascontiguousarray(routed_experts[:expected_len])
deficit = expected_len - routed_experts.shape[0]
if deficit <= 0:
return routed_experts
num_layers = len(routed_experts[0])
topk = len(routed_experts[0][0])
zero_entry = [[0] * topk for _ in range(num_layers)]
return routed_experts + [zero_entry for _ in range(deficit)]
padding = np.zeros((deficit, routed_experts.shape[1], routed_experts.shape[2]), dtype=routed_experts.dtype)
return np.concatenate((routed_experts, padding), axis=0)
def _common_prefix_len(a: list[int], b: list[int]) -> int:
@@ -161,7 +164,7 @@ def _tokenize_step_with_renderer(
return build_trajectory_step(renderer, prompt, completion, tools=tools)
def pretokenize_rollout_trajectory(
def backfill_rollout_tokens(
output: vf.RolloutOutput,
tokenizer: PreTrainedTokenizer,
renderer=None,
@@ -171,6 +174,9 @@ def pretokenize_rollout_trajectory(
When a renderer is provided, uses it for tokenization (faster, deterministic).
Otherwise falls back to the tokenizer + apply_chat_template path.
"""
if all(step["tokens"] is not None for step in output["trajectory"]):
return True
logger = get_logger()
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
@@ -236,13 +242,21 @@ def interleave_rollout(
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
tokens = step["tokens"]
if tokens is not None:
routed_experts_payload = tokens.get("routed_experts")
routed_experts = None
if routed_experts_payload is not None:
decoded_routed_experts = pybase64.b64decode_as_bytearray(routed_experts_payload["data"])
routed_experts = np.frombuffer(decoded_routed_experts, dtype=np.uint8).reshape(
routed_experts_payload["shape"]
)
return {
"prompt_ids": list(tokens["prompt_ids"]),
"prompt_mask": [bool(i) for i in tokens["prompt_mask"]],
"prompt_mask": list(map(bool, tokens["prompt_mask"])),
"completion_ids": list(tokens["completion_ids"]),
"completion_mask": [bool(i) for i in tokens["completion_mask"]],
"completion_mask": list(map(bool, tokens["completion_mask"])),
"completion_logprobs": list(tokens["completion_logprobs"]),
"routed_experts": tokens.get("routed_experts"),
"routed_experts": routed_experts,
# Renderer-emitted multimodal sidecar (placeholders + per-item
# processed tensors). Populated when the rollout went through
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
@@ -260,22 +274,22 @@ def interleave_rollout(
return None
prepared_steps.append(prepared)
# Deferred routed_experts state per sample: O(N) chunk list concatenated
# once at finalize, replacing the prior O(N²) per-extension unpack/repack.
sample_routed_state: dict[int, dict[str, Any]] = {}
def make_sample(tokens: dict[str, Any]) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
if has_error:
completion_mask = [False] * len(tokens["completion_mask"])
else:
completion_mask = [bool(i) for i in tokens["completion_mask"]]
completion_mask = list(tokens["completion_mask"])
completion_ids = list(tokens["completion_ids"])
routed_experts = _align_routed_experts(
tokens.get("routed_experts"),
len(tokens["prompt_ids"]) + len(tokens["completion_ids"]),
)
prompt_ids = list(tokens["prompt_ids"])
return TrainingSample(
sample = TrainingSample(
prompt_ids=prompt_ids,
prompt_mask=[bool(i) for i in tokens["prompt_mask"]],
prompt_mask=list(tokens["prompt_mask"]),
completion_ids=completion_ids,
completion_mask=completion_mask,
completion_logprobs=list(tokens["completion_logprobs"]),
@@ -283,11 +297,26 @@ def interleave_rollout(
teacher_logprobs=None,
advantage=None,
env_name=output["env_name"],
routed_experts=routed_experts,
mm_token_type_ids=None,
routed_experts=None, # deferred — finalized at end of interleave_rollout
)
# Initialize routed-experts state for this sample. First chunk is the
# raw step routed_experts (no pad, no copy). running_len is the
# cumulative count across chunks; tracked so the boundary fix-up at
# each extension is a no-op append rather than a destructive write.
step_routed = tokens.get("routed_experts")
if step_routed is not None:
sample_routed_state[id(sample)] = {
"chunks": [step_routed],
"running_len": int(step_routed.shape[0]),
}
return sample
def extend_sample(sample: TrainingSample, prefix_len: int, step_idx: int) -> None:
def extend_sample(
sample: TrainingSample,
prefix_len: int,
step_idx: int,
) -> None:
"""Extend an existing sample with a new trajectory step (extension property holds)."""
tokens = prepared_steps[step_idx]
@@ -304,21 +333,26 @@ def interleave_rollout(
if has_error:
sample.completion_mask.extend([False] * len(tokens["completion_mask"]))
else:
sample.completion_mask.extend(bool(i) for i in tokens["completion_mask"])
sample.completion_mask.extend(tokens["completion_mask"])
sample.completion_logprobs.extend(tokens["completion_logprobs"])
sample.completion_temperatures.extend([temperature] * len(completion_ids))
if tokens.get("routed_experts") is not None and sample.routed_experts is not None:
step_routed = tokens["routed_experts"]
# The previous step's last routing entry was zero-padded by _align_routed_experts
# (vLLM only captures num_tokens-1 routings per request). This step actually
# processed that boundary token as part of its prompt, so replace the zero-fill
# with the real routing decision before appending new entries.
if prefix_len > 0 and prefix_len <= len(step_routed):
sample.routed_experts[prefix_len - 1] = step_routed[prefix_len - 1]
sample.routed_experts.extend(step_routed[prefix_len:])
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
sample.routed_experts = _align_routed_experts(sample.routed_experts, expected_len)
step_routed = tokens.get("routed_experts")
state = sample_routed_state.get(id(sample))
if step_routed is not None and state is not None:
# vLLM doesn't capture a routing decision for the *last* token of any
# request, so the previous step left no entry for token at index
# (prefix_len - 1). The next step's forward pass *did* process that
# token (as part of its prompt) and produced step_routed[prefix_len-1].
# Append that single boundary entry as its own chunk, then append the
# genuinely new entries from this step. No prior bytes touched.
if prefix_len > 0 and prefix_len <= step_routed.shape[0]:
boundary_chunk = step_routed[prefix_len - 1 : prefix_len]
state["chunks"].append(boundary_chunk)
state["running_len"] += 1
new_chunk = step_routed[prefix_len:]
state["chunks"].append(new_chunk)
state["running_len"] += int(new_chunk.shape[0])
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
# is the explicit list of prepared_steps positions merged into this sample —
@@ -327,7 +361,8 @@ def interleave_rollout(
first_tokens = prepared_steps[0]
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
active_samples.append((first_prefix, make_sample(first_tokens), [0]))
first_sample = make_sample(first_tokens)
active_samples.append((first_prefix, first_sample, [0]))
for step_idx, _step in enumerate(trajectory[1:], start=1):
tokens = prepared_steps[step_idx]
@@ -356,7 +391,29 @@ def interleave_rollout(
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples.append((new_prefix, make_sample(tokens), [step_idx]))
sample = make_sample(tokens)
active_samples.append((new_prefix, sample, [step_idx]))
# Finalize routed_experts for each sample. One concat per sample (O(N) byte
# work) replaces the previous per-step unpack/concat/repack (O(N²)). The
# boundary entries between steps were already inserted as one-entry chunks
# during extend_sample, so a straight concat is correct.
for _, sample, _ in active_samples:
state = sample_routed_state.get(id(sample))
if state is None:
continue
chunks = state["chunks"]
if not chunks:
continue
combined = np.concatenate(chunks, axis=0) if len(chunks) > 1 else np.ascontiguousarray(chunks[0])
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
combined = align_routed_experts(combined, expected_len)
combined = np.ascontiguousarray(combined)
sample.routed_experts = RoutedExperts(
data=combined.tobytes(),
shape=list(combined.shape),
dtype=str(combined.dtype),
)
# Attach images by concatenating mm_items across every step the
# sample covers. verifiers' ``state_to_output`` ships per-step
+4 -4
View File
@@ -1,7 +1,7 @@
import json
import logging
from pathlib import Path
import orjson
import verifiers as vf
from verifiers.utils.save_utils import make_serializable
@@ -82,11 +82,11 @@ def get_tool_response_len(output: vf.RolloutOutput) -> int:
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts to a JSONL file using verifiers serialization."""
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "wb") as f:
for rollout in rollouts:
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
json.dump(row, f, default=make_serializable)
f.write("\n")
f.write(orjson.dumps(row, default=make_serializable, option=opts))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
+60 -7
View File
@@ -1,6 +1,52 @@
import copy
from prime_rl.transport.types import MicroBatch, TrainingSample
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
"uint8": 1,
"int16": 2,
"int32": 4,
}
def _copy_routed_experts(routed_experts: RoutedExperts) -> RoutedExperts:
return RoutedExperts(
data=routed_experts.data,
shape=list(routed_experts.shape),
dtype=routed_experts.dtype,
)
def _routed_experts_row_size(routed_experts: RoutedExperts) -> int:
return routed_experts.shape[1] * routed_experts.shape[2] * ROUTED_EXPERTS_DTYPE_ITEMSIZE[routed_experts.dtype]
def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> RoutedExperts:
row_size = _routed_experts_row_size(routed_experts)
return RoutedExperts(
data=routed_experts.data[: seq_len * row_size],
shape=[seq_len, routed_experts.shape[1], routed_experts.shape[2]],
dtype=routed_experts.dtype,
)
def _append_routed_experts(dst: MicroBatch, src: MicroBatch) -> None:
dst_routed = dst.routed_experts
src_routed = src.routed_experts
assert dst_routed is not None
assert src_routed is not None
assert dst_routed.dtype == src_routed.dtype
assert dst_routed.shape[1:] == src_routed.shape[1:]
dst_routed.data += src_routed.data
dst_routed.shape[0] += src_routed.shape[0]
def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
routed_experts = micro_batch.routed_experts
assert routed_experts is not None
row_size = _routed_experts_row_size(routed_experts)
routed_experts.data += b"\0" * (padding_size * row_size)
routed_experts.shape[0] += padding_size
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
@@ -27,7 +73,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
# Teacher logprobs already cover the full sequence (prompt + completion),
# computed via prefill in the orchestrator when a teacher model is configured
teacher_logprobs = training_example.teacher_logprobs
routed_experts = training_example.routed_experts
routed_experts = (
_copy_routed_experts(training_example.routed_experts) if training_example.routed_experts is not None else None
)
if len(input_ids) > seq_len:
input_ids = input_ids[:seq_len]
@@ -40,7 +88,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
if teacher_logprobs is not None:
teacher_logprobs = teacher_logprobs[:seq_len]
if routed_experts is not None:
routed_experts = routed_experts[:seq_len]
routed_experts = _slice_routed_experts(routed_experts, seq_len)
if mm_token_type_ids is not None:
mm_token_type_ids = mm_token_type_ids[:seq_len]
env_names = env_names[:seq_len]
@@ -60,9 +108,10 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
assert len(teacher_logprobs) == len(input_ids), f"teacher_logprobs: {len(teacher_logprobs)}"
if routed_experts is not None:
assert len(routed_experts) == len(input_ids), (
f"routed_experts: {len(routed_experts)}, input_ids: {len(input_ids)}"
assert routed_experts.shape[0] == len(input_ids), (
f"routed_experts: {routed_experts.shape}, input_ids: {len(input_ids)}"
)
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), (
@@ -143,10 +192,12 @@ def packed_samples_into_micro_bs(
if bin_content.teacher_logprobs is None:
bin_content.teacher_logprobs = []
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
assert (bin_content.routed_experts is None) == (sample.routed_experts is None)
if sample.routed_experts is not None:
if bin_content.routed_experts is None:
bin_content.routed_experts = []
bin_content.routed_experts.extend(sample.routed_experts)
bin_content.routed_experts = _copy_routed_experts(sample.routed_experts)
else:
_append_routed_experts(bin_content, sample)
if sample.mm_token_type_ids is not None:
if bin_content.mm_token_type_ids is None:
bin_content.mm_token_type_ids = []
@@ -201,6 +252,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
)
if micro_batch.mm_token_type_ids is not None:
micro_batch.mm_token_type_ids.extend([0] * padding_size)
if micro_batch.routed_experts is not None:
_pad_routed_experts(micro_batch, padding_size)
micro_batch.env_names.extend([""] * padding_size)
return micro_batch
+13 -5
View File
@@ -210,6 +210,18 @@ class DataLoader:
key: torch.frombuffer(bytearray(payload.data), dtype=_torch_dtype(payload.dtype)).reshape(payload.shape)
for key, payload in micro_batch.mm_kwargs.items()
}
routed_experts = None
packed_routed_experts = micro_batch.routed_experts
if packed_routed_experts is not None:
routed_experts = (
torch.frombuffer(
packed_routed_experts.data,
dtype=_torch_dtype(packed_routed_experts.dtype),
)
.reshape(packed_routed_experts.shape)
.to(torch.int32)
.unsqueeze(0)
)
return TensorMicroBatch(
input_ids=torch.tensor(micro_batch.input_ids, dtype=torch.long).unsqueeze(0),
position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0),
@@ -229,11 +241,7 @@ class DataLoader:
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
if micro_batch.mm_token_type_ids is not None
else None,
routed_experts=torch.tensor(micro_batch.routed_experts, dtype=torch.int32).unsqueeze(
0
) # [1, seq_len, layers, topk]
if micro_batch.routed_experts is not None
else None,
routed_experts=routed_experts,
training_mode=micro_batch.training_mode,
)
+23 -20
View File
@@ -8,7 +8,7 @@ from typing import Any
import torch
from torch import Tensor
from prime_rl.configs.trainer import DefaultLossConfig, TokenExportConfig, TrainerConfig
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
SCHEMA_VERSION = 1
@@ -25,15 +25,12 @@ class DisabledTokenExporter:
class TokenExporter:
def __init__(
self,
config: TokenExportConfig,
output_dir: Path,
rank: int,
) -> None:
self.config = config
self.rank = rank
self.path = self._resolve_path(config.path, output_dir, rank)
self.path.parent.mkdir(parents=True, exist_ok=True)
self._file = self.path.open("a", encoding="utf-8")
self.output_dir = output_dir / "token_exports"
self._file: Any | None = None
self._closed = False
self._current_step: int | None = None
self._sequences_this_step = 0
@@ -49,8 +46,7 @@ class TokenExporter:
loss_config: Any,
) -> None:
if self._current_step != step:
self._current_step = step
self._sequences_this_step = 0
self._start_step(step)
columns = _export_columns(micro_batch, model_output, loss_config)
_check_lengths(columns)
@@ -80,21 +76,28 @@ class TokenExporter:
if self._closed:
return
self._closed = True
self._file.close()
if self._file is not None:
self._file.close()
self._file = None
def _start_step(self, step: int) -> None:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
if self._file is not None:
self._file.close()
self._current_step = step
self._sequences_this_step = 0
step_dir = self.output_dir / f"step_{step}"
step_dir.mkdir(parents=True, exist_ok=True)
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
def _write(self, record: dict[str, Any]) -> None:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.path}")
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
if self._file is None:
raise RuntimeError("Token exporter has no active step file")
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
@staticmethod
def _resolve_path(path: Path | None, output_dir: Path, rank: int) -> Path:
if path is None:
return output_dir / "token_exports" / f"rank_{rank}.jsonl"
if path.is_absolute():
return path
return output_dir / path
def setup_token_exporter(
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
@@ -105,8 +108,8 @@ def setup_token_exporter(
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
return DisabledTokenExporter()
exporter = TokenExporter(token_export_config, config.output_dir, world.rank)
logger.info(f"Writing token exports to {exporter.path}")
exporter = TokenExporter(config.output_dir, world.rank)
logger.info(f"Writing token exports under {exporter.output_dir}")
return exporter
+2 -1
View File
@@ -8,7 +8,7 @@ from prime_rl.transport.filesystem import (
FileSystemTrainingBatchReceiver,
FileSystemTrainingBatchSender,
)
from prime_rl.transport.types import MicroBatch, TrainingBatch, TrainingSample
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingBatch, TrainingSample
from prime_rl.transport.zmq import (
ZMQMicroBatchReceiver,
ZMQMicroBatchSender,
@@ -67,6 +67,7 @@ __all__ = [
"TrainingSample",
"TrainingBatch",
"MicroBatch",
"RoutedExperts",
"setup_training_batch_sender",
"setup_training_batch_receiver",
"setup_micro_batch_sender",
+1 -1
View File
@@ -16,7 +16,7 @@ class TrainingBatchSender(ABC):
self.output_dir = output_dir
@abstractmethod
def send(self, batch: TrainingBatch) -> None:
async def send(self, batch: TrainingBatch) -> None:
"""Send a batch of training examples to the trainer(s).
Args:
+6 -2
View File
@@ -1,3 +1,4 @@
import asyncio
from pathlib import Path
from time import time
@@ -18,11 +19,14 @@ class FileSystemTrainingBatchSender(TrainingBatchSender):
super().__init__(output_dir)
self.rollout_dir = get_rollout_dir(output_dir)
def send(self, batch: TrainingBatch) -> None:
"""Send a batch by writing it to disk"""
async def send(self, batch: TrainingBatch) -> None:
"""Send a batch by writing it to disk. Encode + write run in a worker
thread so the orch event loop stays responsive during step transitions."""
step_path = get_step_path(self.rollout_dir, batch.step)
step_path.mkdir(parents=True, exist_ok=True)
await asyncio.to_thread(self._encode_and_write, batch, step_path)
def _encode_and_write(self, batch: TrainingBatch, step_path: Path) -> None:
buffer = self.encoder.encode(batch)
tmp_path = step_path / BATCH_FILE_TMP_NAME
with open(tmp_path, "wb") as f:
+10 -2
View File
@@ -14,6 +14,14 @@ class EncodedTensor(msgspec.Struct, array_like=True, gc=False):
data: bytes
# Routed experts are large per-token arrays. tolist() is too expensive, so we
# send raw bytes through msgpack and carry the shape/dtype needed to rebuild.
class RoutedExperts(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
data: bytes
shape: list[int] # [seq_len, layers, topk]
dtype: str
# Orchestrator -> Packer
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
"""A single training example."""
@@ -39,7 +47,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
# touching this transport.
mm_kwargs: dict[str, EncodedTensor] | None = None
routed_experts: list[list[list[int]]] | None = None # [seq_len, layers, topk]
routed_experts: RoutedExperts | None = None
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: list[int] | None = None
@@ -70,7 +78,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
env_names: list[str]
teacher_logprobs: list[float] | None = None
lora_num_tokens: list[int] | None = None
routed_experts: list[list[list[int]]] | None = None
routed_experts: RoutedExperts | None = None
# See TrainingSample.mm_kwargs.
mm_kwargs: dict[str, EncodedTensor] | None = None
+1 -1
View File
@@ -32,7 +32,7 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
f"endpoint=tcp://{transport.host}:{transport.port} hwm={transport.hwm}"
)
def send(self, batch: TrainingBatch) -> None:
async def send(self, batch: TrainingBatch) -> None:
payload = self.encoder.encode(batch)
self.logger.debug(f"Sending batch {batch.step} to {self.sender_id}")
self.socket.send_multipart([self.sender_id, payload], copy=False)
+54 -44
View File
@@ -3,8 +3,7 @@
The full happy-path is owned upstream by vLLM 0.20's
``vllm/entrypoints/serve/disagg`` test suite. We only cover the prime-RL
deltas here:
* ``encode_routed_experts`` round-trips a numpy array as expected.
* ``PrimeRlGenerateResponseChoice`` accepts the optional field.
* ``serialize_routed_experts`` round-trips a compact raw-byte payload.
* The subclass attaches its overrides without monkey-patching the parent.
* ``_client_set_max_tokens`` distinguishes raw-body shapes correctly.
"""
@@ -12,19 +11,26 @@ deltas here:
from __future__ import annotations
import asyncio
import base64
import numpy as np
import pybase64
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse, GenerateResponseChoice
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
from prime_rl.inference.vllm.serving_tokens import (
PrimeRlGenerateResponse,
PrimeRlGenerateResponseChoice,
PrimeRlServingTokens,
_client_set_max_tokens,
encode_routed_experts,
_GenerateRoutedExpertsCapture,
)
def _decode_routed_experts(encoded: dict) -> np.ndarray:
return np.frombuffer(
pybase64.b64decode_as_bytearray(encoded["data"]),
dtype=np.uint8,
).reshape(encoded["shape"])
class _FakeRawRequest:
def __init__(self, body):
self._body = body
@@ -36,50 +42,54 @@ class _FakeRawRequest:
return self._body
def test_encode_routed_experts_roundtrip():
arr = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
encoded = encode_routed_experts(arr)
assert encoded["shape"] == [2, 3]
decoded = np.frombuffer(base64.b85decode(encoded["data"]), dtype=np.int32).reshape(encoded["shape"])
np.testing.assert_array_equal(decoded, arr)
async def _empty_request_outputs():
if False:
yield
def test_routed_experts_choice_accepts_none_and_dict():
no_re = PrimeRlGenerateResponseChoice(index=0, finish_reason="stop", token_ids=[1, 2])
assert no_re.routed_experts is None
encoded = encode_routed_experts(np.zeros((1, 1), dtype=np.int32))
with_re = PrimeRlGenerateResponseChoice(index=0, finish_reason="stop", token_ids=[1], routed_experts=encoded)
assert with_re.routed_experts == encoded
def test_response_only_serializes_declared_fields():
# Upstream silently drops id=/created=/model=/usage= because they're not
# declared on GenerateResponse. Our subclass adds nothing to that surface
# — it only widens the choices type — so the JSON shape stays slim.
resp = PrimeRlGenerateResponse(
request_id="gen-x",
choices=[PrimeRlGenerateResponseChoice(index=0, finish_reason="stop", token_ids=[7])],
)
dumped = resp.model_dump()
assert set(dumped.keys()) == {
"request_id",
"choices",
"prompt_logprobs",
"kv_transfer_params",
}
assert dumped["choices"][0]["routed_experts"] is None
def test_subclass_inherits_serve_tokens_full_generator():
# The subclass adds an override; make sure we didn't accidentally rebind
# ``serve_tokens`` to a parent attribute via __dict__-update tricks later.
def test_subclass_only_overrides_serve_tokens():
assert PrimeRlServingTokens.serve_tokens is not PrimeRlServingTokens.__mro__[1].serve_tokens
assert (
PrimeRlServingTokens.serve_tokens_full_generator
is not PrimeRlServingTokens.__mro__[1].serve_tokens_full_generator
)
assert PrimeRlServingTokens.serve_tokens is not PrimeRlServingTokens.__mro__[1].serve_tokens
def test_serialize_routed_experts_uses_compact_raw_payload():
routed_experts = np.array(
[
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
],
dtype=np.int64,
)
encoded = serialize_routed_experts(routed_experts)
assert encoded is not None
decoded = _decode_routed_experts(encoded)
assert decoded.dtype == np.uint8
np.testing.assert_array_equal(decoded, routed_experts)
def test_generate_response_post_process_replaces_upstream_routed_experts():
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3]}
capture = _GenerateRoutedExpertsCapture(_empty_request_outputs())
capture.routed_experts[0] = compact_routed_experts
response = GenerateResponse(
request_id="request-id",
choices=[
GenerateResponseChoice(
index=0,
token_ids=[1, 2, 3],
routed_experts="upstream-npy-payload",
)
],
)
processed = capture.post_process(response)
assert processed.choices[0].routed_experts == compact_routed_experts
def test_client_set_max_tokens_recognizes_explicit_value():
+1 -1
View File
@@ -288,7 +288,7 @@ def test_compute_advantages_without_config():
def test_compute_advantages_partial_groups():
"""Partial groups (size < rollouts_per_example) are advantaged against their own mean.
"""Partial groups (size < group_size) are advantaged against their own mean.
Two groups of different sizes must round-trip cleanly: each group's advantages
must sum to zero and not leak into the other.
+18 -7
View File
@@ -1,7 +1,17 @@
import numpy as np
import pytest
from prime_rl.trainer.batch import prepare_batch, prepare_sample
from prime_rl.transport.types import TrainingSample
from prime_rl.transport.types import RoutedExperts, TrainingSample
def _routed_experts(data, dtype=np.uint8):
routed_experts = np.asarray(data, dtype=dtype)
return RoutedExperts(
data=routed_experts.tobytes(),
shape=list(routed_experts.shape),
dtype=str(routed_experts.dtype),
)
@pytest.fixture
@@ -128,6 +138,7 @@ def test_prepare_sample_with_routed_experts():
"""Routed experts are passed through prepare_sample and match input_ids length."""
# 2 prompt + 2 completion = 4 tokens, 2 layers, topk=2
routed_experts = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]], [[1, 0], [3, 2]]]
routed_payload = _routed_experts(routed_experts)
sample = TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
@@ -137,18 +148,19 @@ def test_prepare_sample_with_routed_experts():
completion_temperatures=[1.0, 1.0],
advantage=1.0,
env_name="test-env",
routed_experts=routed_experts,
routed_experts=routed_payload,
)
micro_batch = prepare_sample(sample, seq_len=8)
assert micro_batch.routed_experts is not None
assert len(micro_batch.routed_experts) == 4
assert micro_batch.routed_experts == routed_experts
assert micro_batch.routed_experts == routed_payload
def test_prepare_sample_truncates_routed_experts():
"""Routed experts are truncated to seq_len when input exceeds it."""
routed_experts = [[[0, 1]], [[2, 3]], [[4, 5]], [[6, 7]]]
routed_payload = _routed_experts(routed_experts)
expected_payload = _routed_experts(routed_experts[:3])
sample = TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
@@ -158,13 +170,12 @@ def test_prepare_sample_truncates_routed_experts():
completion_temperatures=[1.0, 1.0],
advantage=1.0,
env_name="test-env",
routed_experts=routed_experts,
routed_experts=routed_payload,
)
micro_batch = prepare_sample(sample, seq_len=3)
assert micro_batch.routed_experts is not None
assert len(micro_batch.routed_experts) == 3
assert micro_batch.routed_experts == routed_experts[:3]
assert micro_batch.routed_experts == expected_payload
assert micro_batch.env_names == ["test-env"] * 3
+4 -1
View File
@@ -14,10 +14,12 @@ sampling tokens, and returning them) is exercised in real rollouts.
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
import httpx
import pytest
_HF_CACHE = Path("~/.cache/huggingface/hub").expanduser()
@@ -54,7 +56,7 @@ class _FakeOpenAI:
self.calls.append({"path": path, "body": body, "options": options})
# Reply with two sampled tokens + <|im_end|>. The renderer's
# parse_response slices the content tokens.
return {
payload = {
"request_id": "qwen-vl-e2e",
"choices": [
{
@@ -71,6 +73,7 @@ class _FakeOpenAI:
},
],
}
return httpx.Response(200, content=json.dumps(payload).encode())
def test_renderer_client_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
@@ -2,7 +2,7 @@ from unittest.mock import MagicMock
import verifiers as vf
from prime_rl.orchestrator.trajectories import interleave_rollout, pretokenize_rollout_trajectory
from prime_rl.orchestrator.trajectories import backfill_rollout_tokens, interleave_rollout
class SimpleChatTokenizer:
@@ -56,7 +56,7 @@ def test_interleave_rollout_missing_tokens_returns_none():
assert interleave_rollout(output) is None
def test_pretokenize_rollout_trajectory_for_sft():
def test_backfill_rollout_tokens_for_sft():
tokenizer = SimpleChatTokenizer()
output = vf.RolloutOutput(
example_id=42,
@@ -93,7 +93,7 @@ def test_pretokenize_rollout_trajectory_for_sft():
error=None,
)
pretokenize_rollout_trajectory(output, tokenizer)
backfill_rollout_tokens(output, tokenizer)
rollouts = interleave_rollout(output)
assert rollouts is not None
+47 -27
View File
@@ -1,12 +1,13 @@
from unittest.mock import MagicMock
import numpy as np
import pybase64
import pytest
import verifiers as vf
from prime_rl.orchestrator.trajectories import (
_align_routed_experts,
_deserialize_tool_calls,
align_routed_experts,
interleave_rollout,
)
@@ -30,6 +31,21 @@ def _decode_mm_thw(sample) -> list:
return np.frombuffer(g.data, dtype=np.dtype(g.dtype)).reshape(g.shape).tolist()
def _routed_experts_payload(data) -> dict:
arr = np.asarray(data, dtype=np.uint8)
return {
"data": pybase64.b64encode(memoryview(np.ascontiguousarray(arr))).decode("ascii"),
"shape": list(arr.shape),
}
def _sample_routed_experts(sample) -> np.ndarray:
assert sample.routed_experts is not None
return np.frombuffer(sample.routed_experts.data, dtype=np.dtype(sample.routed_experts.dtype)).reshape(
sample.routed_experts.shape
)
def test_deserialize_tool_calls_does_not_inject_missing_key():
messages = [{"role": "assistant", "content": "hello"}]
@@ -807,44 +823,47 @@ def test_interleave_rollout_error_masks_all_false():
def test_align_routed_experts_none():
assert _align_routed_experts(None, 10) is None
assert align_routed_experts(None, 10) is None
def test_align_routed_experts_empty():
result = _align_routed_experts([], 10)
assert result == []
experts = np.empty((0, 2, 2), dtype=np.uint8)
result = align_routed_experts(experts, 10)
assert result is not None
assert result.shape == (10, 2, 2)
assert np.all(result == 0)
def test_align_routed_experts_no_deficit():
# 3 tokens, 2 layers, topk=2
experts = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]]]
result = _align_routed_experts(experts, expected_len=3)
assert result == experts
experts = np.asarray([[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]]], dtype=np.uint8)
result = align_routed_experts(experts, expected_len=3)
np.testing.assert_array_equal(result, experts)
def test_align_routed_experts_with_deficit():
# 2 tokens but expected 4 (deficit of 2)
experts = [[[1, 2], [3, 4]], [[5, 6], [7, 0]]]
result = _align_routed_experts(experts, expected_len=4)
assert len(result) == 4
assert result[:2] == experts
experts = np.asarray([[[1, 2], [3, 4]], [[5, 6], [7, 0]]], dtype=np.uint8)
result = align_routed_experts(experts, expected_len=4)
assert result is not None
assert result.shape == (4, 2, 2)
np.testing.assert_array_equal(result[:2], experts)
# Padded entries should be zero-filled with same shape [layers=2, topk=2]
assert result[2] == [[0, 0], [0, 0]]
assert result[3] == [[0, 0], [0, 0]]
np.testing.assert_array_equal(result[2], [[0, 0], [0, 0]])
np.testing.assert_array_equal(result[3], [[0, 0], [0, 0]])
def test_align_routed_experts_excess_length():
experts = [[[1, 2]], [[3, 4]], [[5, 6]]]
result = _align_routed_experts(experts, expected_len=2)
# No truncation, just returns as-is
assert result == experts
experts = np.asarray([[[1, 2]], [[3, 4]], [[5, 6]]], dtype=np.uint8)
result = align_routed_experts(experts, expected_len=2)
np.testing.assert_array_equal(result, experts[:2])
def test_interleave_rollout_single_step_with_routed_experts():
"""Routed experts are aligned and passed through for a single-step trajectory."""
# prompt_ids=[1,2], completion_ids=[3,4] -> total 4 tokens
# vLLM returns num_tokens-1 = 3 routed expert entries
routed_experts_from_vllm = [[[0, 1]], [[2, 3]], [[4, 5]]] # 3 entries, 1 layer, topk=2
routed_experts_from_vllm = np.asarray([[[0, 1]], [[2, 3]], [[4, 5]]], dtype=np.uint8)
output = vf.RolloutOutput(
example_id=0,
trajectory=[
@@ -860,7 +879,7 @@ def test_interleave_rollout_single_step_with_routed_experts():
completion_logprobs=[-0.1, -0.2],
overlong_prompt=False,
is_truncated=False,
routed_experts=routed_experts_from_vllm,
routed_experts=_routed_experts_payload(routed_experts_from_vllm),
),
reward=None,
advantage=None,
@@ -880,18 +899,19 @@ def test_interleave_rollout_single_step_with_routed_experts():
# Should be aligned to 4 tokens (2 prompt + 2 completion)
assert sample.routed_experts is not None
assert len(sample.routed_experts) == 4
routed_experts = _sample_routed_experts(sample)
assert routed_experts.shape == (4, 1, 2)
# First 3 are original, last one is zero-padded
assert sample.routed_experts[:3] == routed_experts_from_vllm
assert sample.routed_experts[3] == [[0, 0]]
np.testing.assert_array_equal(routed_experts[:3], routed_experts_from_vllm)
np.testing.assert_array_equal(routed_experts[3], [[0, 0]])
def test_interleave_rollout_multi_step_with_routed_experts():
"""Routed experts are extended and aligned across multi-step trajectories."""
# Step 1: prompt=[1,2], completion=[3,4] -> 4 tokens, vLLM returns 3
step1_experts = [[[1, 2]], [[3, 4]], [[5, 6]]]
step1_experts = np.asarray([[[1, 2]], [[3, 4]], [[5, 6]]], dtype=np.uint8)
# Step 2: prompt=[1,2,3,4,5,6], completion=[7,8] -> 8 tokens, vLLM returns 7
step2_experts = [[[1, 0]], [[2, 0]], [[3, 0]], [[4, 0]], [[5, 0]], [[6, 0]], [[7, 0]]]
step2_experts = np.asarray([[[1, 0]], [[2, 0]], [[3, 0]], [[4, 0]], [[5, 0]], [[6, 0]], [[7, 0]]], dtype=np.uint8)
output = vf.RolloutOutput(
example_id=0,
@@ -908,7 +928,7 @@ def test_interleave_rollout_multi_step_with_routed_experts():
completion_logprobs=[-0.1, -0.2],
overlong_prompt=False,
is_truncated=False,
routed_experts=step1_experts,
routed_experts=_routed_experts_payload(step1_experts),
),
reward=None,
advantage=None,
@@ -932,7 +952,7 @@ def test_interleave_rollout_multi_step_with_routed_experts():
completion_logprobs=[-0.3, -0.4],
overlong_prompt=False,
is_truncated=False,
routed_experts=step2_experts,
routed_experts=_routed_experts_payload(step2_experts),
),
reward=None,
advantage=None,
@@ -953,7 +973,7 @@ def test_interleave_rollout_multi_step_with_routed_experts():
# Merged sample: prompt=[1,2], completion=[3,4,5,6,7,8] -> 8 tokens total
assert len(sample.prompt_ids) + len(sample.completion_ids) == 8
assert sample.routed_experts is not None
assert len(sample.routed_experts) == 8
assert _sample_routed_experts(sample).shape == (8, 1, 2)
def test_interleave_rollout_none_routed_experts_stays_none():
+1 -1
View File
@@ -435,7 +435,7 @@ def test_shared_output_dir_propagates_through_cli(tmp_path):
"seq_len": 128,
"model": {"name": "Qwen/Qwen3-0.6B"},
"trainer": {},
"orchestrator": {"batch_size": 16, "rollouts_per_example": 1},
"orchestrator": {"batch_size": 16, "group_size": 1},
"inference": {},
},
)
+1 -1
View File
@@ -29,7 +29,7 @@ def create_run_with_config(output_dir: Path, run_name: str) -> Path:
config = {
"model": {"name": "test-model"},
"batch_size": 2,
"rollouts_per_example": 1,
"group_size": 1,
"env": [{"id": "test-env"}],
"sampling": {"temperature": 1.0},
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
+4 -4
View File
@@ -40,7 +40,7 @@ def create_run_with_config(
config = {
"model": {"name": "test-model"},
"batch_size": 32,
"rollouts_per_example": 4,
"group_size": 4,
"env": [{"id": "test-env"}],
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
"use_renderer": False,
@@ -201,7 +201,7 @@ def test_config_loading(tmp_path: Path) -> None:
"model": {"name": "test-model"},
"batch_size": 32,
"max_steps": 1000,
"rollouts_per_example": 4,
"group_size": 4,
"env": [{"id": "test-env"}],
"use_renderer": False,
}
@@ -246,7 +246,7 @@ def test_config_cleanup_on_deletion(tmp_path: Path) -> None:
test_config = {
"model": {"name": "test-model"},
"batch_size": 16,
"rollouts_per_example": 4,
"group_size": 4,
"env": [{"id": "test-env"}],
"use_renderer": False,
}
@@ -277,7 +277,7 @@ def test_config_invalid(tmp_path: Path) -> None:
invalid_config = {
"model": {"name": "test-model"},
"batch_size": "not-a-number", # Invalid type
"rollouts_per_example": 4,
"group_size": 4,
"env": [{"id": "test-env"}],
}
run_dir = create_run_with_config(tmp_path, "run_invalid", config=invalid_config)
Generated
+26 -19
View File
@@ -23,6 +23,7 @@ vllm = false
vllm-router = false
dion = false
tokenspeed-mla = false
prime = false
nixl-cu12 = false
deep-ep = false
flash-attn-3 = false
@@ -30,7 +31,7 @@ prime-sandboxes = false
prime-tunnel = false
deep-gemm = false
prime-evals = false
prime = false
fastokens = false
[manifest]
members = [
@@ -1309,14 +1310,14 @@ wheels = [
[[package]]
name = "fastokens"
version = "0.1.2"
version = "0.2.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f2/bd/e65b2989eb045863e1d4b1d161d122f69c8d3b8e23fa287e2a8f1eb4c8ab/fastokens-0.1.2.tar.gz", hash = "sha256:71da0dd9b198d3a00c1cdfae06aff7a616513bced4ba6b2ab0da63b688302c0d", size = 675220, upload-time = "2026-05-07T14:34:31.372Z" }
sdist = { url = "https://files.pythonhosted.org/packages/14/8e/7e88ec1d48db5a6e8d8d44318ce285e38c04b81508bdc2a60e17045a116f/fastokens-0.2.0.tar.gz", hash = "sha256:ef0e175de5c8cb1b616b3210d75dce1fab78e35fc02f77f03f7847d4678be686", size = 675822, upload-time = "2026-05-17T10:32:55.642Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c7/79/fd6f087929423289df4cf11c5c05d0c13f5274b6f1ff187d322b15ee35bc/fastokens-0.1.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:07737f126ea0c6b92123f13c6aef9fada45923d37efdcf3d6bb23e677ec782a6", size = 3304086, upload-time = "2026-05-07T14:34:13.13Z" },
{ url = "https://files.pythonhosted.org/packages/3c/9d/393fa72d1d9a4e251221e077e42bdccce736f86636563b785d8460d655d1/fastokens-0.1.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:cd5c630f190a29492d86da7fcc53dd642f59dec4bf3eb204a378a32131003970", size = 3252648, upload-time = "2026-05-07T14:34:01.934Z" },
{ url = "https://files.pythonhosted.org/packages/70/8e/728c46b32fd6c10088a6a1b268732f50c03b0efb035bbea7d3f22b8de47e/fastokens-0.1.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:62b3bbbeb4e0ec72ff895b15e4b0ad04a791c87caa0edb1f63bd9d7c9896c86e", size = 3335929, upload-time = "2026-05-07T14:34:21.548Z" },
{ url = "https://files.pythonhosted.org/packages/04/3d/4ccb53de21bfb87ec13f1dfddc7567cb01732f5c755a083a7cc9e6eebfec/fastokens-0.1.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e1cb2331e4ac377a636411d722e7a0a2a12c00a46c2d64ab6522004a38c8918", size = 3598235, upload-time = "2026-05-07T14:34:30.102Z" },
{ url = "https://files.pythonhosted.org/packages/b4/54/e0e4318ee1ad0b5196df72cf93615bba0b81f7869d659a44ccc475969151/fastokens-0.2.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:160253f8d30747cf66e7ed895c513e16f7b173dd9e644fa641e2eecbd43a616a", size = 3303534, upload-time = "2026-05-17T10:32:37.462Z" },
{ url = "https://files.pythonhosted.org/packages/64/44/bfff90e4b1a43c17edf7305dafbd56dc992bbe832cc08da78f1f50104c2d/fastokens-0.2.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:b61b9fe5b41e0bb36ad86e7551dc53293c9833909ef07b1cdbaa2055b06c3b3e", size = 3254096, upload-time = "2026-05-17T10:32:28.489Z" },
{ url = "https://files.pythonhosted.org/packages/05/bf/1cad7f0e8d03f5f5b2b417cda8859e4d968d2eebdca0cd336b23d7dbbdbb/fastokens-0.2.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:01b9bdba818d7b2c67d57d9917faf7a1dad32ece0734440130de94ad768b819f", size = 3336689, upload-time = "2026-05-17T10:32:46.21Z" },
{ url = "https://files.pythonhosted.org/packages/97/d7/f5fb2564e16b1f5733e05c41b090f95a3fe767f6b888ba7d864193bc5447/fastokens-0.2.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d068bc50082ad67d5d542847075f1f7b8d10f703274e56e241312f18b4d9e772", size = 3598064, upload-time = "2026-05-17T10:32:54.109Z" },
]
[[package]]
@@ -3903,6 +3904,7 @@ dependencies = [
{ name = "prime", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "prime-rl-configs", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pyarrow", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pybase64", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pyzmq", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "renderers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "rich", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -3919,7 +3921,7 @@ dependencies = [
{ name = "uvloop", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "verifiers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" }, marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129.r42434.pr39568.a106aa6", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "wandb", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
@@ -4050,6 +4052,7 @@ requires-dist = [
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pybase64", specifier = ">=1.4.2" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "quack-kernels", marker = "extra == 'quack'", specifier = ">=0.4.1" },
{ name = "renderers", editable = "deps/renderers" },
@@ -4072,8 +4075,8 @@ requires-dist = [
{ name = "verifiers", editable = "deps/verifiers" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.21.0" },
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wiki-search", marker = "extra == 'envs'", editable = "deps/verifiers/environments/wiki_search" },
]
@@ -4756,7 +4759,7 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "fastokens", specifier = ">=0.1.1" },
{ name = "fastokens", specifier = ">=0.2.0" },
{ name = "jinja2" },
{ name = "numpy" },
{ name = "openai", specifier = ">=1.108.1" },
@@ -5893,6 +5896,7 @@ dependencies = [
{ name = "numpy", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "openai", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "openai-agents", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "prime-pydantic-config", extra = ["toml"], marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "prime-sandboxes", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "prime-tunnel", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pydantic", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -5903,6 +5907,7 @@ dependencies = [
{ name = "setproctitle", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tenacity", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "textual", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "uvloop", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and platform_python_implementation != 'PyPy' and sys_platform == 'linux') or (platform_machine == 'x86_64' and platform_python_implementation != 'PyPy' and sys_platform == 'linux') or (platform_machine == 'aarch64' and platform_python_implementation == 'PyPy' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'x86_64' and platform_python_implementation == 'PyPy' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
[package.optional-dependencies]
@@ -5931,7 +5936,7 @@ rl = [
{ name = "torch", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "transformers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" }, marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129.r42434.pr39568.a106aa6", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "wandb", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
ta = [
@@ -5985,6 +5990,7 @@ requires-dist = [
{ name = "openai-agents", specifier = ">=0.0.7" },
{ name = "openenv-core", marker = "extra == 'openenv'", specifier = ">=0.3.0" },
{ name = "peft", marker = "extra == 'rl'" },
{ name = "prime-pydantic-config", extras = ["toml"], editable = "deps/pydantic-config" },
{ name = "prime-sandboxes", specifier = ">=0.2.25" },
{ name = "prime-tunnel", specifier = ">=0.1.6" },
{ name = "pydantic", specifier = ">=2.11.9" },
@@ -6005,9 +6011,10 @@ requires-dist = [
{ name = "torch", marker = "extra == 'rl'", specifier = ">=2.8.0,<2.9.0", index = "https://download.pytorch.org/whl/cu128" },
{ name = "transformers", marker = "extra == 'rl'", git = "https://github.com/huggingface/transformers.git?rev=c1c3424" },
{ name = "typing-extensions", marker = "python_full_version < '3.12'" },
{ name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'", specifier = ">=0.21.0" },
{ name = "vllm", marker = "platform_machine == 'aarch64' and extra == 'rl'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'rl'", specifier = ">=0.10.0,<0.11.0" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and extra == 'rl'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and extra == 'rl'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl" },
{ name = "wandb", marker = "extra == 'rl'" },
]
provides-extras = ["browser", "openenv", "renderers", "rg", "rl", "ta"]
@@ -6227,8 +6234,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
[[package]]
name = "vllm"
version = "0.21.0+cu129"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" }
version = "0.21.0+cu129.r42434.pr39568.a106aa6"
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
@@ -6304,7 +6311,7 @@ dependencies = [
{ name = "xgrammar", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
wheels = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:920777691e340df7a8328adfb1e57b9996dbb537edfb654dd32f70844f5f423d" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:0f0533a9122dfa738fc0f5532cb6795556f072b133f0058a22ff4be2d2f165f0" },
]
[package.metadata]
@@ -6404,8 +6411,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
[[package]]
name = "vllm-router"
version = "0.1.22"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
version = "0.1.25"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" }
dependencies = [
{ name = "aiohttp", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "fastapi", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -6415,7 +6422,7 @@ dependencies = [
{ name = "uvicorn", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6361a0387241e56932f3ba2e51af27f58d11a462e3187e58286b2f96056e4d15" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:e84e731a0779f820bfe3cf4ce78cea2d09993c0a6501c63bcda93826bcd21fd0" },
]
[package.metadata]