Compare commits

...
Author SHA1 Message Date
84f072bc99 chore(deps): bump pydantic-config for dict[str, str] coercion fix (#2618)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Pulls in PrimeIntellect-ai/pydantic-config#14, which stops
`BaseConfig._coerce_dict_str_values` from rewriting string values in
`dict[str, str]` fields. Configs like
`configs/private/rlm5/glm5-swe.toml` that set
`prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0"}` previously
failed validation because "0" was coerced to int(0); they now load.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:58:54 -07:00
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
samsjaandGitHub e971d905a2 Add trainer token JSONL export (#2592)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: add trainer token jsonl export

* chore: use docstrings for token export config
2026-05-21 20:31:03 -07:00
Matej SirovatkaandGitHub 710e11912f fix: set deepgemm moe env for inference (#2591)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-22 03:46:08 +02:00
c95a943c39 feat(scheduler): train on partial groups instead of dropping on rollout error (#2590)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(scheduler): train on partial groups instead of dropping on rollout error

When an individual-scoring env returns N rollouts for a single example and one
errors out, scrap only the failed rollout — keep the survivors and ship the
group through as soon as every dispatched rollout has come back (success or
failure). Group-scoring envs still drop the whole group on any failure because
their per-rollout scores are computed against the now-missing rollouts.

To make variable-size groups round-trip through advantage computation, group
rollouts by (env_name, example_id) instead of positional slicing, and bucket
groups by size so each advantage_fn call still sees a uniform 2D rewards
tensor. Singleton groups produce zero advantage and get filtered out by the
existing zero-advantage filter — no special-casing.

Closes #2585.

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

* refactor(advantage): make advantage_fn per-group

Drop the bucket-by-size workaround in compute_advantages by changing the
advantage_fn contract: AdvantageInputs.rollouts is now a single group
(list[RolloutOutput]) and AdvantageOutputs.advantages is 1D. The framework
calls advantage_fn once per group, which works cleanly for variable-size
groups (partial-group training).

BREAKING: second change to this public API in three weeks. Custom advantage
functions must drop the outer list dim. Migration documented in CHANGELOG.md
and docs/bring-your-own-algorithms.md.

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

* refactor(advantage): return list[float] from advantage_fn

Drops the torch tensor from the public AdvantageOutputs contract; internal
math stays in torch and converts via .tolist() at the boundary. Same partial-
group support, simpler downstream consumers (no more .tolist() / no shape
gymnastics in custom advantages).

BREAKING (folds into the per-group change in the previous commit): custom
advantage functions must return AdvantageOutputs(advantages=[...]) rather
than a tensor. CHANGELOG entry and docs example updated.

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

* refactor(scheduler): log each rollout failure inline, drop GroupState.last_failure_reason

The reason is now logged at the moment the failure is observed (one warning
per failed rollout) instead of being stashed on the group and replayed at
finalization. Removes the per-group field entirely and avoids the "first vs
latest wins" semantic question that came up in review - each log line carries
its own actual reason. Finalization warnings only carry counts now.

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

* chore(scheduler): drop verbose comment on GroupState.failed_rollouts

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-21 18:40:34 -07:00
ca03d89fad feat(orchestrator): per-env state_columns for extra rollout fields (#2589)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): per-env state_columns for extra rollout fields

Adds `state_columns: list[str] = []` to `EnvConfig` so each env can
persist additional `State` fields into the saved JSONL rollouts on top
of the always-saved `trajectory` and `sampling_args`. Merged at the
call site (required first, deduped).

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

* refactor: drop seen set from state_columns dedup

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-21 18:23:30 -07:00
Matej SirovatkaandGitHub e6e814697a fix: patch deepgemm silu quant addressing (#2582)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-21 15:57:53 -07:00
f9cebaa19c fix(slurm): stop cleanup srun from self-killing (#2586)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The pre-launch cleanup block runs `pkill -9 -f "[v]llm"` to mop up
orphans from prior jobs. The `[v]llm` regex-trick relies on no literal
`vllm` appearing in the matching cmdline, but the surviving lines in the
same block do — `pkill -9 "vllm"`, `pkill -9 "vllm::.*"`, the
`/tmp/vllm-*` glob, and the closing `grep -E "...vllm..."`. With
`srun bash -c '<script>'` the entire script body lives in both srun's and
the inner bash's argv, so `[v]llm` matches them and SIGKILLs the cleanup
processes mid-flight. `set -e` then bubbles it up and the batch dies
before any component starts.

Switch to `srun bash -s <<'CLEANUP_SH' ... CLEANUP_SH`. The heredoc goes
over stdin, so the cmdline of srun and bash on every task is just
`srun bash -s` / `bash -s`. `pkill -f "[v]llm"` no longer self-matches
and the cleanup completes normally on every node.

Verified on cluster (multinode RL example): pre-fix the cleanup step
died with `9:0` in 6 s; post-fix the cleanup step exits `0:0` and the
log shows `[node-cleanup] <host> procs=1 gpu_mem=0MiB` from both nodes.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 13:45:00 -07:00
c656d2f8f2 fix(orchestrator): deep-merge legacy model/client aliases; switch multinode template to canonical CLI path (#2584)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): deep-merge legacy model/client aliases; switch multinode template to canonical CLI path

`fold_student_shortcuts` previously skipped re-nesting top-level `client`
into `student.client` when the latter was already populated (and used
`setdefault` for `model`, so existing keys won). That meant a CLI override
like `--client.base-url URL` could never reach `student.client.base_url`
once the TOML provided `[student.client]` — pydantic's `extra="forbid"`
rejected the leftover top-level `client` with `Extra inputs are not
permitted`. Same shape for `--model.<k>` against TOML `[student.model]`.

Deep-merge with the legacy (top-level / CLI) side winning at the leaf.
TOML values that the CLI doesn't touch are preserved.

Also update `multi_node_rl.sbatch.j2` to use the canonical
`--student.client.{base-url,admin-base-url}` instead of the legacy alias.
The new path is a known leaf in pydantic-config, so single-value args
get list-wrapped correctly (the legacy alias goes through the unknown-leaf
branch and would still produce a raw string).

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

* nit: rename _deep_merge_into -> deep_merge, drop redundant comment

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-21 12:17:10 -07:00
9ef2705898 fix(scheduler): drop group on rollout error instead of rescheduling (#2581)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(scheduler): drop group on rollout error instead of rescheduling

Raise per-env max_retries default from 0 to 3 so transient infra failures
are absorbed inside the env server. Drop any group whose rollout bubbles
up with an error or empty trajectory, log it, and let the rest of the
batch proceed — no in-orchestrator reschedule, no partial-group salvage.

Removes max_error_reschedule_attempts and the GroupState round/attempt
tracking. Closes #2475.

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

* fix(scheduler): count every failed rollout in error metrics

Iterating over the rollouts and breaking on the first failure undercounted
errored_rollouts/empty_rollouts for group-scoring envs (which return N
rollouts per task), deflating the reported error rate.

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

* feat(scheduler): emit error/<type>/count metric per step

Adds errors_by_type tracking keyed by ErrorInfo["error"] (the outermost
exception class name from the verifiers error chain), surfaced to wandb
as error/<type>/count. Lets dashboards see which failure mode (e.g.
OverlongPromptError vs InterceptionError vs SandboxError) is driving
dropped groups, instead of one opaque errored_rollouts rate.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 12:16:54 -07:00
92 changed files with 1391 additions and 700 deletions
+2
View File
@@ -2,6 +2,8 @@
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.
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` 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
+10 -11
View File
@@ -70,7 +70,7 @@ kwargs = { clip_eps = 0.2 }
## 2. Custom Advantage Functions
Advantages are computed **per-example** (grouped by `rollouts_per_example`). You provide a function that computes advantages for a batch of examples.
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
@@ -86,8 +86,8 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
```python
@dataclass
class AdvantageInputs:
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
rollouts: list[list[vf.RolloutOutput]]
# All rollouts for a single example (one group).
rollouts: list[vf.RolloutOutput]
```
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
@@ -97,22 +97,21 @@ Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.),
```python
@dataclass
class AdvantageOutputs:
advantages: Float[Tensor, "num_examples rollouts_per_example"]
advantages: list[float] # one entry per rollout in the input group
```
### Example: Normalized Advantage
```python
import torch
import statistics
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
"""Normalize advantages to zero mean and unit variance per example."""
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
mean = rewards.mean(dim=1, keepdim=True)
std = rewards.std(dim=1, keepdim=True)
advantages = (rewards - mean) / (std + eps)
return AdvantageOutputs(advantages=advantages)
"""Normalize advantages to zero mean and unit variance within the group."""
rewards = [r["reward"] for r in inputs.rollouts]
mean = statistics.fmean(rewards)
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
```
### Configuration
+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"
@@ -197,7 +197,7 @@ class EnvConfig(BaseConfig):
ratio: float | None = Field(None, gt=0)
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
max_retries: int = Field(0, ge=0)
max_retries: int = Field(3, ge=0)
"""Times the env server retries a failed rollout before returning an error."""
max_total_completion_tokens: int = -1
@@ -206,6 +206,9 @@ class EnvConfig(BaseConfig):
timeout: float | None = Field(None, validation_alias=AliasChoices("timeout", "timeout_seconds"))
"""Per-rollout wall-clock timeout in seconds. None disables."""
state_columns: list[str] = []
"""Extra ``State`` fields to persist into the saved rollout records (in addition to the always-saved ``trajectory`` and ``sampling_args``). Values must be JSON-serializable."""
@property
def stripped_id(self) -> str:
"""Environment ID without the @version suffix."""
@@ -247,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."""
@@ -264,7 +267,7 @@ class TrainConfig(BaseConfig):
num_workers: int | Literal["auto"] = "auto"
"""Default worker processes for env servers. Can be overridden per env."""
max_retries: int = Field(0, ge=0)
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
@model_validator(mode="after")
@@ -313,13 +316,13 @@ 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"
"""Default worker processes for env servers. Can be overridden per env."""
max_retries: int = Field(0, ge=0)
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
interval: int = Field(100, ge=1)
@@ -327,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:
@@ -337,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
@@ -619,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
@@ -635,9 +638,6 @@ class OrchestratorConfig(BaseConfig):
max_off_policy_steps: int = Field(8, ge=0)
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
max_error_reschedule_attempts: int | None = Field(3, ge=1)
"""The group is dropped from the current step's batch once this many of its dispatch rounds have returned errored or empty rollouts (the trainer proceeds with the rollouts from other groups). Counts rounds, not individual rollouts: a non-group-scoring env that dispatches ``rollouts_per_example`` rollouts at once still only counts one round per failed batch. None retries indefinitely. Useful for unblocking single-example hangs in agent envs."""
max_async_level: int = Field(1, ge=0)
"""Maximum steps inference can be ahead of training. ``0`` degenerates to synchronous on-policy RL; ``≥1`` overlaps training and inference."""
@@ -680,22 +680,34 @@ class OrchestratorConfig(BaseConfig):
if not isinstance(data, dict):
return data
def deep_merge(dst: dict, src: dict) -> None:
"""In-place recursive merge of ``src`` into ``dst``. ``src`` wins at the leaf."""
for k, v in src.items():
if isinstance(v, dict) and isinstance(dst.get(k), dict):
deep_merge(dst[k], v)
else:
dst[k] = v
# 1. Re-nest top-level [orchestrator.client] under student.client.
if "client" in data:
legacy_client = data.pop("client", None)
if isinstance(legacy_client, dict):
student = data.setdefault("student", {})
if isinstance(student, dict) and "client" not in student:
student["client"] = data.pop("client")
if isinstance(student, dict):
deep_merge(student.setdefault("client", {}), legacy_client)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["client"] = legacy_client
# 2. Consolidate the legacy `model` alias into `student` so the
# flat-layout fix-up below sees a single target.
# flat-layout fix-up below sees a single target. Deep-merge with the
# legacy keys winning so a CLI `--model.<k>` overrides TOML `student.model.<k>`.
legacy_model = data.pop("model", None)
if legacy_model is not None:
existing = data.get("student")
if existing is None:
data["student"] = legacy_model
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
for k, v in legacy_model.items():
existing.setdefault(k, v)
deep_merge(existing, legacy_model)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["model"] = legacy_model
@@ -748,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")
@@ -895,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:
@@ -909,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``."""
@@ -479,8 +479,13 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class TokenExportConfig(BaseConfig):
"""Configures per-token rollout exports from the RL trainer."""
class TrainerExperimentalConfig(BaseConfig):
pass
token_export: TokenExportConfig | None = None
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
class TrainerConfig(BaseConfig):
+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..."
+10
View File
@@ -60,6 +60,16 @@ CLI: `--env.0.id reverse-text --env.1.id math-env`.
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 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]
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
## Key files
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
+188
View File
@@ -1,4 +1,5 @@
import torch
from vllm.triton_utils import tl, triton
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
@@ -16,9 +17,55 @@ def transformers_v5_compat():
_patch_qwen35_lora()
_patch_lora_key_prefix()
monkey_patch_deep_gemm_silu_mul_quant_int64()
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():
@@ -53,6 +100,147 @@ def monkey_patch_vllm_layerwise_reload_alias_buffers():
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
@triton.jit
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
y_ptr,
y_q_ptr,
y_s_ptr,
M: tl.int64,
N: tl.int64,
y_s_col_stride: tl.int64,
eps,
clamp_limit,
fp8_min: tl.constexpr,
fp8_max: tl.constexpr,
use_ue8m0: tl.constexpr,
HAS_CLAMP: tl.constexpr,
GROUP_SIZE: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
N_2 = N // 2
m_offset = (pid_m * BLOCK_M).to(tl.int64)
n_offset = (pid_n * BLOCK_N).to(tl.int64)
if m_offset >= M:
return
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
base_y_ptr = y_ptr + m_offset * N + n_offset
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
act_in = tl.load(act_in_ptrs)
mul_in = tl.load(act_in_ptrs + N_2)
if HAS_CLAMP:
act_in = tl.minimum(act_in.to(tl.float32), clamp_limit).to(y_ptr.dtype.element_ty)
mul_in = tl.clamp(mul_in.to(tl.float32), -clamp_limit, clamp_limit).to(y_ptr.dtype.element_ty)
act_in = act_in.to(tl.float32)
one_f32 = tl.cast(1, tl.float32)
silu_out = (act_in / (one_f32 + tl.exp(-act_in))).to(y_ptr.dtype.element_ty)
y = (silu_out * mul_in).to(tl.float32)
absmax = tl.maximum(tl.max(tl.abs(y), axis=1), eps)
scale_raw = absmax * (1.0 / fp8_max)
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
y_s = tl.reshape(y_s, (BLOCK_M, 1))
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
base_y_q_ptr = y_q_ptr + m_offset * N_2 + n_offset
y_q_ptrs = base_y_q_ptr + offs_m[:, None] * N_2 + offs_n[None, :]
tl.store(y_q_ptrs, y_q)
group_id = n_offset // GROUP_SIZE
base_y_s_ptr = y_s_ptr + group_id * y_s_col_stride + m_offset
y_s_ptrs = base_y_s_ptr + offs_m
y_s = tl.reshape(y_s, (BLOCK_M,))
tl.store(y_s_ptrs, y_s)
def _silu_mul_per_token_group_quant_fp8_colmajor_int64(
input: torch.Tensor,
output: torch.Tensor | None = None,
use_ue8m0: bool | None = None,
eps: float = 1e-10,
clamp_limit: float | None = None,
):
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
group_size = 128
assert input.ndim == 2
if output is not None:
assert output.ndim == 2
assert input.size(0) % group_size == 0
assert input.size(1) % (group_size * 2) == 0
if use_ue8m0 is None:
use_ue8m0 = is_deep_gemm_e8m0_used()
M, N = input.size()
N_2 = N // 2
fp8_dtype = current_platform.fp8_dtype()
if output is None:
output = torch.empty((M, N_2), dtype=fp8_dtype, device=input.device)
output_scales = torch.empty(((N_2 // group_size), M), dtype=torch.float32, device=input.device).transpose(0, 1)
block_m = 8
block_n = group_size
assert M % block_m == 0
assert N_2 % block_n == 0
finfo = torch.finfo(fp8_dtype)
fp8_min = -224.0 if current_platform.is_fp8_fnuz() else finfo.min
fp8_max = 224.0 if current_platform.is_fp8_fnuz() else finfo.max
has_clamp = clamp_limit is not None
grid = (M // block_m, N_2 // block_n)
_silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel[grid](
input,
output,
output_scales,
M,
N,
output_scales.stride(-1),
eps,
clamp_limit if has_clamp else 0.0,
fp8_min,
fp8_max,
use_ue8m0,
has_clamp,
group_size,
block_m,
block_n,
)
return output, output_scales
def monkey_patch_deep_gemm_silu_mul_quant_int64():
import sys
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.utils import fp8_utils
logger = init_logger(__name__)
fp8_utils.silu_mul_per_token_group_quant_fp8_colmajor = _silu_mul_per_token_group_quant_fp8_colmajor_int64
deep_gemm_moe_module = sys.modules.get("vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe")
if deep_gemm_moe_module is not None:
deep_gemm_moe_module.silu_mul_per_token_group_quant_fp8_colmajor = (
_silu_mul_per_token_group_quant_fp8_colmajor_int64
)
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
def _patch_qwen35_lora():
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
@@ -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
+44 -59
View File
@@ -1,3 +1,4 @@
from collections import defaultdict
from dataclasses import dataclass
from typing import Callable
@@ -19,20 +20,16 @@ from prime_rl.utils.utils import import_object
@dataclass
class AdvantageInputs:
"""Inputs for advantage computation.
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
`rollouts` is grouped by problem: `rollouts[i][j]` is the j-th rollout for problem i,
so `len(rollouts) == num_problems` and `len(rollouts[0]) == rollouts_per_example`.
"""
rollouts: list[list[vf.RolloutOutput]]
rollouts: list[vf.RolloutOutput]
@dataclass
class AdvantageOutputs:
"""Outputs from advantage computation."""
"""Outputs from advantage computation of a single group."""
advantages: Float[Tensor, "num_problems rollouts_per_example"]
advantages: list[float]
AdvantageFn = Callable[..., AdvantageOutputs]
@@ -41,6 +38,9 @@ AdvantageFn = Callable[..., AdvantageOutputs]
Expected signature:
def my_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
...
The function receives a single group and returns a list of advantages with one
entry per rollout. `compute_advantages` calls it once per group.
"""
@@ -48,73 +48,63 @@ def default_advantage_fn(
inputs: AdvantageInputs,
length_penalty: LengthPenaltyConfig | None = None,
) -> AdvantageOutputs:
"""Default GRPO advantage: reward minus per-problem baseline.
"""Default GRPO advantage for a single group: reward minus per-group baseline.
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
cost: tokens (weighted completion + tool-response) or trajectory turn count.
"""
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts], dtype=torch.float32)
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
if isinstance(length_penalty, TokensLengthPenaltyConfig):
w_c = length_penalty.completion_weight
w_t = length_penalty.tool_response_weight
costs = torch.tensor(
[
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in group]
for group in inputs.rollouts
],
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
costs = torch.tensor(
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
costs = torch.tensor([get_num_turns(r) for r in inputs.rollouts], dtype=rewards.dtype)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
baseline = rewards.mean(dim=1, keepdim=True)
return AdvantageOutputs(advantages=rewards - baseline)
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
def _efficiency_shaping(
rewards: Float[Tensor, "num_problems rollouts_per_example"],
costs: Float[Tensor, "num_problems rollouts_per_example"],
) -> Float[Tensor, "num_problems rollouts_per_example"]:
rewards: Float[Tensor, "group_size"],
costs: Float[Tensor, "group_size"],
) -> Float[Tensor, "group_size"]:
"""Correctness-gated efficiency shaping with bounded advantages.
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
preserving zero-mean advantages per group. `costs` is a per-rollout cost (e.g.,
completion length in tokens or number of turns).
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
(e.g., completion length in tokens or number of turns).
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
"""
max_reward = rewards.max(dim=1, keepdim=True).values
max_reward = rewards.max()
correct_mask = rewards >= max_reward
num_correct = correct_mask.sum(dim=1, keepdim=True)
num_correct = correct_mask.sum()
# No shaping when max reward is 0 — no correct rollouts to differentiate
has_correct = max_reward > 0
if max_reward <= 0:
return rewards - rewards.mean()
# Mean cost of correct rollouts per problem
correct_costs = costs * correct_mask
mean_correct_cost = correct_costs.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
# Mean cost of correct rollouts
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
has_cost = mean_correct_cost > 0
safe_mean = torch.where(has_cost, mean_correct_cost, torch.ones_like(mean_correct_cost))
bonus = (1 - costs / safe_mean).clamp(0, 1) * has_cost
if mean_correct_cost <= 0:
return rewards - rewards.mean()
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
shaped_rewards = rewards * (1 + bonus * correct_mask)
baseline = shaped_rewards.mean(dim=1, keepdim=True)
shaped = shaped_rewards - baseline
unshaped = rewards - rewards.mean(dim=1, keepdim=True)
return torch.where(has_correct, shaped, unshaped)
return shaped_rewards - shaped_rewards.mean()
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
@@ -136,31 +126,26 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
def compute_advantages(
rollouts: list[vf.RolloutOutput],
samples_per_problem: int,
advantage_config: AdvantageConfig | None,
) -> None:
"""
Computes advantages from rollouts, grouped by problem.
Stores advantages in-place on the rollouts.
"""Computes advantages from rollouts, grouped by (env_name, example_id), and
stores them in-place on the rollouts.
Args:
rollouts: List of rollouts to store advantages on
samples_per_problem: Number of samples (and thus, rewards) per problem
advantage_config: Configuration for advantage computation (DefaultAdvantageConfig or CustomAdvantageConfig)
`advantage_fn` is called once per group, so groups may have varying sizes
(partial-group training drops failed rollouts rather than rescheduling them).
"""
rewards = [r["reward"] for r in rollouts]
if not advantage_config:
for rollout, reward in zip(rollouts, rewards):
rollout["advantage"] = reward
for rollout in rollouts:
rollout["advantage"] = rollout["reward"]
return
advantage_fn = setup_advantage_fn(advantage_config)
grouped = [rollouts[i : i + samples_per_problem] for i in range(0, len(rollouts), samples_per_problem)]
inputs = AdvantageInputs(rollouts=grouped)
result = advantage_fn(inputs)
advantages = result.advantages.flatten().tolist()
groups_by_example: dict[tuple[str, int], list[vf.RolloutOutput]] = defaultdict(list)
for rollout in rollouts:
groups_by_example[(rollout["env_name"], rollout["example_id"])].append(rollout)
for rollout, advantage in zip(rollouts, advantages):
rollout["advantage"] = advantage
for group in groups_by_example.values():
result = advantage_fn(AdvantageInputs(rollouts=group))
for rollout, advantage in zip(group, result.advantages):
rollout["advantage"] = advantage
+23 -16
View File
@@ -110,6 +110,15 @@ class Env:
sampling_args["extra_body"] = extra_body
return sampling_args
@property
def state_columns(self) -> list[str]:
"""Required columns plus any extras configured on the env, deduped (required first)."""
merged: list[str] = []
for col in (*REQUIRED_STATE_COLUMNS, *self.config.state_columns):
if col not in merged:
merged.append(col)
return merged
async def run_rollout(
self,
client: vf.ClientConfig,
@@ -124,7 +133,7 @@ class Env:
model=model_name,
sampling_args=self._sampling_args_with_salt(cache_salt),
max_retries=self.config.max_retries,
state_columns=REQUIRED_STATE_COLUMNS,
state_columns=self.state_columns,
env_client=self.env_client,
)
@@ -133,17 +142,17 @@ 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),
max_retries=self.config.max_retries,
state_columns=REQUIRED_STATE_COLUMNS,
state_columns=self.state_columns,
env_client=self.env_client,
)
@@ -182,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]
@@ -226,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)
@@ -282,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():
@@ -298,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.rollouts_per_example, 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)))
+54 -69
View File
@@ -32,8 +32,6 @@ class InflightRequest:
env_name: str
group_id: int | None = None
rollout_count: int = 1
# Dispatch round the request belongs to (see GroupState.current_round).
round_id: int = 0
@dataclass
@@ -44,19 +42,7 @@ class GroupState:
rollouts_to_schedule: int
completed_rollouts: list[vf.RolloutOutput] = field(default_factory=list)
pinned_client: vf.ClientConfig | None = None
# Number of dispatch rounds in which at least one rollout returned errored
# or empty trajectories. Compared against
# config.max_error_reschedule_attempts to decide when to drop a
# permanently-stuck group. Counts rounds, not rollouts: a failed round in
# an individual-scoring env that happens to dispatch N rollouts at once
# still only counts as 1.
failed_attempts: int = 0
# Round id assigned to newly-dispatched rollouts. Advances after a failure
# is counted so the resulting reschedule starts a new round.
current_round: int = 0
# Highest round already counted as failed; used to dedupe failures from
# multiple rollouts in the same round.
last_failed_round: int = -1
failed_rollouts: int = 0
class Scheduler:
@@ -94,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
@@ -136,6 +122,7 @@ class Scheduler:
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_env: dict[str, int] = defaultdict(int)
self.errored_rollouts_by_env: dict[str, int] = defaultdict(int)
self.errors_by_type: dict[str, int] = defaultdict(int)
self.total_rollouts_by_env: dict[str, int] = defaultdict(int)
self.dropped_groups_by_env: dict[str, int] = defaultdict(int)
self.last_batch_generation_time = 0.0
@@ -232,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,
)
)
@@ -253,7 +240,6 @@ class Scheduler:
env_name=env_name,
group_id=group_id,
rollout_count=rollout_count,
round_id=group.current_round,
)
@property
@@ -280,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
@@ -446,74 +432,70 @@ class Scheduler:
if group is None:
continue
env = self.train_envs.get(env_name)
result = finished_task.result()
rollouts: list[vf.RolloutOutput] = result if isinstance(result, list) else [result]
self.total_rollouts_by_env[env_name] += len(rollouts)
# Check for empty/errored rollouts and reschedule
valid_rollouts = []
has_failures = False
last_failure_reason: str | None = None
# Partition rollouts into valid vs failed and tally per-rollout
# error metrics. Tally every failure (group-scoring envs return
# N rollouts per task) so error-rate metrics aren't deflated.
env = self.train_envs.get(env_name)
valid_rollouts: list[vf.RolloutOutput] = []
for rollout in rollouts:
if rollout["error"] is not None:
self.errored_rollouts_by_env[env_name] += 1
has_failures = True
last_failure_reason = rollout["error"]["error_chain_repr"]
self.errors_by_type[rollout["error"]["error"]] += 1
self.logger.warning(
f"Rollout error in group {group_id} ({env_name}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
f"{last_failure_reason}"
f"Rollout failed in group {group_id} ({env_name}) - "
f"{rollout['error']['error_chain_repr']}"
)
elif len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_env[env_name] += 1
has_failures = True
last_failure_reason = "empty trajectory"
self.logger.warning(
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
)
self.logger.warning(f"Empty trajectory in group {group_id} ({env_name})")
else:
rollout["env_name"] = env_name
valid_rollouts.append(rollout)
if has_failures:
# Dedupe failures within the same dispatch round: an
# individual-scoring env dispatches N rollouts at once,
# so a single failed round can produce up to N failed
# tasks. We only count the round once.
if rollout_info.round_id > group.last_failed_round:
group.failed_attempts += 1
group.last_failed_round = rollout_info.round_id
group.current_round = rollout_info.round_id + 1
max_attempts = self.config.max_error_reschedule_attempts
if max_attempts is not None and group.failed_attempts >= max_attempts:
# Permanently-stuck group: drop it from this step and let the
# rest of the batch proceed. Avoids a single bad example (e.g.
# an agent rollout whose sandbox poll keeps timing out)
# blocking step progress forever.
self.dropped_groups_by_env[env_name] += 1
self.logger.warning(
f"Dropping group {group_id} ({env_name}) after {group.failed_attempts} "
f"failed dispatch rounds ({len(group.completed_rollouts)}/{self.rollouts_per_example} "
f"complete). Last failure: {last_failure_reason}. Set "
f"orchestrator.max_error_reschedule_attempts higher (or to None) "
f"to retry more aggressively."
)
await self.drop_group(group_id)
continue
num_failed = len(rollouts) - len(valid_rollouts)
group.failed_rollouts += num_failed
if has_failures and env.requires_group_scoring:
# Group scoring requires all rollouts — discard partial results, reschedule full group
group.completed_rollouts.clear()
group.rollouts_to_schedule = self.rollouts_per_example
# Group-scoring envs compute scores over all N rollouts
# together; the surviving rollouts carry scores computed against
# the (now-missing) failed ones, so partial salvage is unsafe.
# Drop the whole group on any failure.
if num_failed > 0 and env.requires_group_scoring:
self.dropped_groups_by_env[env_name] += 1
self.logger.warning(
f"Dropping group-scored group {group_id} ({env_name}) after rollout failure"
)
await self.drop_group(group_id)
continue
# For individual scoring, reschedule only the failed ones
group.rollouts_to_schedule += len(rollouts) - len(valid_rollouts)
group.completed_rollouts.extend(valid_rollouts)
if len(group.completed_rollouts) < self.rollouts_per_example:
# Wait until every dispatched rollout has come back (succeeded
# or failed) before finalizing. The group may finalize as a
# 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.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.group_size} rollouts failed"
)
self.groups.pop(group_id, None)
continue
if group.failed_rollouts > 0:
self.logger.warning(
f"Partial group {group_id} ({env_name}) - "
f"{len(group.completed_rollouts)}/{self.group_size} valid "
f"({group.failed_rollouts} failed)"
)
completed_rollouts = self.groups.pop(group_id).completed_rollouts
except asyncio.CancelledError:
@@ -527,7 +509,7 @@ class Scheduler:
continue
self.buffer.update(completed_rollouts)
accepted_rollouts = self.buffer.sample_rollouts(n=self.rollouts_per_example)
accepted_rollouts = self.buffer.sample_rollouts(n=len(completed_rollouts))
batch_rollouts.extend(accepted_rollouts)
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
@@ -589,6 +571,8 @@ class Scheduler:
metrics[f"errored_rollouts/{env_name}"] = self.errored_rollouts_by_env.get(env_name, 0) / env_total
for env_name, count in self.dropped_groups_by_env.items():
metrics[f"dropped_groups/{env_name}"] = count
for error_type, count in self.errors_by_type.items():
metrics[f"error/{error_type}/count"] = count
by_env: dict[str, list[int]] = {}
for info in self.inflight_requests.values():
by_env.setdefault(info.env_name, []).append(info.off_policy_steps)
@@ -598,6 +582,7 @@ class Scheduler:
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_env.clear()
self.errored_rollouts_by_env.clear()
self.errors_by_type.clear()
self.total_rollouts_by_env.clear()
self.dropped_groups_by_env.clear()
+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):
+7 -2
View File
@@ -116,7 +116,11 @@ echo "INFER_URLS=${INFER_URLS}"
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
# termination and cause the next launch to hang (e.g. decode engines stuck at
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
srun bash -c '
#
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
# because the surviving literal `vllm` strings below appear in the cmdline.
srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
@@ -131,7 +135,7 @@ srun bash -c '
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
'
CLEANUP_SH
# Run inference
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
@@ -171,6 +175,7 @@ srun --kill-on-bad-exit=1 bash -c '
export VLLM_WORKER_MULTIPROC_METHOD=spawn
{%- if use_deep_gemm %}
export VLLM_USE_DEEP_GEMM=1
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
export GLOO_SOCKET_IFNAME=bond0
@@ -160,7 +160,11 @@ uv sync --all-extras
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
# termination and cause the next launch to hang (e.g. decode engines stuck at
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
srun bash -c '
#
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
# because the surviving literal `vllm` strings below appear in the cmdline.
srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
@@ -175,7 +179,7 @@ srun bash -c '
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
'
CLEANUP_SH
# Run RL
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
@@ -224,6 +228,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if use_deep_gemm %}
export VLLM_USE_DEEP_GEMM=1
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
export GLOO_SOCKET_IFNAME=bond0
@@ -376,8 +381,8 @@ else
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --client.admin-base-url $ADMIN_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if wandb_shared %}WANDB_SHARED_LABEL=orchestrator {% endif %}uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
@@ -67,7 +67,11 @@ cd $PROJECT_DIR && uv sync --all-extras
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
# termination and cause the next launch to hang. Harmless on clean nodes.
srun bash -c '
#
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
# because the surviving literal `vllm` strings below appear in the cmdline.
srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
@@ -82,7 +86,7 @@ srun bash -c '
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
'
CLEANUP_SH
# Run SFT
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
+75 -8
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:
@@ -12,6 +58,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
loss_mask = training_example.prompt_mask + training_example.completion_mask
inference_logprobs = [0.0] * len(training_example.prompt_ids) + training_example.completion_logprobs
advantages = [training_example.advantage] * len(input_ids)
reward = training_example.reward if training_example.reward is not None else float("nan")
rewards = [reward] * len(input_ids)
position_ids = list(range(len(input_ids)))
mm_token_type_ids = training_example.mm_token_type_ids
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
@@ -25,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]
@@ -33,11 +83,12 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
inference_logprobs = inference_logprobs[:seq_len]
position_ids = position_ids[:seq_len]
advantages = advantages[:seq_len]
rewards = rewards[:seq_len]
temperatures = temperatures[:seq_len]
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]
@@ -48,17 +99,19 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
== len(loss_mask)
== len(position_ids)
== len(inference_logprobs)
== len(rewards)
== len(temperatures)
), (
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}, temperatures: {len(temperatures)}"
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}, rewards: {len(rewards)}, temperatures: {len(temperatures)}"
)
if teacher_logprobs is not None:
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), (
@@ -74,6 +127,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
inference_logprobs=inference_logprobs,
teacher_logprobs=teacher_logprobs,
temperatures=temperatures,
rewards=rewards,
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
@@ -122,19 +176,28 @@ def packed_samples_into_micro_bs(
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
and bin_content.training_mode == sample.training_mode
):
existing_len = len(bin_content.input_ids)
bin_content.input_ids.extend(sample.input_ids)
bin_content.loss_mask.extend(sample.loss_mask)
bin_content.advantages.extend(sample.advantages)
if sample.rewards is not None:
if bin_content.rewards is None:
bin_content.rewards = [float("nan")] * existing_len
bin_content.rewards.extend(sample.rewards)
elif bin_content.rewards is not None:
bin_content.rewards.extend([float("nan")] * len(sample.input_ids))
bin_content.inference_logprobs.extend(sample.inference_logprobs)
bin_content.temperatures.extend(sample.temperatures)
if sample.teacher_logprobs is not None:
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 = []
@@ -175,6 +238,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
micro_batch.input_ids.extend([1] * padding_size)
micro_batch.advantages.extend([0.0] * padding_size)
if micro_batch.rewards is not None:
micro_batch.rewards.extend([float("nan")] * padding_size)
micro_batch.loss_mask.extend([False] * padding_size)
micro_batch.position_ids.extend(list(range(padding_size)))
micro_batch.inference_logprobs.extend([0.0] * padding_size)
@@ -187,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
+19 -5
View File
@@ -20,6 +20,7 @@ class TensorMicroBatch(TypedDict):
input_ids: Int[Tensor, "batch seq"]
position_ids: Int[Tensor, "batch seq"]
advantages: Float[Tensor, "batch seq"]
rewards: Float[Tensor, "batch seq"] | None
inference_logprobs: Float[Tensor, "batch seq"]
teacher_logprobs: Float[Tensor, "batch seq"] | None
loss_mask: Bool[Tensor, "batch seq"]
@@ -108,6 +109,7 @@ class FakeDataLoader:
"input_ids": input_ids.unsqueeze(0),
"position_ids": position_ids.unsqueeze(0),
"advantages": advantages.unsqueeze(0),
"rewards": None,
"inference_logprobs": inference_logprobs.unsqueeze(0),
"teacher_logprobs": None,
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
@@ -135,6 +137,7 @@ class FakeDataLoader:
),
"position_ids": torch.cat([torch.arange(self.seq_len)]).unsqueeze(0),
"advantages": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
"rewards": None,
"inference_logprobs": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
"teacher_logprobs": None,
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
@@ -207,10 +210,25 @@ 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),
advantages=torch.tensor(micro_batch.advantages, dtype=torch.float).unsqueeze(0),
rewards=torch.tensor(micro_batch.rewards, dtype=torch.float).unsqueeze(0)
if micro_batch.rewards is not None
else None,
inference_logprobs=torch.tensor(micro_batch.inference_logprobs, dtype=torch.float).unsqueeze(0),
teacher_logprobs=torch.tensor(micro_batch.teacher_logprobs, dtype=torch.float).unsqueeze(0)
if micro_batch.teacher_logprobs is not None
@@ -223,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,
)
+237
View File
@@ -0,0 +1,237 @@
import atexit
import json
import math
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any
import torch
from torch import Tensor
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
SCHEMA_VERSION = 1
class DisabledTokenExporter:
def export(self, *args: Any, **kwargs: Any) -> None:
return
def close(self) -> None:
return
class TokenExporter:
def __init__(
self,
output_dir: Path,
rank: int,
) -> None:
self.rank = rank
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
atexit.register(self.close)
def export(
self,
step: int,
micro_step: int,
micro_batch: Mapping[str, Any],
model_output: Mapping[str, Tensor],
response_lengths: list[int],
loss_config: Any,
) -> None:
if self._current_step != step:
self._start_step(step)
columns = _export_columns(micro_batch, model_output, loss_config)
_check_lengths(columns)
start = 0
for micro_sequence_idx, length in enumerate(response_lengths):
raw_end = start + length
end = _trim_padding(columns, start, raw_end)
if end > start and any(columns["loss_mask"][start:end]):
self._write(
{
"schema_version": SCHEMA_VERSION,
"step": step,
"rank": self.rank,
"micro_step": micro_step,
"micro_sequence_idx": micro_sequence_idx,
"export_sequence_idx": self._sequences_this_step,
"env_name": _first_non_empty(columns["env_names"][start:end]),
"training_mode": str(micro_batch["training_mode"]),
**_slice_columns(columns, start, end),
}
)
self._sequences_this_step += 1
start = raw_end
def close(self) -> None:
if self._closed:
return
self._closed = True
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.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")
def setup_token_exporter(
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
) -> TokenExporter | DisabledTokenExporter:
token_export_config = config.experimental.token_export
if token_export_config is None:
return DisabledTokenExporter()
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
return DisabledTokenExporter()
exporter = TokenExporter(config.output_dir, world.rank)
logger.info(f"Writing token exports under {exporter.output_dir}")
return exporter
def _export_columns(
micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor], loss_config: Any
) -> dict[str, list[Any]]:
token_ids = _tensor_to_ints(micro_batch["input_ids"])
seq_len = len(token_ids)
trainer_logprobs = model_output["logprobs"]
export_tensors = _compute_export_tensors(micro_batch, trainer_logprobs, loss_config)
return {
"token_ids": token_ids,
"position_ids": _tensor_to_ints(micro_batch["position_ids"]),
"loss_mask": _tensor_to_bools(micro_batch["loss_mask"]),
"advantages": _tensor_to_floats(micro_batch["advantages"]),
"rewards": _optional_tensor_to_floats(micro_batch.get("rewards"), seq_len),
"inference_logprobs": _tensor_to_floats(micro_batch["inference_logprobs"]),
"trainer_logprobs": _tensor_to_floats(trainer_logprobs),
"entropy": _tensor_to_floats(model_output["entropy"]),
"mismatch_kl": _optional_tensor_to_floats(export_tensors["mismatch_kl"], seq_len),
"log_importance_ratio": _optional_tensor_to_floats(export_tensors["log_importance_ratio"], seq_len),
"importance_ratio": _optional_tensor_to_floats(export_tensors["importance_ratio"], seq_len),
"prob_delta": _optional_tensor_to_floats(export_tensors["prob_delta"], seq_len),
"is_masked": _optional_tensor_to_bools(export_tensors["is_masked"], seq_len),
"is_masked_high": _optional_tensor_to_bools(export_tensors["is_masked_high"], seq_len),
"is_masked_low": _optional_tensor_to_bools(export_tensors["is_masked_low"], seq_len),
"env_names": list(micro_batch["env_names"]),
}
def _compute_export_tensors(
micro_batch: Mapping[str, Any], trainer_logprobs: Tensor, loss_config: Any
) -> dict[str, Tensor | None]:
fields: dict[str, Tensor | None] = {
"log_importance_ratio": None,
"importance_ratio": None,
"mismatch_kl": None,
"prob_delta": None,
"is_masked": None,
"is_masked_high": None,
"is_masked_low": None,
}
if micro_batch["training_mode"] == "sft":
return fields
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
advantages = micro_batch["advantages"].to(trainer_logprobs.device)
with torch.no_grad():
log_ratio, ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(trainer_logprobs, inference_logprobs)
prob_delta = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
fields["log_importance_ratio"] = log_ratio
fields["importance_ratio"] = ratio
fields["mismatch_kl"] = mismatch_kl
fields["prob_delta"] = prob_delta
if isinstance(loss_config, DefaultLossConfig):
invalid_high = prob_delta > loss_config.dppo_mask_high
invalid_low = prob_delta < -loss_config.dppo_mask_low
positive_advantages = advantages > 0
negative_advantages = advantages < 0
invalid = torch.where(positive_advantages, invalid_high, invalid_low)
fields["is_masked"] = loss_mask & invalid
fields["is_masked_high"] = loss_mask & positive_advantages & invalid_high
fields["is_masked_low"] = loss_mask & negative_advantages & invalid_low
return fields
def _tensor_to_ints(tensor: Tensor) -> list[int]:
return [int(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
def _tensor_to_bools(tensor: Tensor) -> list[bool]:
return [bool(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
return [_json_float(value) for value in values]
def _optional_tensor_to_floats(tensor: Tensor | None, seq_len: int) -> list[float | None]:
if tensor is None:
return [None] * seq_len
return _tensor_to_floats(tensor)
def _optional_tensor_to_bools(tensor: Tensor | None, seq_len: int) -> list[bool | None]:
if tensor is None:
return [None] * seq_len
return _tensor_to_bools(tensor)
def _check_lengths(columns: Mapping[str, Sequence[Any]]) -> None:
lengths = {key: len(values) for key, values in columns.items()}
if len(set(lengths.values())) != 1:
raise ValueError(f"Token export fields must have aligned lengths, got {lengths}")
def _slice_columns(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> dict[str, list[Any]]:
return {key: list(values[start:end]) for key, values in columns.items() if key != "env_names"}
def _trim_padding(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> int:
env_names = columns["env_names"]
loss_mask = columns["loss_mask"]
while end > start and env_names[end - 1] == "" and not loss_mask[end - 1]:
end -= 1
return end
def _json_float(value: float | None) -> float | None:
if value is None:
return None
value = float(value)
if not math.isfinite(value):
return None
return value
def _first_non_empty(values: Sequence[str]) -> str | None:
for value in values:
if value:
return value
return None
+7
View File
@@ -35,6 +35,7 @@ from prime_rl.trainer.rl.loss import (
shift_tensor_left,
shift_tensor_right,
)
from prime_rl.trainer.rl.token_export import setup_token_exporter
from prime_rl.trainer.model import (
forward,
setup_tokenizer,
@@ -239,6 +240,8 @@ def train(config: TrainerConfig):
config.rollout_transport,
)
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
@@ -500,6 +503,8 @@ def train(config: TrainerConfig):
for env_name, indices in env_to_indices.items():
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
if is_tt_moe_model(model):
load_balance_stats = get_load_balance_stats(model)
for k, v in load_balance_stats.items():
@@ -678,6 +683,8 @@ def train(config: TrainerConfig):
prof.export_chrome_trace(trace_file)
logger.info(f"Saved trace to {trace_file}")
token_exporter.close()
# Write final checkpoint (only for single-run mode; multi-run checkpoints are managed by MultiCheckpointManager)
if config.max_concurrent_runs == 1 and ckpt_manager is not None:
if not (config.ckpt and config.ckpt.weights_only):
+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:
+11 -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
@@ -80,3 +88,4 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
# Loss dispatch is batch-driven (rl/opd → default loss with mode-specific taus,
# sft → sft loss). All samples packed into a micro batch share the same mode.
training_mode: TrainingMode = "rl"
rewards: list[float] | 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():
+166 -169
View File
@@ -1,4 +1,6 @@
import torch
import math
import pytest
from prime_rl.configs.orchestrator import (
CustomAdvantageConfig,
@@ -15,7 +17,13 @@ from prime_rl.orchestrator.advantage import (
)
def _make_rollout(reward: float, completion_len: int = 0, num_turns: int = 1) -> dict:
def _make_rollout(
reward: float,
completion_len: int = 0,
num_turns: int = 1,
env_name: str = "test",
example_id: int = 0,
) -> dict:
"""Create a minimal rollout dict for advantage testing.
`completion_len` tokens are split across `num_turns` trajectory steps.
@@ -25,21 +33,21 @@ def _make_rollout(reward: float, completion_len: int = 0, num_turns: int = 1) ->
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
for i in range(num_turns)
]
return {"reward": reward, "trajectory": trajectory}
return {
"reward": reward,
"trajectory": trajectory,
"env_name": env_name,
"example_id": example_id,
}
def _make_inputs(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
"""Build AdvantageInputs from 2D arrays of rewards/lengths/turns."""
rewards_t = torch.as_tensor(rewards, dtype=torch.float32)
num_problems, rollouts_per_example = rewards_t.shape
def _make_group(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths/turns."""
rollouts = []
for i in range(num_problems):
group = []
for j in range(rollouts_per_example):
cl = int(completion_lengths[i][j]) if completion_lengths is not None else 0
nt = int(num_turns[i][j]) if num_turns is not None else 1
group.append(_make_rollout(float(rewards_t[i, j]), cl, nt))
rollouts.append(group)
for i, reward in enumerate(rewards):
cl = int(completion_lengths[i]) if completion_lengths is not None else 0
nt = int(num_turns[i]) if num_turns is not None else 1
rollouts.append(_make_rollout(float(reward), cl, nt))
return AdvantageInputs(rollouts=rollouts)
@@ -49,23 +57,16 @@ _TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_respon
def test_default_advantage_fn_simple_mean():
inputs = _make_inputs(
rewards=[[1.0, 0.5, 0.8], [0.2, 0.9, 0.1]],
completion_lengths=[[10, 12, 8], [15, 11, 9]],
)
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
result = default_advantage_fn(inputs)
assert result.advantages.shape == (2, 3)
# Check that mean is subtracted per row
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
assert len(result.advantages) == 3
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_mixed_group():
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0, 1.0]],
completion_lengths=[[10, 30, 20, 20]],
)
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# mean_correct_len = (10+30+20)/3 = 20
@@ -73,247 +74,190 @@ def test_efficiency_mixed_group():
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
# baseline = mean(shaped_rewards) = 0.875
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
expected = torch.tensor([[0.625, 0.125, -0.875, 0.125]])
assert torch.allclose(result.advantages, expected, atol=1e-6)
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
# Zero-mean per group
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
# All correct rollouts have positive advantage
rewards = torch.tensor([r["reward"] for r in inputs.rollouts[0]])
correct_mask = rewards >= 1.0
assert (result.advantages[0][correct_mask] > 0).all()
for rollout, adv in zip(inputs.rollouts, result.advantages):
if rollout["reward"] >= 1.0:
assert adv > 0
def test_efficiency_all_correct_group():
"""All-correct group: zero-mean, shorter gets higher advantage."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 1.0]],
completion_lengths=[[10, 20, 40]],
)
inputs = _make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 40])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# mean_len = 70/3 ≈ 23.33
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
# baseline = mean = (11/7 + 8/7 + 1) / 3 = (11+8+7)/(7*3) = 26/21
# A = shaped - baseline
shaped = torch.tensor([[11.0 / 7, 8.0 / 7, 1.0]])
baseline = shaped.mean(dim=1, keepdim=True)
expected = shaped - baseline
assert torch.allclose(result.advantages, expected, atol=1e-6)
shaped = [11.0 / 7, 8.0 / 7, 1.0]
mean_shaped = sum(shaped) / len(shaped)
expected = [s - mean_shaped for s in shaped]
assert result.advantages == pytest.approx(expected, abs=1e-6)
# Zero-mean
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
# Shortest has highest advantage
assert result.advantages[0, 0] > result.advantages[0, 1] > result.advantages[0, 2]
assert result.advantages[0] > result.advantages[1] > result.advantages[2]
def test_efficiency_all_zero_rewards():
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
inputs = _make_inputs(
rewards=[[0.0, 0.0, 0.0]],
completion_lengths=[[10, 20, 15]],
)
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 20, 15])
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
result_without = default_advantage_fn(inputs)
assert torch.allclose(result_with.advantages, result_without.advantages, atol=1e-6)
assert result_with.advantages == pytest.approx(result_without.advantages, abs=1e-6)
def test_efficiency_single_correct():
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
inputs = _make_inputs(
rewards=[[1.0, 0.0, 0.0, 0.0]],
completion_lengths=[[100, 50, 200, 150]],
)
inputs = _make_group(rewards=[1.0, 0.0, 0.0, 0.0], completion_lengths=[100, 50, 200, 150])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
expected = torch.tensor([[0.75, -0.25, -0.25, -0.25]])
assert torch.allclose(result.advantages, expected, atol=1e-6)
assert result.advantages == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
def test_efficiency_shorter_correct_higher_advantage():
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 1.0, 0.0, 0.0]],
completion_lengths=[[50, 100, 200, 80, 120]],
)
inputs = _make_group(rewards=[1.0, 1.0, 1.0, 0.0, 0.0], completion_lengths=[50, 100, 200, 80, 120])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
advs = result.advantages[0]
advs = result.advantages
assert advs[0] > advs[1] > advs[2]
assert (advs[:3] > 0).all()
assert (advs[3:] < 0).all()
assert all(a > 0 for a in advs[:3])
assert all(a < 0 for a in advs[3:])
def test_efficiency_zero_mean_per_group():
"""Reward shaping preserves zero-mean advantages per group."""
inputs = _make_inputs(
rewards=[
[1.0, 1.0, 0.0, 1.0], # mixed
[1.0, 1.0, 1.0, 1.0], # all correct
],
completion_lengths=[
[10, 30, 20, 20],
[10, 20, 40, 80],
],
"""Reward shaping preserves zero-mean advantages within each group."""
mixed = default_advantage_fn(
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20]),
length_penalty=_TOKENS_COMPLETION,
)
all_correct = default_advantage_fn(
_make_group(rewards=[1.0, 1.0, 1.0, 1.0], completion_lengths=[10, 20, 40, 80]),
length_penalty=_TOKENS_COMPLETION,
)
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
assert sum(mixed.advantages) == pytest.approx(0.0, abs=1e-6)
assert sum(all_correct.advantages) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_amplification_bounded():
"""Even with extreme length outliers, reward amplification is capped at 2x."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0]],
completion_lengths=[[1, 10000, 5000]],
)
inputs = _make_group(rewards=[1.0, 1.0, 0.0], completion_lengths=[1, 10000, 5000])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
# Standard reward = 1, so amplification ≈ 2x
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
assert result.advantages[0, 0] < 1.0 + 1e-3
def test_efficiency_multiple_problems():
"""Handles multiple problems independently."""
inputs = _make_inputs(
rewards=[
[1.0, 1.0, 0.0], # mixed
[1.0, 1.0, 1.0], # all correct
],
completion_lengths=[
[10, 20, 15],
[10, 20, 40],
],
)
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# Row 0: mixed group — shorter correct > longer correct
assert result.advantages[0, 0] > result.advantages[0, 1]
assert (result.advantages[0, :2] > 0).all()
assert result.advantages[0, 2] < 0
# Row 1: all-correct group — shorter gets higher advantage
assert result.advantages[1, 0] > result.advantages[1, 1] > result.advantages[1, 2]
# Both rows have zero-mean
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
assert result.advantages[0] < 1.0 + 1e-3
def test_efficiency_tokens_with_tool_response_weight():
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
rollouts = [
[
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 200},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 0},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 100},
},
]
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 200},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 0},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 100},
},
]
inputs = AdvantageInputs(rollouts=rollouts)
# completion tokens identical (10 each) → completion-only shaping is a no-op
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert torch.allclose(result_completion_only.advantages, torch.zeros(1, 3), atol=1e-6)
assert result_completion_only.advantages == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
advs = result_tool_only.advantages[0]
advs = result_tool_only.advantages
assert advs[1] > advs[0]
assert advs[1] > advs[2]
assert torch.allclose(advs[0], advs[2], atol=1e-6)
assert torch.allclose(result_tool_only.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_fractional_weight_with_int_rewards():
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
rollouts_int = [
[
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
]
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
]
rollouts_float = [[{**r, "reward": float(r["reward"])} for r in g] for g in rollouts_int]
rollouts_float = [{**r, "reward": float(r["reward"])} for r in rollouts_int]
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
assert torch.allclose(int_result.advantages, float_result.advantages, atol=1e-6)
assert int_result.advantages == pytest.approx(float_result.advantages, abs=1e-6)
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
# tool-only weights but no harness metric → all costs == 0
rollouts = [
[
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
]
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
]
inputs = AdvantageInputs(rollouts=rollouts)
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
expected = default_advantage_fn(inputs) # plain GRPO
assert not torch.isnan(result.advantages).any()
assert torch.allclose(result.advantages, expected.advantages, atol=1e-6)
assert not any(math.isnan(a) for a in result.advantages)
assert result.advantages == pytest.approx(expected.advantages, abs=1e-6)
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0, 1.0]],
completion_lengths=[[10, 30, 20, 20]],
)
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert torch.allclose(result_default.advantages, result_completion.advantages, atol=1e-6)
assert result_default.advantages == pytest.approx(result_completion.advantages, abs=1e-6)
def test_efficiency_turns_penalty():
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0, 1.0]],
inputs = _make_group(
rewards=[1.0, 1.0, 0.0, 1.0],
# token counts identical, but turns differ — turns penalty should still differentiate
completion_lengths=[[100, 100, 100, 100]],
num_turns=[[1, 3, 2, 2]],
completion_lengths=[100, 100, 100, 100],
num_turns=[1, 3, 2, 2],
)
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
# mean_correct_turns = (1+3+2)/3 = 2
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
expected = torch.tensor([[0.625, 0.125, -0.875, 0.125]])
assert torch.allclose(result.advantages, expected, atol=1e-6)
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
def test_compute_advantages_with_config():
rewards = [1.0, 0.5, 0.8, 0.2, 0.9, 0.1]
lengths = [10, 12, 8, 15, 11, 9]
rollouts = [_make_rollout(r, l) for r, l in zip(rewards, lengths)]
rollouts = [_make_rollout(r, l, example_id=i // 3) for i, (r, l) in enumerate(zip(rewards, lengths))]
compute_advantages(rollouts, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
assert len(advantages) == 6
assert abs(sum(advantages[:3])) < 1e-5
assert abs(sum(advantages[3:])) < 1e-5
assert sum(advantages[:3]) == pytest.approx(0.0, abs=1e-5)
assert sum(advantages[3:]) == pytest.approx(0.0, abs=1e-5)
def test_compute_advantages_no_cross_group_leakage():
@@ -321,18 +265,15 @@ def test_compute_advantages_no_cross_group_leakage():
Two problems with very different reward scales — cross-group leakage would pull the
small-scale group's advantages toward the large-scale group's mean (and vice versa).
Distinct positional values also catch slicing/transpose bugs in the flat→grouped→flat
round-trip.
Distinct positional values also catch ordering bugs in the group→flat round-trip.
"""
rewards = [10.0, 20.0, 30.0, 0.0, 0.1, 0.2]
rollouts = [_make_rollout(r) for r in rewards]
rollouts = [_make_rollout(r, example_id=i // 3) for i, r in enumerate(rewards)]
compute_advantages(rollouts, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
expected = [-10.0, 0.0, 10.0, -0.1, 0.0, 0.1]
for got, want in zip(advantages, expected):
assert abs(got - want) < 1e-5, (advantages, expected)
assert advantages == pytest.approx([-10.0, 0.0, 10.0, -0.1, 0.0, 0.1], abs=1e-5)
def test_compute_advantages_without_config():
@@ -340,12 +281,72 @@ def test_compute_advantages_without_config():
lengths = [10, 12, 8]
rollouts = [_make_rollout(r, l) for r, l in zip(rewards, lengths)]
compute_advantages(rollouts, samples_per_problem=3, advantage_config=None)
compute_advantages(rollouts, advantage_config=None)
advantages = [r["advantage"] for r in rollouts]
assert advantages == rewards
def test_compute_advantages_partial_groups():
"""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.
"""
# Group A (example_id=0): 4 rollouts. Group B (example_id=1): 2 rollouts.
rollouts = [
_make_rollout(1.0, example_id=0),
_make_rollout(0.0, example_id=0),
_make_rollout(1.0, example_id=0),
_make_rollout(0.0, example_id=0),
_make_rollout(0.3, example_id=1),
_make_rollout(0.7, example_id=1),
]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
# Group A: mean=0.5, advantages=[0.5, -0.5, 0.5, -0.5]
assert advantages[:4] == pytest.approx([0.5, -0.5, 0.5, -0.5], abs=1e-5)
# Group B: mean=0.5, advantages=[-0.2, 0.2]
assert advantages[4:] == pytest.approx([-0.2, 0.2], abs=1e-5)
def test_compute_advantages_singleton_group_gets_zero_advantage():
"""A group of size 1 has reward == mean, so its advantage is 0 (filterable downstream)."""
rollouts = [
_make_rollout(0.5, example_id=0),
_make_rollout(0.8, example_id=0),
_make_rollout(0.3, example_id=1), # singleton group
]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
# Group 0: mean=0.65, advantages=[-0.15, 0.15]
assert advantages[:2] == pytest.approx([-0.15, 0.15], abs=1e-5)
# Group 1 (singleton): advantage=0
assert advantages[2] == pytest.approx(0.0, abs=1e-5)
def test_compute_advantages_disambiguates_example_id_across_envs():
"""example_id=0 in env A and example_id=0 in env B must not be grouped together."""
rollouts = [
_make_rollout(1.0, env_name="env_a", example_id=0),
_make_rollout(0.0, env_name="env_a", example_id=0),
_make_rollout(100.0, env_name="env_b", example_id=0),
_make_rollout(200.0, env_name="env_b", example_id=0),
]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
# env_a group: mean=0.5, advantages=[0.5, -0.5]
assert advantages[:2] == pytest.approx([0.5, -0.5], abs=1e-5)
# env_b group: mean=150, advantages=[-50, 50]
assert advantages[2:] == pytest.approx([-50.0, 50.0], abs=1e-5)
def test_setup_advantage_fn_with_custom_config():
config = CustomAdvantageConfig(
import_path="tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
@@ -353,17 +354,13 @@ def test_setup_advantage_fn_with_custom_config():
)
advantage_fn = setup_advantage_fn(config)
inputs = _make_inputs(
rewards=[[1.0, 0.5, 0.8]],
completion_lengths=[[10, 12, 8]],
)
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
result = advantage_fn(inputs)
assert isinstance(result, AdvantageOutputs)
assert torch.allclose(result.advantages, torch.tensor([[2.0, 1.0, 1.6]]))
assert result.advantages == pytest.approx([2.0, 1.0, 1.6], abs=1e-6)
def _dummy_custom_advantage(inputs: AdvantageInputs, scale: float = 1.0) -> AdvantageOutputs:
"""A simple custom advantage for testing."""
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
return AdvantageOutputs(advantages=rewards * scale)
return AdvantageOutputs(advantages=[r["reward"] * scale for r in inputs.rollouts])
+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]