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
1d9ca92551 fix(rl): normalize loss by global token count across dp_cp (#2562)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Each DP rank was dividing its summed token loss by its own local
loss_scale, then FSDP averaged the resulting gradients. Because ranks
process different sequence lengths, that mean is not the true per-token
mean over the global batch — ranks with fewer loss tokens get implicitly
upweighted.

Mirror the SFT trainer fix (src/prime_rl/trainer/sft/train.py:416-427):
all-reduce the local token count across dp_cp, divide by that global
denominator on every rank, and multiply grads by fsdp_gradient_divide_factor
after the microbatch loop so FSDP's per-rank averaging is undone and the
final gradient is the per-token mean over the global batch.

Closes #2358. Adapted from #2359, which first diagnosed the bias and
proposed the all-reduce-then-rescale approach.

Co-authored-by: irfanjamil <irfanjamil9@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 20:12:08 -07:00
ea2f390045 feat: renderer-only multimodal path — rip MITO branch, pack pixel_values from renderer (#2473)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: drop use_renderer=True VLM skip; pack pixel_values from renderer

interleave_rollout now consumes renderer-emitted multi_modal_data on each
trajectory step (when present), packs the per-image pixel_values and
image_grid_thw onto the TrainingSample, and computes mm_token_type_ids —
no VLMImageCache lookup required when the rollout went through a
multimodal renderer. VLMImageCache stays as the fallback for
MITO/chat-completions rollouts.

build_trajectory_step (renderers package) was updated separately to
surface mm_data on its output, so the pretokenize-fallback path also
carries images through correctly.

Other changes:
- orchestrator config: removed validate_renderer_vs_vlm validator that
  previously rejected use_renderer=True for VLMs (it's now supported).
- e2e test: a real Qwen3VLRenderer + RendererClient -> /inference/v1/generate
  mock POST, plus a roundtrip through vllm's GenerateRequest pydantic
  model and decode_mm_kwargs_item. Strongest end-to-end check we can
  run without a GPU.
- 20-step A/B configs for color-codeword (feat-renderer vs main-mito),
  both logging to W&B project 'multimodal-renderer'.

126 orchestrator unit tests pass (+2 new for renderer-mm packing).

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

* refactor(orchestrator): rip MITO multimodal path, renderer-only for VLMs

Delete the MITO chat-completions multimodal branch from the orchestrator
and the ~370 lines of image-cache/preprocess machinery in trajectories.py
that supported it. VLM training now goes through the renderer path
exclusively — the renderer owns the processor, ships byte-identical
pixel_values to both vLLM (via /inference/v1/generate features) and the
trainer (via mm_kwargs).

Renderer-shipped mm_token_type_ids: the orchestrator reads the renderer's
`mm_token_type_id_map` property (1=image_pad, 2=video_pad) and stamps a
per-token list onto each TrainingSample. Trainer's `_get_qwen3_vl_mm_token_type_ids`
auto-path remains as a fallback but the renderer is now the source of truth.

forward() now takes a generic `mm_kwargs: dict` (e.g. {pixel_values,
image_grid_thw}) instead of the Qwen3-VL-specific (pixel_values, image_grid_thw)
keyword pair, so adding new VLM families (Gemma3, LLaVA, etc.) doesn't
require touching forward.

Config validator: orchestrator.use_renderer must be true when model.vlm is
set — fail at config-load instead of producing cryptic runtime errors.

Test cleanup: drop 25 tests for removed helpers (VLMImageCache, _extract_images,
etc.); update the one remaining renderer-mm trajectory test to pass
`mm_token_type_ids_mapping` directly.

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

* fix: align with renderer-multimodal PR surface (configs + deps + tests)

CI was failing for three reasons after the cherry-pick of the renderer
multimodal commits onto current origin/main. Three fixes:

1. Multimodal configs missing the renderer flag pair. The orchestrator
   config validator (added in the same PR) requires
   ``use_renderer = true`` when ``model.vlm`` is set, AND it's mutually
   exclusive with ``use_token_client`` (default ``true``). Three configs
   (``rl_color_codeword_test.toml``, ``rl_color_codeword.toml``,
   ``ci/nightly/multimodal_color_codeword.toml``) needed both flags set
   explicitly in ``[orchestrator]``. Delete
   ``rl_color_codeword_main_mito.toml`` — that was the A/B reference for
   the legacy MITO path, which this PR rips out. With MITO gone the
   config is no longer runnable; the ``rl_color_codeword_feat_renderer``
   counterpart already covers the new renderer-driven path.

2. ``test_model_forward.py`` was still calling ``forward(...,
   pixel_values=..., image_grid_thw=...)``. ``forward()`` now takes a
   generic ``mm_kwargs: dict`` (so adding new VLM families doesn't
   require touching the trainer signature) — update both tests to pass
   ``mm_kwargs={"pixel_values": ..., "image_grid_thw": ...}`` instead.

3. ``renderers`` / ``verifiers`` deps stale. The orchestrator imports
   ``MultiModalData`` from ``renderers.base`` (introduced in the
   companion renderers PR) and threads ``multi_modal_data`` end-to-end
   via the verifiers ``RendererClient`` changes. Pin both to their
   feature branches until the upstream PRs merge and PyPI / git
   rev-pins are bumped:

     - renderers @ feat/multimodal-vlm
     - verifiers @ feat/renderer-multimodal-passthrough

   Drops the ``renderers==0.1.6`` PyPI pin (the new symbols are post-0.1.6).

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

* chore: bump renderers + verifiers to latest feature-branch commits

Picks up:
- renderers c3feaa5: RendererPool implements Renderer protocol structurally
  (callers can drop pool unwrap + isinstance branching), size=1 fast path,
  is_multimodal helper with per-type cache.
- verifiers 64f2555a: bugbot pass — multimodal dispatch fix (was broken
  for pooled renderers), tighter is_json_serializable, response-tokens
  mm_data strip on intermediate steps.

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

* chore: bump renderers + verifiers to pick up isinstance dispatch fix

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

* chore: drop renderers git source, pin to released 0.1.7

renderers v0.1.7 is now on PyPI with the multimodal feature set this
branch consumes (RenderedTokens, MultiModalData, MultimodalRenderer
protocol, mm_token_type_id_map, RendererPool delegation).

verifiers still pinned to feat/renderer-multimodal-passthrough until
that companion PR merges.

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

* chore: repin verifiers to main + bump renderers to 0.1.8.dev2

The multimodal renderer-passthrough work has merged on verifiers
(verifiers#1346 → c7731bbb, on main since 2026-05-12), so we no longer
need the feature-branch pin. Switching to a `rev =` pin on main
(f633365f) — consistent with how every other git source in this file
is pinned — and bumping renderers to 0.1.8.dev2 to match what verifiers
main now requires.

Pin updates:
- verifiers: branch `feat/renderer-multimodal-passthrough`
  (0.1.14 @ 397b8aa5)  ->  rev `f633365f` (0.1.15.dev7)
- renderers: `>=0.1.7` -> `>=0.1.8.dev2`
- prime-sandboxes: 0.2.22 -> 0.2.26 (transitive from verifiers main)
- fastokens added (transitive from renderers 0.1.8.dev1+; renderers
  routes `load_tokenizer` through fastokens by default)

What's in the verifiers delta (397b8aa5..f633365f) that touches our
surface:
- `RendererClient.from_native_response` migrated to renderers'
  `ParsedToolCall` dataclass shape and filters non-OK parse attempts
  (verifiers#1366 / renderers#22). Internal — the Response we consume
  is unchanged.
- Routed-experts payloads now flow as opaque bytes through the chat
  completions clients (verifiers PRs around the `routed_experts`
  changes). Prime-rl consumes the surface that emits these; no caller
  change needed.

Test plan:
- [x] `uv run pytest tests/unit/orchestrator` — 101 passed against the
  new pins, including `test_qwen3_vl_e2e` which exercises the renderer
  -> RendererClient -> /inference/v1/generate roundtrip path.

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

* chore: drop renderers version pin, defer to verifiers' transitive constraint

We import directly from `renderers` (orchestrator + tests), so the dep
needs to be declared — but pinning a floor here is just second-guessing
verifiers, which already requires `renderers>=0.1.8.dev2`. Let verifiers
be the source of truth for the version.

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

* fix(trainer): drop mm_token_type_ids auto-compute, trust renderer

The auto-compute path (`_get_qwen3_vl_mm_token_type_ids`) was preferred
over the renderer-shipped `mm_token_type_ids` in `forward()`. For
Qwen3-VL the auto function never returns `None` (allocates
`torch.zeros_like(input_ids)` then masked_fills), so the explicit
orchestrator-shipped list was silently discarded — contradicting both
the "renderer is source of truth" design and the trajectories.py
comment noting the explicit list produces ~30x lower mismatch KL.

The new `vlm_requires_renderer` validator (this PR) mandates the
renderer for every VLM config, so the auto path is no longer reachable
as a real fallback. Deleting it. The renderer's `mm_token_type_id_map`
is now the sole source of truth, exactly as advertised.

Also adding the CHANGELOG entry the validator missed — removing the
`[model.vlm]` + `use_renderer = false` combo is a breaking config
change per CHANGELOG.md's stated policy.

The remaining `if "image_grid_thw" not in mm_kwargs` branch is *not*
renderer-replaceable: it skips `position_ids` for MRoPE families
because HF's Qwen-VL `forward()` internally recomputes 3D positions
from `image_grid_thw` and breaks if given the trainer's pre-computed
1D `position_ids`. Duck-typed against the kwargs schema so any future
MRoPE family that ships `image_grid_thw` is handled without a
`model_type` enumeration.

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

* fix(orchestrator): union per-step delta mm_data across sample's step range

verifiers ≥ c7731bbb (PR #1346 merge) replaced ``_strip_intermediate_mm_data``
with ``_delta_intermediate_mm_data`` (commit 9aafa659): each trajectory
step now carries only the items whose ``mm_hash`` was NOT in the prior
step's cumulative set, with multiset-aware semantics. The intended
contract is that per-window assemblers union deltas to recover the
per-sample cumulative.

Prime-rl's ``interleave_rollout`` was that assembler but still read
``prepared_steps[last_step_idx].get("multi_modal_data")`` alone,
assuming the last step held the cumulative set. With the new delta
encoding, the last step often holds **0 items** (everything was a
duplicate of step 0's cumulative set) — so the trainer was given
pixel_values for only the first turn's images. For ``color-codeword``
with ``max_turns=2, images_per_turn=2`` (4 images total), the trainer
saw a subset → wildly wrong attention → mismatch KL jumped from
~0.04 to ~7 (>100× regression). On Qwen3-VL the model raised
``ValueError: Image features and image tokens do not match`` when the
delta drop left the trainer with fewer feature blocks than placeholder
runs.

Fix: track ``start_step_idx`` per active sample and concatenate
``mm_items`` / ``mm_hashes`` across ``[start_step_idx, last_step_idx]``
in step order. No dedup here — verifiers' delta already handled
cross-step dedup with multiset semantics (legitimate duplicate
placeholders, where the same image appears in two turns' separate
placeholder runs, are preserved).

Test plan:
- ``uv run pytest tests/unit/orchestrator/test_trajectories.py`` — 20 passed
- ``uv run pytest tests/unit/orchestrator tests/unit/train`` — 216 passed, 6 skipped, 1 xfailed
- ``uv run rl @ configs/multimodal/rl_color_codeword_feat_renderer.toml``
  on 2× RTX PRO 6000: Step 0 KL **0.020** (was 7.0), Step 1 **0.090**,
  Step 2 **0.253** — all within the baseline range published in #2473
  (max 0.487 across 20 steps).

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

* fix(orchestrator): track explicit step indices per sample for mm union

interleave_rollout used (start_step_idx, last_step_idx) to bound the
mm_data union per sample. When agents interleave (e.g. agent1 at steps
0,1,3 and agent2 at step 2), the range [0,3] over-collects step 2 and
agent2's delta mm_items leak into agent1's sample.mm_kwargs — placeholder
count vs. patch count mismatches at the VLM forward.

Replace the (start, last) pair with the explicit list of prepared_steps
positions merged into the sample. _union_step_mm_data iterates the list
directly, so non-owned steps are skipped by construction.

Non-interleaved trajectories produce step_indices = [0..N], iterating
identically to the old range — bit-for-bit unchanged for the common path.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: eligotts <78387377+eligotts@users.noreply.github.com>
2026-05-20 19:00:55 -07:00
44dcc5ab40 fix(slurm): release allocation when any component crashes (#2577)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Previously a trainer/inference/orchestrator/router crash left surviving
components running, holding the SLURM allocation until walltime. The
sbatch script propagates the failure now:

- srun uses --kill-on-bad-exit=1 so a non-zero exit on any task kills
  tasks on the other nodes.
- All per-node components run in the background; `wait -n` turns the
  first exit (success or crash) into the task exit code, surfacing
  background crashes (router, orchestrator) that the previous foreground
  layout silently ignored.
- `set -o pipefail` inside the task and `set -e` in the outer sbatch
  keep failures from being swallowed by `| tee` or by setup commands.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:04:39 -07:00
271801bd4d fix(wandb): handle shared mode breakage from wandb v0.26.1 (#2578)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(wandb): handle shared mode breakage from wandb v0.26.1

wandb v0.26.1 (PR #11759) changed `inform_init` to propagate
duplicate stream ID errors as `ServerResponseError` instead of
silently swallowing them. This breaks shared mode where multiple
processes intentionally call `wandb.init(id=same_run_id)`.

- Add `resume="allow"` when a run ID is provided so wandb attaches
  to the existing run instead of rejecting it
- Catch `ServerResponseError` (alongside `CommError`) for non-primary
  shared-mode processes to handle transient init races

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

* fix(wandb): teardown wandb-core between init retries

A failed wandb.init leaves the run_id registered in the local
wandb-core StreamMux. The next retry hits the same wandb-core,
finds the stream still there, and raises ServerResponseError
("run ID ... is in use") regardless of resume="allow" — the check
fires before reaching the server.

Tearing down the service before sleeping clears the StreamMux so
the retry starts fresh. Also catch ServerResponseError on the
primary side, since the race is symmetric: either side can win
the upsertBucket and the other can hit this path.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 17:00:04 -07:00
851233e5de feat(release): automated tagging + release flow (#2573)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(release): add tag-and-release workflow, backfill release notes, expand release skill

Port the verifiers tag-and-release pattern: on version bump in pyproject.toml,
auto-tag main and create the GitHub Release using assets/release/RELEASE_v{tag}.md
as the body. Skip the PyPI publish steps since prime-rl is not on PyPI.

Backfill release-note files for v0.1 through v0.5.0 by copying each existing
GitHub Release body so the workflow has historical artifacts to compare against.

Expand skills/release/SKILL.md so an agent can prepare the full release PR
(version bump, release notes file, draft PR) — merging the PR is then enough
to publish the release.

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

* chore(release): rename v0.1/v0.2 notes to v0.1.0/v0.2.0 for consistency

Aligns all backfilled release note filenames on a MAJOR.MINOR.PATCH suffix.
The historical GitHub tags (v0.1, v0.2) keep their original names; this only
touches the on-disk filenames.

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

* chore(ci): rename release.yaml to docker-push.yaml; exclude dev tags from tag-and-release

The old release.yaml only builds and pushes the Docker image; the new
tag-and-release.yaml is now the canonical "release" workflow. Renaming
removes the ambiguity.

Add a trigger filter to tag-and-release so '*dev*' tags do not flow through
the release path. devx_tag.yaml creates dev tags via GITHUB_TOKEN, which
already does not retrigger workflows; this exclusion is defensive for any
manual dev-tag pushes. Skill note updated to clarify the two workflows
coexist.

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

* fix(ci): check release notes before tagging, and retry on tag-without-release

Two bugbot fixes in tag-and-release.yaml:

1. Move the assets/release/RELEASE_*.md presence check into auto-tag-on-main,
   before the tag is created and pushed. Missing notes used to fail in
   release-from-auto-tag, but only after the tag was already on the remote,
   blocking a clean retry.

2. If the target tag already exists (locally or on origin) but no GitHub
   Release exists for it yet, still emit created=true so release-from-auto-tag
   runs against the existing tag. This unblocks recovery from a partial
   failure (e.g. the release step crashed after the tag push) without
   requiring manual cleanup or workflow_dispatch.

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

* refactor(release): drop in-repo release notes; promote pre-existing draft release on tag

Pivot the release flow:
- Release notes live as a draft GitHub Release created via `gh release create
  --draft` (no longer tracked in the repo). Removed assets/release/*.
- The release skill instructs an agent to (1) draft the release on GitHub
  with the notes inline and (2) open a draft PR that only bumps `version` in
  pyproject.toml.
- On merge, tag-and-release verifies the draft release exists for the new
  tag, pushes the tag, then promotes the draft via `gh release edit
  --draft=false --latest`. Recovery path: if the tag exists with a draft,
  the next main push (or workflow_dispatch) re-promotes it.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 14:43:06 -07:00
101 changed files with 2434 additions and 2532 deletions
@@ -1,4 +1,4 @@
name: Release
name: Docker Push
on:
push:
+212
View File
@@ -0,0 +1,212 @@
name: Tag and Release
on:
push:
branches:
- main
tags:
# Stable release tags only. `.dev` tags are created by `devx_tag.yaml`
# via GITHUB_TOKEN (which does not retrigger workflows), so they would
# not arrive here anyway — this exclusion is defensive for manual pushes.
- 'v*'
- '!v*dev*'
workflow_dispatch:
inputs:
tag:
description: 'Existing tag to release (e.g. v0.6.0)'
required: true
type: string
jobs:
auto-tag-on-main:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
created: ${{ steps.tag.outputs.created }}
tag: ${{ steps.tag.outputs.tag }}
version: ${{ steps.tag.outputs.version }}
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect version bump and create tag
id: tag
env:
BEFORE_SHA: ${{ github.event.before }}
GH_TOKEN: ${{ github.token }}
run: |
echo "created=false" >> "$GITHUB_OUTPUT"
if [ "$BEFORE_SHA" = "0000000000000000000000000000000000000000" ]; then
echo "No valid base commit available; skipping auto-tag."
exit 0
fi
OLD_VERSION=$(git show "$BEFORE_SHA:pyproject.toml" | sed -n 's/^version = "\([^"]*\)"$/\1/p' | head -n1)
if [ -z "$OLD_VERSION" ]; then
echo "Could not find version in previous pyproject.toml" >&2
exit 1
fi
NEW_VERSION=$(python - <<'PY'
from pathlib import Path
import re
import sys
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', Path("pyproject.toml").read_text())
if not match:
sys.exit("Could not find version in current pyproject.toml")
print(match.group(1))
PY
)
if [ "$OLD_VERSION" = "$NEW_VERSION" ]; then
echo "No version change detected in pyproject.toml; skipping auto-tag."
exit 0
fi
TAG="v${NEW_VERSION}"
# A draft GitHub Release must already exist for this tag before we
# bump the version on main. The release skill creates it via
# `gh release create --draft` ahead of the PR merge.
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
echo "No GitHub Release found for $TAG." >&2
echo "Create a draft release first: gh release create --draft $TAG --title $TAG --notes-file <notes>.md" >&2
exit 1
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; skipping auto-tag."
exit 0
fi
TAG_EXISTS_LOCAL=false
TAG_EXISTS_REMOTE=false
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
TAG_EXISTS_LOCAL=true
fi
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
TAG_EXISTS_REMOTE=true
fi
if [ "$TAG_EXISTS_LOCAL" = "true" ] || [ "$TAG_EXISTS_REMOTE" = "true" ]; then
# Tag exists but draft hasn't been published — proceed to publish
# (covers retries after the release-from-auto-tag step failed).
echo "Tag ${TAG} already exists with a draft release; will publish."
echo "created=true" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "$TAG" -m "Release $TAG"
git push origin "$TAG"
echo "created=true" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
release-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Publish draft release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
run: |
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
tag-and-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: refs/tags/${{ inputs.tag }}
- name: Checkout tagged release (push)
if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Resolve release version
id: release
env:
EVENT_NAME: ${{ github.event_name }}
PUSHED_REF: ${{ github.ref_name }}
INPUT_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
run: |
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
TAG="$INPUT_TAG"
else
TAG="$PUSHED_REF"
fi
if [ -z "$TAG" ]; then
echo "Unable to determine release tag" >&2
exit 1
fi
case "$TAG" in
v*)
;;
*)
echo "Release tags must be prefixed with 'v' (received '$TAG')" >&2
exit 1
;;
esac
VERSION="${TAG#v}"
FILE_VERSION=$(python - <<'PY'
from pathlib import Path
import re
import sys
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', Path("pyproject.toml").read_text())
if not match:
sys.exit("Could not find version in pyproject.toml")
print(match.group(1))
PY
)
if [ "$FILE_VERSION" != "$VERSION" ]; then
echo "Version mismatch: tag requests '$VERSION' but pyproject.toml defines '$FILE_VERSION'" >&2
exit 1
fi
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Publish draft release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
run: |
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
echo "No GitHub Release found for $TAG." >&2
echo "Create a draft release first: gh release create --draft $TAG --title $TAG --notes-file <notes>.md" >&2
exit 1
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; nothing to do."
exit 0
fi
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
+3
View File
@@ -2,6 +2,9 @@
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.
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
+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,8 +15,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
use_renderer = false
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 -3
View File
@@ -10,9 +10,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
use_renderer = false
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
@@ -0,0 +1,99 @@
# 20-step Qwen3-VL-4B RL run on color-codeword using the renderer multimodal path.
#
# Pair with rl_color_codeword_main_mito.toml for an A/B comparison: same env,
# same hyperparameters, same step count — only difference is the inference
# client. The feat-branch run uses the new RendererClient + Qwen3VLRenderer
# (renderers package with multimodal support); the main-branch baseline uses
# the existing TITO chat-completions path through the inference server.
#
# Compare in W&B project ``multimodal-renderer``:
# - ``kl/sampler_vs_trainer`` should be ~0 on this branch (the renderer
# produces byte-identical tokens to what the trainer re-tokenizes) and
# can spike on main when BPE drifts mid-rollout.
# - ``reward`` and ``loss`` should track within noise — same model, same
# env, same hyperparameters.
# - ``bridge_break_rate`` is renderer-only; surfaces multi-turn extension
# failures.
max_steps = 20
seq_len = 4096
output_dir = "outputs/rl_color_codeword_feat_renderer"
clean_output_dir = true
# Pure on-policy: inference can't run ahead of training, so every rollout
# is generated from the latest policy weights. Removes async/off-policy
# drift as a confound for the sampler-vs-trainer KL.
max_async_level = 0
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
gpus_per_node = 2
[orchestrator]
batch_size = 16
group_size = 8
use_renderer = true
# Track zero-advantage groups but don't drop them — we're validating the
# multimodal renderer path on 20 steps, not optimizing training efficiency.
# Step 0 on Qwen3-VL-4B vs color-codeword is likely uniform (all-correct or
# all-wrong) so enforce=True would crash before any training happens.
[[orchestrator.filters]]
type = "gibberish"
[[orchestrator.filters]]
type = "repetition"
[[orchestrator.filters]]
type = "zero_advantage"
enforce = false
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 2, max_turns = 2, num_examples = 100, seed = 42 }
[orchestrator.renderer]
name = "auto"
# 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.
pool_size = 4
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.model]
# Workaround for vLLM 0.20.1 Qwen3-VL deepstack buffer bug: when num_scheduled_tokens
# (188) gets padded up to the next cudagraph_capture_size (192), the model's
# _set_deepstack_input_embeds sizes the buffer to 188 but forward() runs with 192,
# triggering "Requested more deepstack tokens than available in buffer". Eager mode
# skips the padding so num_input_tokens == num_scheduled_tokens.
enforce_eager = true
[inference.parallel]
dp = 1
tp = 1
[wandb]
project = "multimodal-renderer"
name = "feat-renderer-20step-r8-i2-t2-onpolicy"
tags = ["qwen3vl-4b", "color-codeword", "renderer", "feat-branch", "mm-kwargs-generic", "on-policy"]
@@ -11,8 +11,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 16
rollouts_per_example = 2
use_renderer = false
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
+4 -6
View File
@@ -47,13 +47,11 @@ To add permanent support for a new model family, add an entry to `VLM_REGISTRY`
## How Multi-Turn VLM RL Training Works
VLM training uses the same `interleave_rollout` path as text-only models. Multi-turn trajectory steps are merged into a single training sample wherever the extension property holds.
VLM rollouts go through the renderer-backed TITO client (`orchestrator.use_renderer = true`, the default and required for VLMs). The renderer owns the HuggingFace processor per-slot and emits multimodal tensors alongside tokens.
Images are handled via a `VLMImageCache` built once per batch:
1. **Extract**: Base64 images are decoded from trajectory step prompts into PIL images.
2. **Preprocess**: Images are processed through the HuggingFace image processor, producing `pixel_values` and `image_grid_thw`.
3. **Attach**: Each training sample receives the cumulative `pixel_values` up to its last merged step.
1. **Render**: For each trajectory step, the renderer tokenizes messages and emits per-image multimodal tensors (e.g. `pixel_values`, `image_grid_thw` for Qwen3-VL) as `multi_modal_data`.
2. **Pack**: `interleave_rollout` concatenates the per-image tensors emitted across a sample's merged step range into a single `mm_kwargs` dict on the `TrainingSample`. Per-token `mm_token_type_ids` (0=text, 1=image, 2=video) come from `renderer.mm_token_type_id_map`.
3. **Forward**: The trainer `**`-unpacks `mm_kwargs` into the model's `forward` signature, so any VLM whose HF processor and forward agree on kwarg names works without touching the transport.
Each multimodal sample becomes its own micro-batch during training (no packing) since image tensor sizes vary.
+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."""
@@ -654,7 +654,7 @@ class OrchestratorConfig(BaseConfig):
"""BetterStack heartbeat configuration for monitoring training progress."""
use_renderer: bool = True
"""Use the renderer-backed TITO client (client-side tokenization via the ``renderers`` package, served by ``/v1/generate``). When True, the ``[orchestrator.renderer]`` block applies. This is the default for text-only rollouts. False falls back to MITO (``openai_chat_completions``); VLMs and external teacher rollouts require MITO."""
"""Use the renderer-backed TITO client (client-side tokenization via the ``renderers`` package, served by ``/v1/generate``). When True, the ``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) applies. Default for both text-only and VLM rollouts; VLMs require it. False falls back to MITO (``openai_chat_completions``)."""
env_install_prerelease: bool = False
"""Allow pre-release versions when installing environments (e.g. ``verifiers>=0.1.12.dev5``). Passes ``--prerelease`` to ``prime env install``."""
@@ -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")
@@ -788,20 +800,6 @@ class OrchestratorConfig(BaseConfig):
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
"""The renderer client takes plain message dicts and tokenizes
them client-side. VLMs need server-side image preprocessing and
chat templating, so they must use MITO — fail
loudly when both are set."""
if self.use_renderer and self.student.model.vlm is not None:
raise ValueError(
"orchestrator.use_renderer is not supported for VLMs. Use MITO "
"(``use_renderer=false``) so image preprocessing and chat templating stay on the "
"inference server."
)
return self
@model_validator(mode="after")
def validate_renderer_args(self):
"""``[orchestrator.renderer]`` knobs are only meaningful when
@@ -833,6 +831,21 @@ class OrchestratorConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def vlm_requires_renderer(self):
"""VLMs (``[model.vlm]`` block set) must go through the renderer.
The renderer owns the processor per-slot, produces byte-identical
tokens, and ships generic ``mm_kwargs`` keyed by whatever the
model's forward signature expects.
"""
if self.student.model.vlm is not None and not self.use_renderer:
raise ValueError(
"orchestrator.use_renderer must be true when model.vlm is set. "
"VLMs must go through a renderer (e.g. Qwen3VLRenderer) that owns the processor."
)
return self
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
"""Reject the silent DefaultRenderer fallback at config time.
@@ -894,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:
@@ -908,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`
+62 -7
View File
@@ -5,10 +5,65 @@ description: How to prepare and publish GitHub releases for prime-rl. Use when d
# Releases
1. **Match prior style** — `gh release list --limit 1` then `gh release view <tag>` to mirror tone and structure.
2. **Gather commits** — `git fetch origin main` and `git log <last-tag>..origin/main --oneline --no-merges`. Re-fetch right before publishing in case PRs landed during drafting.
3. **Structure** — numbered highlight sections (`# 1.`, `# 2.`, ...) for impactful user-facing features, then `# Breaking Changes`, `# Bug Fixes`, `# Misc`. Use `##` subsections inside a highlight when it bundles multiple items.
4. **Verify TOML field names** — when referencing config in notes, check the actual code; don't guess.
5. **Links** — clickable for docs (`[docs/foo.md](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/docs/foo.md)`) and PRs (`[#1234](https://github.com/PrimeIntellect-ai/prime-rl/pull/1234)`).
6. **Contributors** — list by commit count, using GitHub `@username` from the API (git author names can be inconsistent).
7. **Always draft first** — `gh release create ... --draft`, iterate, then publish.
Releases are driven by [`.github/workflows/tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml). The flow:
1. You create a **draft GitHub Release** with the notes inline (`gh release create --draft`).
2. You open a **draft PR** that bumps `version` in `pyproject.toml`.
3. Maintainer merges. The workflow tags the commit and promotes the draft.
Release notes live on the GitHub Release, not in the repo. Prime-rl is **not** on PyPI. `.dev` tags are handled separately by `devx_tag.yaml`; `tag-and-release.yaml` ignores them.
## 1. Decide the version
```bash
git fetch origin --tags
grep '^version' pyproject.toml
gh release list --repo PrimeIntellect-ai/prime-rl --limit 5
```
SemVer (`MAJOR.MINOR.PATCH`). Confirm with the user before continuing.
## 2. Draft the notes
Match the prior release's structure: numbered highlights (`# 1.`, ...), then `# Breaking Changes`, `# Bug Fixes`, `# Misc`, `# Contributors`. Use `##` subsections inside a highlight when it bundles multiple items.
```bash
PREV=$(gh release list --limit 1 --json tagName --jq '.[0].tagName')
gh release view "$PREV" --json body --jq .body # style reference
git log "$PREV"..origin/main --oneline --no-merges # commits since
gh pr list --base main --state merged --search \
"merged:>=$(gh release view "$PREV" --json publishedAt --jq .publishedAt)" \
--limit 500 --json number,title,author # for PR links + contributors
```
Tips:
- PR refs: `[#1234](https://github.com/PrimeIntellect-ai/prime-rl/pull/1234)`.
- Contributors: order by commit count, use the GH `@username` from the API (not git author names).
- Verify any TOML field names against the actual config classes.
## 3. Create the draft release
```bash
NEW=v0.6.0
gh release create --draft "$NEW" --title "$NEW" --target main --notes-file /tmp/release-notes-$NEW.md
gh release view "$NEW" --json isDraft,tagName --jq '{tagName, isDraft}' # expect isDraft: true
```
Iterate with `gh release edit "$NEW" --notes-file /tmp/release-notes-$NEW.md`.
## 4. Open the version-bump PR
```bash
git switch -c chore/release-$NEW
# bump `version = "..."` in pyproject.toml
git add pyproject.toml
git commit -m "chore: release $NEW"
git push -u origin "chore/release-$NEW"
gh pr create --draft --title "chore: release $NEW" --body "Bumps version to ${NEW#v}. Draft release: https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/$NEW"
```
Stop. Do not tag, push tags, or flip the draft to published — the workflow does that on merge.
## Recovery
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it.
+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,
}
+47 -66
View File
@@ -13,10 +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 (
build_vlm_image_cache,
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
@@ -34,7 +33,6 @@ monkey_patch_chat_completion_logprobs()
import pandas as pd
import verifiers as vf
from renderers.base import create_renderer
from transformers import AutoProcessor
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.buffer import Buffer
@@ -118,17 +116,9 @@ async def orchestrate(config: OrchestratorConfig):
for env_id in env_ids_to_install:
install_env(env_id, prerelease=config.env_install_prerelease)
# Load tokenizer and processor (processor only for VLM models)
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
processor = None
if config.student.model.is_vlm:
logger.info(f"Loading VLM processor for {config.student.model.name}")
processor = AutoProcessor.from_pretrained(
config.student.model.name, trust_remote_code=config.student.model.trust_remote_code, use_fast=True
)
# Set up student inference pool (required for all training modes).
logger.info(
f"Initializing student inference pool (base_url={', '.join(config.student.client.base_url)}, "
@@ -140,6 +130,18 @@ async def orchestrate(config: OrchestratorConfig):
logger=logger,
)
# Token-id → modality marker (1 = image patch, 2 = video patch) used
# to build ``mm_token_type_ids`` per sample. The renderer is the
# single source of truth — it already knows its own special-token
# IDs (``<|image_pad|>`` etc.) from the tokenizer it owns, so the
# orchestrator never needs to load a separate ``AutoProcessor``.
# Text-only renderers expose an empty map (or no attribute).
mm_token_type_ids_mapping: dict[int, int] | None = (
getattr(renderer, "mm_token_type_id_map", None) if renderer is not None else None
)
if mm_token_type_ids_mapping == {}:
mm_token_type_ids_mapping = None
# Set up teacher inference pool (configured for opd or sft). Always MITO for
# simplicity - this also keeps external OAI-compatible teachers (PI inference,
# OpenAI) working as drop-in endpoints.
@@ -426,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:
@@ -468,69 +470,47 @@ async def orchestrate(config: OrchestratorConfig):
save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
)
# VLM: offload base64 images to disk immediately to free memory
if config.student.model.is_vlm:
offload_start = time.perf_counter()
num_offloaded = offload_images_to_disk(train_rollouts, config.output_dir)
if num_offloaded:
logger.info(
f"VLM offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
)
# Offload base64 images to disk to free memory. No-op for text-only
# rollouts (no ``data:image`` URLs to find); cheap to call always.
offload_start = time.perf_counter()
num_offloaded = offload_images_to_disk(train_rollouts, config.output_dir)
if num_offloaded:
logger.info(
f"Offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
)
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
# Stage 1: pretokenize + (for VLM) build image cache concurrently.
# Pretokenize is a no-op when the renderer client already populated
# `tokens` on each trajectory step, but the fallback-tokenizer path
# and image-cache build are both CPU-heavy. Running them on threads
# and awaiting a single gather lets whichever finishes first free
# the event loop immediately and, with max_async_level >= 2, overlaps
# this whole stage with inference for the next batch.
async def _pretokenize_all() -> None:
# 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(
pretokenize_rollout_trajectory,
backfill_rollout_tokens,
rollout,
tokenizer,
processor=processor,
renderer=renderer,
)
for rollout in train_rollouts
)
)
if config.student.model.is_vlm:
mm_token_type_ids_mapping = {}
if hasattr(processor, "image_token_id") and processor.image_token_id is not None:
mm_token_type_ids_mapping[processor.image_token_id] = 1
if hasattr(processor, "video_token_id") and processor.video_token_id is not None:
mm_token_type_ids_mapping[processor.video_token_id] = 2
_, vlm_cache = await asyncio.gather(
_pretokenize_all(),
asyncio.to_thread(build_vlm_image_cache, train_rollouts, processor),
)
logger.info(
f"VLM timing: extract={vlm_cache.extract_time:.2f}s, preprocess={vlm_cache.preprocess_time:.2f}s "
f"({vlm_cache.num_unique_images} unique images from {vlm_cache.num_unique_examples} examples)"
)
else:
await _pretokenize_all()
vlm_cache = None
mm_token_type_ids_mapping = None
# Process rollouts in parallel
def process_rollout(rollout: vf.RolloutOutput, rollout_idx: int) -> list[TrainingSample] | None:
return interleave_rollout(
rollout,
vlm_cache=vlm_cache,
cache_key=rollout_idx,
mm_token_type_ids_mapping=mm_token_type_ids_mapping,
)
results = await asyncio.gather(
*(asyncio.to_thread(process_rollout, r, rollout_idx) for rollout_idx, r in enumerate(train_rollouts))
*(
asyncio.to_thread(interleave_rollout, r, mm_token_type_ids_mapping=mm_token_type_ids_mapping)
for r in train_rollouts
)
)
# Collect results and assign advantages. Metrics are computed over all
@@ -590,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
@@ -640,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
@@ -793,7 +773,7 @@ async def orchestrate(config: OrchestratorConfig):
is_first_step = False
# Free large per-step objects to prevent memory accumulation
del train_rollouts, train_examples, training_batch, vlm_cache
del train_rollouts, train_examples, training_batch
del results_df, metrics_df
gc.collect()
# Return free glibc heap pages to the OS. numpy/pandas allocate array data
@@ -889,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)))
@@ -903,10 +886,8 @@ async def setup_student_inference_pool(
Routing policy is driven by ``config.use_renderer``:
- ``use_renderer=True`` → renderer-backed TITO client (``/v1/generate``).
Default for text-only rollouts. Not allowed for VLMs (validated at
config time).
- ``use_renderer=False`` → MITO (``openai_chat_completions``). VLMs
land here too.
Default for both text-only and VLM rollouts; required for VLMs.
- ``use_renderer=False`` → MITO (``openai_chat_completions``).
Eval clients always use MITO. In sft mode ``use_renderer`` is forced off
by a config validator, so the student pool is plain MITO end-to-end.
+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()
+216 -495
View File
@@ -1,17 +1,15 @@
import base64
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path
from typing import Any
import numpy as np
import pybase64
import torch
import verifiers as vf
from PIL import Image
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,
@@ -22,28 +20,29 @@ from prime_rl.utils.chat_template import (
from prime_rl.utils.logger import get_logger
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
# primitives are immutable. pixel_values/image_grid_thw are not mutated after creation.
# 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:
@@ -67,62 +66,19 @@ def _render_messages(
messages: list[dict[str, Any]],
add_generation_prompt: bool = False,
tools: list[dict[str, Any]] | None = None,
processor=None,
) -> list[int]:
return render_messages(
tokenizer,
messages,
add_generation_prompt=add_generation_prompt,
tools=tools,
processor=processor,
)
def _prepare_messages_for_processor(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Convert messages to the format expected by the VLM processor.
- Converts image_url items to image items with loaded PIL Images
- Strips extra fields (e.g. image_url on text items) that confuse the processor
- Ensures all message content is in list format (processor requires this)
"""
prepared = []
for msg in messages:
content = msg.get("content")
if isinstance(content, str):
prepared.append({**msg, "content": [{"type": "text", "text": content}]})
continue
if not isinstance(content, list):
prepared.append(msg)
continue
new_content = []
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith(_FILE_URL_PREFIX):
img = _load_file_image(url)
elif url.startswith("data:image"):
b64_data = url.split(",", 1)[1]
img = Image.open(BytesIO(base64.b64decode(b64_data)))
else:
new_content.append(item)
continue
new_content.append({"type": "image", "image": img})
elif item.get("type") == "text":
new_content.append({"type": "text", "text": item.get("text", "")})
else:
new_content.append(item)
prepared.append({**msg, "content": new_content})
return prepared
def _tokenize_step_from_messages(
step: vf.TrajectoryStep,
tokenizer: PreTrainedTokenizer,
tools: list[dict[str, Any]] | None = None,
processor=None,
) -> dict[str, Any]:
prompt = _normalize_messages(step.get("prompt"), default_role="user")
completion = _normalize_messages(step.get("completion"), default_role="assistant")
@@ -135,10 +91,6 @@ def _tokenize_step_from_messages(
f"got roles: {[m.get('role') for m in completion]}"
)
if processor is not None:
prompt = _prepare_messages_for_processor(prompt)
completion = _prepare_messages_for_processor(completion)
all_messages = prompt + completion
prompt_has_assistant_completion = len(completion) > 0 and completion[0].get("role") == "assistant"
prompt_ids = _render_messages(
@@ -146,13 +98,11 @@ def _tokenize_step_from_messages(
prompt,
add_generation_prompt=prompt_has_assistant_completion,
tools=tools,
processor=processor,
)
full_ids = _render_messages(
tokenizer,
all_messages,
tools=tools,
processor=processor,
)
split_idx = _common_prefix_len(prompt_ids, full_ids)
@@ -214,10 +164,9 @@ 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,
processor=None,
renderer=None,
) -> bool:
"""Populate missing step tokens from prompt/completion messages.
@@ -225,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", []))
@@ -235,7 +187,7 @@ def pretokenize_rollout_trajectory(
if renderer is not None:
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
else:
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools, processor=processor)
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools)
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
logger.debug(
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
@@ -251,8 +203,6 @@ def pretokenize_rollout_trajectory(
def interleave_rollout(
output: vf.RolloutOutput,
vlm_cache: "VLMImageCache | None" = None,
cache_key: int | None = None,
mm_token_type_ids_mapping: dict[int, int] | None = None,
) -> list[TrainingSample] | None:
"""
@@ -270,13 +220,9 @@ def interleave_rollout(
Returns a list of samples - could be 1 (extension always held) or up to T
(extension never held).
For VLM models, pass vlm_cache to attach cumulative pixel_values per sample.
Each sample gets the images accumulated up to its last merged step.
Args:
output: vf.RolloutOutput containing trajectory data
vlm_cache: Pre-computed VLM image cache for multimodal training
cache_key: Cache key to use when retrieving images from the VLM cache
For VLM models, each renderer-produced trajectory step carries its
per-image processed tensors inline on ``multi_modal_data``; the last
merged step's sidecar covers every image in the sample.
"""
logger = get_logger()
@@ -296,13 +242,26 @@ 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
# for text-only rollouts.
"multi_modal_data": tokens.get("multi_modal_data"),
}
logger.warning(f"Missing rollout tokens for example {output['example_id']} step {step_idx}.")
@@ -315,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"]),
@@ -338,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]
@@ -359,28 +333,36 @@ 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, last_step_idx] per active sample
active_samples: list[tuple[list[int], TrainingSample, int]] = []
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
# is the explicit list of prepared_steps positions merged into this sample —
# non-contiguous when other agents' steps interleave.
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
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]
@@ -395,9 +377,13 @@ def interleave_rollout(
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample, _ = active_samples[matched_idx]
prefix_tokens, sample, step_indices = active_samples[matched_idx]
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
active_samples[matched_idx] = (tokens["prompt_ids"] + tokens["completion_ids"], sample, step_idx)
active_samples[matched_idx] = (
tokens["prompt_ids"] + tokens["completion_ids"],
sample,
step_indices + [step_idx],
)
else:
# No prefix matches - start a new sample
logger.debug(
@@ -405,31 +391,136 @@ 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]))
# Attach images once per sample using only the last merged step. Prompt
# tokens already contain fully expanded <|image_pad|> placeholders because
# VLMs go through MITO (chat completions), which runs apply_chat_template
# server-side; the orchestrator re-tokenizes via the same processor in the
# fallback path so features and tokens stay 1:1.
if vlm_cache is not None:
key = output["example_id"] if cache_key is None else cache_key
for _, sample, last_step_idx in active_samples:
pv, shape, grids = vlm_cache.get_for_step(key, last_step_idx)
sample.pixel_values = pv
sample.pixel_values_shape = shape
sample.image_grid_thw = grids
if mm_token_type_ids_mapping is not None:
sample.mm_token_type_ids = [
mm_token_type_ids_mapping.get(token_id, 0) for token_id in sample.prompt_ids + sample.completion_ids
]
# 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
# *delta* mm_data (each step contains only items not present in the
# prior step's cumulative set, with multiset-aware dedup), so
# reading the last step alone would miss every earlier-turn image.
# Concat in step order recovers the per-sample cumulative set;
# deduping again here would drop legitimate duplicate placeholders.
for _, sample, step_indices in active_samples:
renderer_mm = _union_step_mm_data(prepared_steps, step_indices)
if renderer_mm is not None:
mm_kwargs = _pack_mm_kwargs_from_renderer(renderer_mm)
if mm_kwargs is not None:
sample.mm_kwargs = mm_kwargs
# ``mm_token_type_ids``: 1 for image-placeholder tokens, 2
# for video, 0 otherwise. Renderer-supplied via
# ``mm_token_type_id_map`` (single source of truth).
if mm_token_type_ids_mapping is not None:
sample.mm_token_type_ids = [
mm_token_type_ids_mapping.get(token_id, 0)
for token_id in sample.prompt_ids + sample.completion_ids
]
return [sample for _, sample, _ in active_samples]
# =============================================================================
# VLM-specific functions
# =============================================================================
def _union_step_mm_data(
prepared_steps: list[dict[str, Any]],
step_indices: list[int],
) -> "dict[str, Any] | None":
"""Concatenate renderer-emitted mm_items across this sample's owned steps.
``step_indices`` lists exactly the ``prepared_steps`` positions merged into
the sample — explicit, not a range, so interleaved-agent trajectories skip
steps owned by other agents.
Verifiers ≥ c7731bbb ships per-step *delta* mm_data instead of
cumulative — see ``verifiers/utils/save_utils.py::_delta_intermediate_mm_data``.
The cross-step dedup is already done there with multiset semantics
(preserving multiplicity for an image that appears in multiple
placeholder runs in the token stream). We just concatenate in step
order to recover the per-sample cumulative; deduping again here
would drop legitimate duplicate placeholders.
"""
union_items: dict[str, list] = {}
union_hashes: dict[str, list] = {}
has_any = False
for i in step_indices:
mm = prepared_steps[i].get("multi_modal_data")
if mm is None:
continue
items = mm.mm_items if hasattr(mm, "mm_items") else (mm or {}).get("mm_items") or {}
hashes = mm.mm_hashes if hasattr(mm, "mm_hashes") else (mm or {}).get("mm_hashes") or {}
for modality, item_lst in items.items():
hash_lst = hashes.get(modality, []) or []
for j, item in enumerate(item_lst or []):
h = hash_lst[j] if j < len(hash_lst) else None
union_items.setdefault(modality, []).append(item)
union_hashes.setdefault(modality, []).append(h)
has_any = True
if not has_any:
return None
return {"mm_items": union_items, "mm_hashes": union_hashes}
def _pack_mm_kwargs_from_renderer(mm_data: Any) -> "dict[str, Any] | None":
"""Batch the renderer's per-image ``mm_items`` into model-agnostic
forward kwargs.
``mm_data`` may arrive as a ``MultiModalData`` instance (in-process
for tests) or as a plain dict (after msgpack round-trip from the
env-worker). Each item is a dict keyed by the names the model's
``forward`` expects (``pixel_values`` + ``image_grid_thw`` for
Qwen3-VL, just ``pixel_values`` for Gemma3-VL, etc.). We batch by
``torch.cat(..., dim=0)`` per key — generic because every HF VLM
processor emits a leading batch/patch dimension, and the renderer
always processes one image per call.
Returns a dict of ``EncodedTensor`` payloads keyed by kwarg name,
or ``None`` when no multimodal data is present.
"""
from verifiers.utils.serve_utils import decode_tensor_payload
from prime_rl.transport.types import EncodedTensor
mm_items = mm_data.mm_items if hasattr(mm_data, "mm_items") else (mm_data or {}).get("mm_items") or {}
# Flatten across modalities into one kwarg dict — the model's
# forward signature is the schema. ``mm_items`` is typically
# ``{"image": [...], "video": [...]}`` but each modality's keys
# don't collide for any HF VLM we ship today.
per_kwarg: dict[str, list] = {}
for _modality, items in mm_items.items():
for item in items or []:
for key, payload in item.items():
per_kwarg.setdefault(key, []).append(decode_tensor_payload(payload))
if not per_kwarg:
return None
out: dict[str, EncodedTensor] = {}
for key, tensors in per_kwarg.items():
cat = torch.cat(tensors, dim=0).contiguous()
arr = cat.detach().cpu().numpy()
out[key] = EncodedTensor(
dtype=str(arr.dtype),
shape=list(arr.shape),
data=arr.tobytes(),
)
return out
_FILE_URL_PREFIX = "file://"
@@ -475,373 +566,3 @@ def offload_images_to_disk(rollouts: list[vf.RolloutOutput], output_dir: Path) -
item["image_url"]["url"] = f"{_FILE_URL_PREFIX}{path}"
return len(written)
def _load_file_image(path_str: str) -> Image.Image:
"""Load an image from a file:// path."""
return Image.open(path_str.removeprefix(_FILE_URL_PREFIX))
def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str]]:
"""Extract (image, key) pairs from OpenAI-style chat messages.
Handles both base64 data URLs and file:// paths from disk offloading.
"""
images = []
if not messages or not isinstance(messages, list):
return images
for msg in messages:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith(_FILE_URL_PREFIX):
img = _load_file_image(url)
images.append((img, url))
elif url.startswith("data:image"):
b64_data = url.split(",", 1)[1]
img_bytes = base64.b64decode(b64_data)
img = Image.open(BytesIO(img_bytes))
images.append((img, b64_data))
return images
def _collect_image_keys_from_messages(messages: list) -> list[str]:
"""Extract image keys from OpenAI-style chat messages without decoding.
Handles both base64 data URLs and file:// paths from disk offloading.
"""
keys = []
if not messages or not isinstance(messages, list):
return keys
for msg in messages:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image"):
keys.append(url.split(",", 1)[1])
elif url.startswith(_FILE_URL_PREFIX):
keys.append(url)
return keys
def _decode_image(key: str) -> Image.Image:
"""Decode an image from a base64 string or load from a file:// path."""
if key.startswith(_FILE_URL_PREFIX):
return _load_file_image(key)
return Image.open(BytesIO(base64.b64decode(key)))
_PARALLEL_DECODE_THRESHOLD = 4
_IMAGE_STRIPPED_PLACEHOLDER = "[preprocessed image]"
def strip_base64_images(examples: list[tuple[int, vf.RolloutOutput]]) -> None:
"""Strip image data from rollout prompts to free memory.
Handles both base64 data URLs and file:// paths from disk offloading.
The images have been decoded and indexed; the original data is no longer needed.
"""
for _, output in examples:
for step in output.get("trajectory", []):
prompt = step.get("prompt")
if not prompt or not isinstance(prompt, list):
continue
for msg in prompt:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image") or url.startswith(_FILE_URL_PREFIX):
item["image_url"]["url"] = _IMAGE_STRIPPED_PLACEHOLDER
def _extract_images_from_examples(
examples: list[tuple[int, vf.RolloutOutput]],
) -> tuple[list[Image.Image], dict[int, list[list[int]]]]:
"""
Extract images from all trajectory steps of each example.
Two-pass approach: first collects unique base64 keys (fast, string-only),
then decodes unique images in parallel via ThreadPoolExecutor.
Args:
examples: List of (cache_key, output) tuples where output contains a "trajectory"
list with steps that have "prompt" messages in OpenAI chat format.
Returns:
Tuple of (all_images, step_image_indices_per_example)
- all_images: deduplicated flat list of decoded PIL images
- step_image_indices_per_example: dict mapping cache_key to per-step lists of
indices into all_images (e.g., [[0], [0, 1], [1]] for the decreasing-images case)
"""
# Pass 1: collect unique b64 keys and build step indices
unique_keys: list[str] = []
key_to_index: dict[str, int] = {}
step_image_indices_per_example: dict[int, list[list[int]]] = {}
for eid, output in examples:
trajectory = output.get("trajectory", [])
if not trajectory:
step_image_indices_per_example[eid] = []
continue
step_image_indices = []
for step in trajectory:
prompt = step.get("prompt")
image_keys = _collect_image_keys_from_messages(prompt)
indices = []
for key in image_keys:
if key not in key_to_index:
key_to_index[key] = len(unique_keys)
unique_keys.append(key)
indices.append(key_to_index[key])
step_image_indices.append(indices)
step_image_indices_per_example[eid] = step_image_indices
# Pass 2: decode unique images (parallel when worthwhile)
if len(unique_keys) > _PARALLEL_DECODE_THRESHOLD:
with ThreadPoolExecutor(max_workers=min(len(unique_keys), 16)) as pool:
all_images = list(pool.map(_decode_image, unique_keys))
else:
all_images = [_decode_image(k) for k in unique_keys]
del unique_keys, key_to_index
strip_base64_images(examples)
return all_images, step_image_indices_per_example
_DEFAULT_IMAGE_CHUNK_SIZE = 32
class _ImageStore:
"""Holds per-unique-image data, assembled lazily on demand.
Instead of duplicating pixel bytes for every step that references an image,
we store each image's bytes once and assemble the concatenation at retrieval time.
"""
def __init__(
self,
image_bytes: list[bytes],
image_num_patches: list[int],
patch_dim: int,
image_grids: list[list[int]],
):
self.image_bytes = image_bytes
self.image_num_patches = image_num_patches
self.patch_dim = patch_dim
self.image_grids = image_grids
self._cache: dict[tuple[int, ...], tuple[bytes, list[int], list[list[int]]]] = {}
def assemble(self, indices: list[int]) -> tuple[bytes, list[int], list[list[int]]]:
"""Assemble pixel bytes, shape, and grids for a set of image indices.
Results are cached by index tuple — multi-turn rollouts with the same
cumulative image set (common across rollouts of the same example) hit
the cache and skip the join.
"""
cache_key = tuple(indices)
cached = self._cache.get(cache_key)
if cached is not None:
return cached
total_patches = sum(self.image_num_patches[i] for i in indices)
pixel_bytes = b"".join(self.image_bytes[i] for i in indices)
shape = [total_patches, self.patch_dim]
grids = [self.image_grids[i] for i in indices]
result = (pixel_bytes, shape, grids)
self._cache[cache_key] = result
return result
def _preprocess_images_batched(
images: list[Image.Image],
step_image_indices_per_example: dict[int, list[list[int]]],
processor,
chunk_size: int = _DEFAULT_IMAGE_CHUNK_SIZE,
) -> tuple["_ImageStore | None", dict[int, list[list[int]]]]:
"""
Preprocess all images in chunked batches, returning an _ImageStore and step indices.
Images are processed in chunks to avoid OOM on large batches. Per-image bytes are
stored once in the _ImageStore and assembled lazily at retrieval time.
Returns:
Tuple of (_ImageStore or None, step_image_indices_per_example).
The store is None when there are no images or no processor.
"""
if not images or processor is None:
return None, step_image_indices_per_example
logger = get_logger()
image_sizes = [(img.width, img.height) for img in images]
# Process images in chunks to avoid OOM, parallelized across threads
# (PIL/numpy release the GIL so threads give real concurrency here)
chunks = [images[i : i + chunk_size] for i in range(0, len(images), chunk_size)]
def _process_chunk(chunk: list[Image.Image]) -> tuple[torch.Tensor, torch.Tensor]:
processed = processor.image_processor(images=chunk, return_tensors="pt")
return processed["pixel_values"], processed["image_grid_thw"]
if len(chunks) > 1:
with ThreadPoolExecutor(max_workers=min(len(chunks), 8)) as pool:
results = list(pool.map(_process_chunk, chunks))
else:
results = [_process_chunk(chunks[0])]
# Free PIL images now that preprocessing is done
del chunks
images.clear()
all_pixel_values_list = [r[0] for r in results]
all_grid_thw_list = [r[1] for r in results]
all_pixel_values = torch.cat(all_pixel_values_list, dim=0)
all_grid_thw = torch.cat(all_grid_thw_list, dim=0)
del all_pixel_values_list, all_grid_thw_list, results
logger.debug(
f"VLM image processing: {len(image_sizes)} images, sizes={image_sizes}, "
f"pixel_values={all_pixel_values.shape}, grid_thw={all_grid_thw.tolist()}"
)
# Pre-compute patch start offset for each image
patch_starts = [0]
for g in all_grid_thw:
patch_starts.append(patch_starts[-1] + int(g[0] * g[1] * g[2]))
patch_dim = all_pixel_values.shape[1]
# Convert to bytes per-image and free the tensor immediately after
image_bytes_list: list[bytes] = []
image_num_patches_list: list[int] = []
image_grids_list: list[list[int]] = []
for i in range(len(image_sizes)):
img_slice = all_pixel_values[patch_starts[i] : patch_starts[i + 1]]
image_bytes_list.append(img_slice.numpy().tobytes())
image_num_patches_list.append(img_slice.shape[0])
image_grids_list.append(all_grid_thw[i].tolist())
del all_pixel_values, all_grid_thw
store = _ImageStore(
image_bytes=image_bytes_list,
image_num_patches=image_num_patches_list,
patch_dim=patch_dim,
image_grids=image_grids_list,
)
return store, step_image_indices_per_example
class VLMImageCache:
"""Result of building VLM image cache with per-step image data."""
def __init__(
self,
cache: dict[int, list[tuple[bytes | None, list[int] | None, list[list[int]] | None]]],
num_unique_examples: int,
extract_time: float,
preprocess_time: float,
):
self._store: _ImageStore | None = None
self._step_indices: dict[int, list[list[int]]] | None = None
self.cache = cache
self.num_unique_examples = num_unique_examples
self.num_unique_images = 0
self.extract_time = extract_time
self.preprocess_time = preprocess_time
@classmethod
def from_store(
cls,
store: _ImageStore | None,
step_indices: dict[int, list[list[int]]],
num_unique_examples: int,
num_unique_images: int,
extract_time: float,
preprocess_time: float,
) -> "VLMImageCache":
"""Create a store-backed cache that assembles bytes lazily."""
obj = cls.__new__(cls)
obj._store = store
obj._step_indices = step_indices
obj.cache = {}
obj.num_unique_examples = num_unique_examples
obj.num_unique_images = num_unique_images
obj.extract_time = extract_time
obj.preprocess_time = preprocess_time
return obj
def _assemble(self, indices: list[int]) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
if not indices:
return (None, None, None)
return self._store.assemble(indices)
def get_for_step(
self, cache_key: int, step_idx: int
) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
"""Get cumulative images up to and including the given step."""
if self._store is not None:
steps = self._step_indices.get(cache_key, [])
if not steps or step_idx >= len(steps):
return (None, None, None)
return self._assemble(steps[step_idx])
steps = self.cache.get(cache_key, [])
if not steps or step_idx >= len(steps):
return (None, None, None)
return steps[step_idx]
def get_all(self, cache_key: int) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
"""Get all images for the cache key (last step's cumulative images)."""
if self._store is not None:
steps = self._step_indices.get(cache_key, [])
if not steps:
return (None, None, None)
return self._assemble(steps[-1])
steps = self.cache.get(cache_key, [])
if not steps:
return (None, None, None)
return steps[-1]
def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMImageCache:
"""
Build image cache for VLM training by extracting and preprocessing images.
Caches per rollout to keep images aligned with divergent multi-turn trajectories.
"""
examples = [(idx, rollout) for idx, rollout in enumerate(rollouts)]
unique_example_ids = {(rollout.get("env_name"), rollout["example_id"]) for rollout in rollouts}
# Extract images (also strips base64 data from rollout prompts to free memory)
extract_start = time.perf_counter()
all_images, images_per_example = _extract_images_from_examples(examples)
num_unique_images = len(all_images)
extract_time = time.perf_counter() - extract_start
# Preprocess images (clears PIL image list when done)
preprocess_start = time.perf_counter()
store, step_indices = _preprocess_images_batched(all_images, images_per_example, processor)
preprocess_time = time.perf_counter() - preprocess_start
return VLMImageCache.from_store(
store=store,
step_indices=step_indices,
num_unique_examples=len(unique_example_ids),
num_unique_images=num_unique_images,
extract_time=extract_time,
preprocess_time=preprocess_time,
)
+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):
+35 -6
View File
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
@@ -112,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
@@ -127,10 +135,18 @@ 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
srun bash -c '
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed router/engine terminates the SLURM job instead of leaving
# the surviving ranks holding nodes.
srun --kill-on-bad-exit=1 bash -c '
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router) as task failures.
set -o pipefail
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
@@ -159,6 +175,7 @@ srun 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
@@ -262,7 +279,7 @@ srun bash -c '
--parallel.dp $EP \
--data-parallel-rpc-port $RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- elif num_nodes > 1 %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
@@ -289,7 +306,7 @@ srun bash -c '
@ $CONFIG_PATH \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- else %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Required for graph compilation to work
@@ -297,6 +314,18 @@ srun bash -c '
uv run inference \
@ $CONFIG_PATH \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router) into task failures that
# --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job tears
# down instead of leaving zombies holding the allocation.
wait -n
EXIT_CODE=$?
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
for pid in $(jobs -p); do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
'
+38 -9
View File
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_TRAIN_NODES={{ num_train_nodes }}
export NUM_INFER_NODES={{ num_infer_nodes }}
@@ -156,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
@@ -171,10 +179,18 @@ 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
srun bash -c '
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed component terminates the SLURM job instead of leaving the
# surviving ranks holding nodes.
srun --kill-on-bad-exit=1 bash -c '
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router, orchestrator) as task failures.
set -o pipefail
# Source environment
cd $PROJECT_DIR
[ -f .env ] && source .env
@@ -212,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
@@ -313,7 +330,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
--parallel.dp $DP \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- else -%}
# Start vllm-router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
@@ -349,13 +366,13 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
--server.port $BACKEND_PORT \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
fi
{%- endif %}
@@ -364,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 &
@@ -394,6 +411,18 @@ else
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.toml \
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
{% if num_infer_nodes > 0 %} fi{% endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router, orchestrator) into task failures
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
# tears down instead of leaving zombies holding the allocation.
wait -n
EXIT_CODE=$?
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
for pid in $(jobs -p); do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
'
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately on any failed command so a crash on any node releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
@@ -63,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
@@ -78,10 +86,15 @@ 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
srun bash -c '
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a single trainer crash terminates the entire SLURM job instead of
# leaving the surviving ranks (and their nodes) idle.
srun --kill-on-bad-exit=1 bash -c '
set -o pipefail
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
set -e
export PROJECT_DIR={{ project_dir }}
# Setup environment
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
set -e
export PROJECT_DIR={{ project_dir }}
# Setup environment
+78 -14
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,20 +127,18 @@ 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,
# Multimodal fields (Qwen3-VL) - passed through without modification
pixel_values=training_example.pixel_values,
pixel_values_shape=training_example.pixel_values_shape,
image_grid_thw=training_example.image_grid_thw,
mm_kwargs=training_example.mm_kwargs,
training_mode=training_example.training_mode,
)
def _is_multimodal_sample(sample: MicroBatch) -> bool:
"""Check if a sample contains multimodal data (images)."""
return sample.pixel_values is not None
return sample.mm_kwargs is not None
def packed_samples_into_micro_bs(
@@ -98,7 +149,7 @@ def packed_samples_into_micro_bs(
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
With per-token temperatures, samples can be packed together regardless of their temperature values.
NOTE: Multimodal samples (with pixel_values) are NOT packed together as they have variable-sized
NOTE: Multimodal samples (with mm_kwargs) are NOT packed together as they have variable-sized
vision data that doesn't pack well. Each multimodal sample becomes its own micro batch.
"""
# Sort by (lora_idx, -length) for packing efficiency
@@ -125,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 = []
@@ -178,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)
@@ -190,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 -31
View File
@@ -12,9 +12,8 @@ os.environ.setdefault("USE_HUB_KERNELS", "NO")
import torch
import torch._dynamo
import torch.nn as nn
from beartype import beartype as typechecker
from huggingface_hub import snapshot_download
from jaxtyping import Float, Int, jaxtyped
from jaxtyping import Int
from torch import Tensor
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
@@ -1100,25 +1099,6 @@ def setup_model(
return model
def _get_qwen3_vl_mm_token_type_ids(model: nn.Module, input_ids: Tensor) -> Tensor | None:
config = getattr(model, "config", None)
if getattr(config, "model_type", None) != "qwen3_vl":
return None
mm_token_type_ids = torch.zeros_like(input_ids)
image_token_id = getattr(config, "image_token_id", None)
if image_token_id is not None:
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == image_token_id, 1)
video_token_id = getattr(config, "video_token_id", None)
if video_token_id is not None:
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == video_token_id, 2)
return mm_token_type_ids
@jaxtyped(typechecker=typechecker)
def forward(
model: nn.Module,
input_ids: Int[Tensor, "batch seq"],
@@ -1126,9 +1106,13 @@ def forward(
labels: Int[Tensor, "batch seq"] | None = None,
temperature: Tensor | None = None,
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
# Multimodal fields (Qwen3-VL)
pixel_values: Float[Tensor, "num_patches patch_dim"] | None = None,
image_grid_thw: Int[Tensor, "num_images 3"] | None = None,
# Generic multimodal kwargs (e.g. {"pixel_values": ...,
# "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...}
# for Gemma3). Passed straight through to ``model(**kwargs)`` so
# the model's HF forward signature is the schema. ``mm_token_type_ids``
# is split out because it's prime-rl-computed (from token ids),
# not a renderer/processor output.
mm_kwargs: dict[str, Tensor] | None = None,
mm_token_type_ids: Int[Tensor, "batch seq"] | None = None,
) -> PrimeLmOutput:
# Build kwargs for model forward
@@ -1138,15 +1122,19 @@ def forward(
"temperature": temperature,
}
# For multimodal (VLM), don't pass position_ids - let the model compute MRoPE internally
# using image_grid_thw. Qwen3-VL only computes proper MRoPE when position_ids is None.
if pixel_values is not None:
assert image_grid_thw is not None, "pixel_values requires image_grid_thw for MRoPE computation"
kwargs["pixel_values"] = pixel_values
kwargs["image_grid_thw"] = image_grid_thw
mm_token_type_ids = _get_qwen3_vl_mm_token_type_ids(model, input_ids)
if mm_kwargs:
# Forward the per-model multimodal tensors verbatim, plus the
# renderer-supplied ``mm_token_type_ids`` (renderer owns the
# token→modality mapping via ``mm_token_type_id_map``).
kwargs.update(mm_kwargs)
if mm_token_type_ids is not None:
kwargs["mm_token_type_ids"] = mm_token_type_ids
# ``position_ids`` for MRoPE families: Qwen3-VL's HF forward
# recomputes 3D positions from ``image_grid_thw`` and breaks if
# given the trainer's pre-computed 1D ``position_ids``. Detect
# via the mm_kwargs shape so we don't enumerate model_types.
if "image_grid_thw" not in mm_kwargs:
kwargs["position_ids"] = position_ids
else:
kwargs["position_ids"] = position_ids
+49 -23
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"]
@@ -32,11 +33,12 @@ class TensorMicroBatch(TypedDict):
# MoE router replay
routed_experts: Int[Tensor, "batch seq layers topk"] | None
# Multimodal fields (Qwen3-VL)
# pixel_values: flattened image patches [num_patches, patch_dim] where patch_dim=1176 for Qwen3-VL
pixel_values: Float[Tensor, "num_patches patch_dim"] | None
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: Int[Tensor, "num_images 3"] | None
# Generic multimodal kwargs — flat dict matching the model's forward
# signature (e.g. ``{"pixel_values": ..., "image_grid_thw": ...}`` for
# Qwen3-VL; ``{"pixel_values": ...}`` for Gemma3-VL). The trainer
# ``**`` -unpacks this into the forward call, so any HF VLM whose
# processor and forward agree on kwarg names works out of the box.
mm_kwargs: dict[str, Tensor] | None
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
@@ -107,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),
@@ -114,8 +117,7 @@ class FakeDataLoader:
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"pixel_values": None,
"image_grid_thw": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
}
@@ -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),
@@ -142,8 +145,7 @@ class FakeDataLoader:
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"pixel_values": None,
"image_grid_thw": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
}
@@ -199,10 +201,34 @@ class DataLoader:
if micro_batch.lora_num_tokens is None:
micro_batch.lora_num_tokens = [0] * self.multi_run_manager.max_runs
micro_batch.lora_num_tokens[0] = len(micro_batch.input_ids)
mm_kwargs: dict[str, Tensor] | None = None
if micro_batch.mm_kwargs:
# Each value is an EncodedTensor (dtype, shape, raw bytes).
# No batch dim — the orchestrator concatenates per-image along
# dim=0 generically, matching what each HF VLM's forward expects.
mm_kwargs = {
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
@@ -211,22 +237,22 @@ class DataLoader:
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
# Multimodal fields - no batch dimension for these as they are variable-sized
pixel_values=torch.frombuffer(bytearray(micro_batch.pixel_values), dtype=torch.float32).reshape(
micro_batch.pixel_values_shape
)
if micro_batch.pixel_values is not None
else None,
image_grid_thw=torch.tensor(micro_batch.image_grid_thw, dtype=torch.long)
if micro_batch.image_grid_thw is not None
else None,
mm_kwargs=mm_kwargs,
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,
)
def _torch_dtype(name: str) -> torch.dtype:
"""Resolve a numpy/torch dtype name (e.g. ``"float32"``) to torch.dtype."""
# Strip the ``numpy.`` prefix some dtype reprs carry.
name = name.replace("numpy.", "")
if hasattr(torch, name):
return getattr(torch, name)
# numpy ↔ torch alias mismatches (rare but possible) — fall back via numpy.
import numpy as np
return torch.from_numpy(np.zeros(1, dtype=np.dtype(name))).dtype
+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
+30 -13
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'})")
@@ -338,9 +341,15 @@ def train(config: TrainerConfig):
forward_backward_start_time = time.perf_counter()
seq_len = micro_batches[0]["input_ids"].shape[1]
# Normalize by the local number of unmasked tokens in the batch (per-batch length normalization)
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
loss_scale = max(loss_scale, 1)
# Normalize by the global (dp_cp) number of unmasked tokens in the batch, so every rank
# divides by the same denominator. With a per-rank denominator, ranks with fewer loss
# tokens implicitly upweight their per-token gradient contribution after FSDP averaging.
# FSDP's per-rank divide is undone after the microbatch loop via fsdp_gradient_divide_factor.
local_loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
global_loss_scale = torch.tensor(local_loss_scale, dtype=torch.int64, device="cuda")
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
dist.all_reduce(global_loss_scale, op=dist.ReduceOp.SUM, group=dp_cp_group)
loss_scale = max(global_loss_scale.item(), 1)
logger.debug(f"Starting forward and backward pass ({batch_size=})")
tensors = Tensors() # Used to accumulate tensor statistics across micro-batches and ranks for logging
@@ -371,13 +380,12 @@ def train(config: TrainerConfig):
# we could've gotten routed experts from the inference server, but we didn't enable router replay
routed_experts = None
# Multimodal fields (Qwen3-VL) - only present for VLM training
pixel_values = (
micro_batch["pixel_values"].to("cuda") if micro_batch.get("pixel_values") is not None else None
)
image_grid_thw = (
micro_batch["image_grid_thw"].to("cuda") if micro_batch.get("image_grid_thw") is not None else None
)
# Multimodal kwargs are an opaque per-model dict (e.g.
# {"pixel_values": ..., "image_grid_thw": ...} for Qwen3-VL,
# just {"pixel_values": ...} for Gemma3-VL) — we move every
# tensor to CUDA and let the model's forward sort them.
mm_kwargs_raw = micro_batch.get("mm_kwargs")
mm_kwargs = {k: v.to("cuda") for k, v in mm_kwargs_raw.items()} if mm_kwargs_raw else None
mm_token_type_ids = (
micro_batch["mm_token_type_ids"].to("cuda")
if micro_batch.get("mm_token_type_ids") is not None
@@ -387,7 +395,7 @@ def train(config: TrainerConfig):
labels = shift_tensor_left(input_ids)
# VLM + CP is not supported: MRoPE requires global positions but CP shards the sequence
if cp_enabled and pixel_values is not None:
if cp_enabled and mm_kwargs is not None:
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
if cp_enabled:
@@ -426,8 +434,7 @@ def train(config: TrainerConfig):
forward_position_ids,
labels=labels,
temperature=temperatures,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
)
@@ -496,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():
@@ -514,6 +523,12 @@ def train(config: TrainerConfig):
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
# across dp_cp so the final gradient is the true per-token mean over the global batch.
for param in model.parameters():
if param.grad is not None:
param.grad.mul_(parallel_dims.fsdp_gradient_divide_factor)
# Optionally, clip the gradients
grad_norm: torch.Tensor | None = None
if config.optim.max_norm is not None:
@@ -668,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:
+31 -12
View File
@@ -5,6 +5,23 @@ import msgspec
TrainingMode = Literal["rl", "opd", "sft"]
# Encoded tensor: {dtype: "float32", shape: [...], data: <bytes>}.
# Mirrors verifiers.utils.serve_utils.msgpack_encoder so the same wire
# shape is used end-to-end from renderer → orchestrator → trainer.
class EncodedTensor(msgspec.Struct, array_like=True, gc=False):
dtype: str
shape: list[int]
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."""
@@ -20,13 +37,17 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
advantage: float | None = None
reward: float | None = None
# Multimodal fields (Qwen3-VL) — pixel_values stored as raw float32 bytes for efficient serialization
pixel_values: bytes | None = None
pixel_values_shape: list[int] | None = None # [num_patches, patch_dim]
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: list[list[int]] | None = None
# Generic multimodal kwargs: flat dict keyed by the kwarg names the
# model's forward expects (e.g. {"pixel_values": ..., "image_grid_thw":
# ...} for Qwen3-VL; just {"pixel_values": ...} for Gemma3). The
# orchestrator batches per-image renderer items by torch.cat along
# dim=0 generically — no model-specific knowledge in prime-rl. The
# trainer ``**`` -unpacks this into the model forward, so any VLM
# whose HF processor / forward agree on kwarg names works without
# 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
@@ -57,16 +78,14 @@ 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
# Multimodal fields (Qwen3-VL) — pixel_values stored as raw float32 bytes for efficient serialization
pixel_values: bytes | None = None
pixel_values_shape: list[int] | None = None # [num_patches, patch_dim]
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: list[list[int]] | None = None
# See TrainingSample.mm_kwargs.
mm_kwargs: dict[str, EncodedTensor] | 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
# 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)
+10 -1
View File
@@ -9,6 +9,7 @@ import verifiers as vf
import wandb
from transformers.tokenization_utils import PreTrainedTokenizer
from wandb.errors import CommError
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.chat_template import deserialize_tool_calls
@@ -70,11 +71,14 @@ class WandbMonitor(Monitor):
mode = os.environ.get("WANDB_MODE", "offline" if config.offline else "online")
settings = wandb.Settings(mode=mode)
retryable_errors = (CommError, ServerResponseError) if shared_mode else (CommError,)
def init_wandb(max_retries: int):
for attempt in range(max_retries):
try:
return wandb.init(
id=run_id,
resume="allow" if run_id else None,
project=config.project,
entity=config.entity,
name=config.name,
@@ -84,7 +88,7 @@ class WandbMonitor(Monitor):
config=run_config.model_dump() if run_config else None,
settings=settings,
)
except CommError as e:
except retryable_errors as e:
if attempt + 1 == max_retries:
raise
if shared_mode and not primary:
@@ -94,6 +98,11 @@ class WandbMonitor(Monitor):
else:
msg = f"Transient W&B init error ({e}) - retrying in 10s ({attempt + 1}/{max_retries})"
self.logger.info(msg)
# A failed wandb.init leaves the run_id registered in the local
# wandb-core StreamMux, causing the next attempt to fail with
# "run ID ... is in use". Tear down the service so the retry
# starts from a clean state.
wandb.teardown()
time.sleep(10)
# Non-primary processes in shared mode wait for the primary to create the run.
+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
@@ -0,0 +1,190 @@
"""End-to-end integration test for the Qwen3-VL renderer path.
Walks a multimodal request through the full client stack — RendererClient
→ renderers.client.generate → /inference/v1/generate features payload —
with the HTTP layer mocked, and verifies that vLLM can deserialize the
features back into engine inputs identical to what its own server-side
processor would have produced for the same messages.
This is the strongest end-to-end check we can run without a GPU. The
remaining missing piece (vLLM actually consuming the engine input,
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()
_MODEL = "Qwen/Qwen3-VL-4B-Instruct"
def _model_cached() -> bool:
safe = "models--" + _MODEL.replace("/", "--")
snapshots = _HF_CACHE / safe / "snapshots"
if not snapshots.is_dir():
return False
return any(p.is_dir() for p in snapshots.iterdir())
pytestmark = pytest.mark.skipif(
not _model_cached(),
reason=f"{_MODEL}: HF snapshot not cached locally",
)
class _FakeOpenAI:
"""Minimal AsyncOpenAI stand-in that captures POST bodies.
The renderer client calls ``client.post(absolute_url, body=...)``;
we capture the body for assertions and return a canned generate
response so the parse-side of the flow runs.
"""
def __init__(self):
self.calls: list[dict[str, Any]] = []
self.base_url = "http://fake-host:8000/v1"
async def post(self, path, *, cast_to=dict, body=None, options=None):
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.
payload = {
"request_id": "qwen-vl-e2e",
"choices": [
{
"index": 0,
"token_ids": [50, 60, 151645],
"logprobs": {
"content": [
{"token": "t1", "logprob": -0.1},
{"token": "t2", "logprob": -0.2},
{"token": "t3", "logprob": -0.3},
]
},
"finish_reason": "stop",
},
],
}
return httpx.Response(200, content=json.dumps(payload).encode())
def test_renderer_client_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
"""Walk a Qwen3-VL multimodal turn through the renderer client and
verify the resulting ``/inference/v1/generate`` body has a valid
``features`` payload that:
1. parses through vLLM's ``GenerateRequest`` pydantic model,
2. decodes back to ``MultiModalKwargsItem`` instances carrying
``pixel_values`` + ``image_grid_thw`` of the right shapes,
3. has placeholder ranges that exactly cover the ``<|image_pad|>``
runs in the prompt token sequence.
"""
from PIL import Image
from renderers.base import load_tokenizer
from renderers.qwen3_vl import Qwen3VLRenderer
from transformers import AutoProcessor
from verifiers.clients.renderer_client import RendererClient
from verifiers.types import (
ClientConfig,
UserMessage,
)
from vllm.entrypoints.serve.disagg.mm_serde import decode_mm_kwargs_item
from vllm.entrypoints.serve.disagg.protocol import GenerateRequest
# ── Build a real Qwen3VLRenderer with a real processor. ─────────────
tokenizer = load_tokenizer(_MODEL)
processor = AutoProcessor.from_pretrained(_MODEL)
renderer = Qwen3VLRenderer(tokenizer, processor=processor)
image_pad_id = tokenizer.convert_tokens_to_ids("<|image_pad|>")
# ── Manually wire a RendererClient bypassing the pool factory. ──────
client_cfg = ClientConfig(client_type="renderer", base_url="http://fake-host:8000/v1")
rc = object.__new__(RendererClient)
rc._config = client_cfg
rc._renderer = renderer
rc._pool_size = 1
rc._client = _FakeOpenAI()
rc.logger = MagicMock()
# ── Build a verifiers-shaped user message with an image. ────────────
img = Image.new("RGB", (224, 224), color=(64, 128, 255))
# The renderer accepts the OpenAI ``image_url`` content-part shape —
# the same shape verifiers' UserMessage carries through.
user = UserMessage(
content=[
{"type": "text", "text": "What's in this picture?"},
# Embed the PIL image directly. The verifiers→renderer message
# converter forwards content unchanged for our purposes.
{"type": "image", "image": img},
]
)
# to_native_prompt converts to renderer-shaped messages.
prompt, _ = asyncio.run(rc.to_native_prompt([user]))
sampling = {"max_tokens": 16}
response = asyncio.run(
rc.get_native_response(
prompt=prompt,
model=_MODEL,
sampling_args=sampling,
tools=None,
)
)
# ── The HTTP body should carry a features payload. ──────────────────
fake = rc.client
assert isinstance(fake, _FakeOpenAI)
assert len(fake.calls) == 1
body = fake.calls[0]["body"]
assert "features" in body, "RendererClient should ship features for image content"
features = body["features"]
# ── Pydantic-roundtrip through vLLM's GenerateRequest model. ────────
gen_req = GenerateRequest(
token_ids=body["token_ids"],
features=features,
sampling_params=body["sampling_params"],
)
assert gen_req.features is not None
assert "image" in gen_req.features.mm_hashes
assert len(gen_req.features.mm_hashes["image"]) == 1
# ── Placeholder anchoring: the offset/length in features must land
# exactly on a run of <|image_pad|> ids in the prompt. ───────────
placeholders = gen_req.features.mm_placeholders["image"]
assert len(placeholders) == 1
ph = placeholders[0]
pad_slice = body["token_ids"][ph.offset : ph.offset + ph.length]
assert all(t == image_pad_id for t in pad_slice), (
f"placeholder span ({ph.offset}, {ph.length}) does not cover image_pad tokens; slice={pad_slice[:8]}..."
)
# ── kwargs_data decodes to MultiModalKwargsItem with the right keys. ─
assert gen_req.features.kwargs_data is not None
encoded_items = gen_req.features.kwargs_data["image"]
assert len(encoded_items) == 1
item = decode_mm_kwargs_item(encoded_items[0])
assert set(item.keys()) == {"pixel_values", "image_grid_thw"}
# The image_grid_thw must match what the HF processor would have
# produced for the same PIL image — strongest signal that the engine
# sees the same image features the trainer will.
direct_proc_out = processor.image_processor(images=[img], return_tensors="pt")
expected_grid = direct_proc_out["image_grid_thw"][0].tolist()
assert item["image_grid_thw"].data.tolist() == expected_grid
# ── Response parsed through renderer's parse_response. ──────────────
assert response["completion_ids"] == [50, 60, 151645]
# multi_modal_data surfaces on the result so the caller can persist it.
assert response["multi_modal_data"] is not None
assert len(response["multi_modal_data"].mm_items["image"]) == 1
@@ -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
File diff suppressed because it is too large Load Diff
+10 -8
View File
@@ -157,18 +157,20 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
def test_orchestrator_vlm_configs_must_disable_renderer():
with pytest.raises(ValidationError, match="orchestrator.use_renderer is not supported for VLMs"):
def test_orchestrator_vlm_requires_renderer():
with pytest.raises(ValidationError, match="orchestrator.use_renderer must be true when model.vlm is set"):
OrchestratorConfig.model_validate(
{
"student": {
"model": {
"name": "Qwen/Qwen3-VL-4B-Instruct",
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
},
}
}
},
"use_renderer": False,
}
)
@@ -176,17 +178,17 @@ def test_orchestrator_vlm_configs_must_disable_renderer():
{
"student": {
"model": {
"name": "Qwen/Qwen3-VL-4B-Instruct",
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
},
}
},
"use_renderer": False,
}
)
assert config.use_renderer is False
assert config.use_renderer is True
def test_selective_activation_checkpointing_requires_custom_impl():
@@ -433,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.
+45 -12
View File
@@ -18,33 +18,66 @@ class _CaptureModel(nn.Module):
return {"logits": torch.zeros(*input_ids.shape, 4)}
def test_forward_adds_qwen3_vl_mm_token_type_ids():
image_token_id = 10
video_token_id = 20
model = _CaptureModel(
SimpleNamespace(model_type="qwen3_vl", image_token_id=image_token_id, video_token_id=video_token_id)
)
input_ids = torch.tensor([[1, image_token_id, image_token_id, 2, video_token_id]])
def test_forward_passes_renderer_mm_token_type_ids_through():
"""``forward()`` forwards renderer-supplied ``mm_token_type_ids``
verbatim — the trainer no longer auto-computes from the model
config, since the renderer is the source of truth."""
model = _CaptureModel(SimpleNamespace(model_type="qwen3_vl"))
input_ids = torch.tensor([[1, 10, 10, 2, 20]])
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
pixel_values = torch.ones(2, 3)
image_grid_thw = torch.tensor([[1, 1, 2]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 0, 2]])
forward(model, input_ids, position_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
forward(
model,
input_ids,
position_ids,
mm_kwargs={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw},
mm_token_type_ids=mm_token_type_ids,
)
assert model.kwargs is not None
# MRoPE families (image_grid_thw present) get position_ids stripped.
assert "position_ids" not in model.kwargs
torch.testing.assert_close(model.kwargs["pixel_values"], pixel_values)
torch.testing.assert_close(model.kwargs["image_grid_thw"], image_grid_thw)
torch.testing.assert_close(model.kwargs["mm_token_type_ids"], torch.tensor([[0, 1, 1, 0, 2]]))
torch.testing.assert_close(model.kwargs["mm_token_type_ids"], mm_token_type_ids)
def test_forward_skips_mm_token_type_ids_for_other_vlm_models():
model = _CaptureModel(SimpleNamespace(model_type="qwen3_5_moe", image_token_id=10))
def test_forward_omits_mm_token_type_ids_when_renderer_does_not_supply():
"""When the renderer doesn't ship ``mm_token_type_ids`` (text-only
or a family without modality markers), ``forward()`` doesn't
fabricate one."""
model = _CaptureModel(SimpleNamespace(model_type="qwen3_vl"))
input_ids = torch.tensor([[1, 10, 10, 2]])
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
forward(model, input_ids, position_ids, pixel_values=torch.ones(2, 3), image_grid_thw=torch.tensor([[1, 1, 2]]))
forward(
model,
input_ids,
position_ids,
mm_kwargs={"pixel_values": torch.ones(2, 3), "image_grid_thw": torch.tensor([[1, 1, 2]])},
)
assert model.kwargs is not None
assert "position_ids" not in model.kwargs
assert "mm_token_type_ids" not in model.kwargs
def test_forward_keeps_position_ids_for_non_mrope_vlm():
"""Non-MRoPE VLM families (no ``image_grid_thw``) keep the trainer's
pre-computed ``position_ids``."""
model = _CaptureModel(SimpleNamespace(model_type="gemma3"))
input_ids = torch.tensor([[1, 10, 10, 2]])
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
forward(
model,
input_ids,
position_ids,
mm_kwargs={"pixel_values": torch.ones(2, 3)},
)
assert model.kwargs is not None
torch.testing.assert_close(model.kwargs["position_ids"], position_ids)
+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)

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