Compare commits

..
Author SHA1 Message Date
2662c9ace1 feat: select taskset tasks per train and eval source (#3703)
## Summary

- Give every train and eval source a `select` block (`EnvConfig.select`,
a `vf.SelectConfig`): `include`/`exclude` by task `idx`, `ids`, `keys`
or `names`, then `shuffle`, `skip` and `limit`. The orchestrator loads
each source's tasks with `vf.load_taskset(...).select(source.select)`.
prime-rl no longer shuffles or slices tasksets itself, so it picks the
same tasks as `vf-eval` for the same selection.
  ```toml
  [[orchestrator.train.source]]
  env.taskset.id = "gsm8k"
  select.exclude.idx = [":100"]   # hold out the first 100 tasks

  [[orchestrator.eval.source]]
  env.taskset.id = "gsm8k"
  select.include.idx = [":100"]
  ```
- Every source group (`[orchestrator.train]`, `[orchestrator.eval]`, SFT
`[eval]`, the top level of `uv run eval`) takes a shared `select` block.
The same before-validator that layers the group `env` block layers it
under each source, field by field, and a field that the source sets
wins. A source's `include` or `exclude` replaces the group's whole
block. A source `select` that does not validate keeps its own block, so
its error surfaces. For example, this evaluates 128 tasks of each
taskset:
  ```toml
  [orchestrator.eval.select]
  limit = 128
  ```
- Only `uv run eval` has the `-n`/`-s` short flags
(`select.limit`/`select.shuffle`), through `vf.SelectCLIConfig`. The
`rl`, `orchestrator` and `sft` CLIs have several `select` blocks, so
they get no short flags.
- The dashboard derives the expected episode count from `select.limit`,
per source and for vf-shaped configs.
- Migrate the configs, examples and docs from `num_examples` to
`select.limit`. Group-level blocks use `[... .select]` tables.
- Update the eval docs and skill: resume no longer checks the config
(#3690), and a resume matches landed episodes to the new `select` by
`task.key`.
- Update the `configs` skill (`[select]`, `-s`). Update the eval skill:
the `select` shorthands, and common patterns (a random subset, tasks by
position or name, dropping broken tasks, contiguous and random
train/test splits via `include`/`exclude` and `skip`).
- Pin `deps/verifiers` to its main, which merged
PrimeIntellect-ai/verifiers#2695 (`Taskset.select`, `vf.SelectConfig`).
Raise the `verifiers` minimum to `0.3.2.dev152`, its first release, in
both `pyproject.toml` files, so the slim `prime-rl-configs` install gets
it.

Companion PRs: PrimeIntellect-ai/verifiers#2695 (merged),
PrimeIntellect-ai/prime-envs#852 (independent; `compile_statements`
stops calling `head()`).

## Breaking

- `EnvConfig.shuffle` is removed. Use `select.shuffle`.
- `EvalSourceConfig.num_examples` and the group-level `num_examples` are
removed. Use `select.limit` on the source or on the eval block.
- The shuffle seed changes from 42 to verifiers' default 0
(`select.seed`). Existing `shuffle = true` configs pick other tasks, so
eval numbers before and after this change are not comparable.
- Default task keys change for tasksets that never set `idx` (see
verifiers#2695). An interrupted eval of such a taskset cannot resume
across this change.

## Verification

- The slim-install CI check, run locally: the `prime-rl-configs` wheel
installed outside the workspace resolves `verifiers 0.3.2.dev152`, and
the workflow's import script passes.
- `uv run pytest tests/unit/test_configs.py tests/unit/eval
tests/unit/orchestrator tests/unit/test_dashboard_timeline.py`: 296
passed (2 vLLM-only tests deselected; `vllm` is not installed on the
test box). `test_load_configs` loads every migrated TOML.
- Real configs and CLI calls against a local mock OpenAI server (no
inference spend). The mock counted the model calls, and the selected
task `idx` matched an independent oracle:
- `uv run eval @ configs/debug/eval/single-turn.toml`: tasks 0–7 × 2, 16
calls.
- `uv run eval @ configs/debug/eval/resume.toml`: first run 16 calls.
`--resume --select.limit 10` restored 16 episodes and ran only tasks 8–9
(4 calls). `--resume --select.include.idx 0:5` kept the landed episodes
of tasks 0–4 and made no model calls.
- `uv run eval gsm8k -n 4 -s --select.exclude.idx '[0]'`: the oracle's 4
tasks, 4 calls.
- A two-source TOML that splits gsm8k into `[:50]` and the rest under a
group `select` default: both sources match the oracle, 5 calls.
- Config checks: train and eval group `select` defaults reach every
source, a source's own fields win, and the resolved `OrchestratorConfig`
re-validates to the same values. `uv run rl -h`, `orchestrator -h` and
`sft -h` list no `-n`/`-s`; `uv run eval -h` does.
- `uv run rl --dry-run` on `configs/debug/algo/grpo.toml`,
`examples/basic/reverse-text/rl.toml` and
`configs/debug/multi-env/rl.toml`, and `uv run sft --dry-run` on
`examples/basic/reverse-text/sft.toml`: group eval limits (128, 64, 32)
resolve onto each source, a per-source `select.limit = 256` is kept, and
train sources default to all tasks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config renames and verifiers-driven
selection/shuffle/task-key semantics affect every train/eval run and
eval resume comparability across the upgrade, though runtime logic is
largely delegated to verifiers.
> 
> **Overview**
> Replaces **`num_examples`** and per-source **`shuffle`** with
verifiers' **`select`** block on every train/eval source (and
group-level `[select]` / `[orchestrator.eval.select]` /
`[eval.select]`). **`select.limit`** caps how many tasks run;
**`include`/`exclude`**, **`shuffle`**, **`skip`**, and **`seed`**
follow verifiers' ordering so prime-rl matches **`vf-eval`** for the
same selection.
> 
> The orchestrator now loads tasks with
**`vf.load_taskset(...).select(source.select)`** instead of client-side
shuffle (seed 42) and **`islice`**. Group config merging layers shared
**`select`** onto each source like **`env`**. **`uv run eval`** maps
**`-n`/`-s`** to **`select.limit`/`select.shuffle`**; eval resume no
longer validates config against the interrupted run—landed episodes are
matched by **`task.key`** to the new **`select`**.
> 
> All example/debug/CI TOMLs, docs, and skills are migrated.
**`verifiers`** minimum is raised to **`0.3.2.dev152`**. The dashboard
expects **`select.limit`** when estimating episode counts.
> 
> **Breaking:** rename configs from **`num_examples`** →
**`select.limit`**, **`shuffle`** → **`select.shuffle`**; default
shuffle seed and task keys may differ from pre-change runs
(resume/comparability implications).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f30798a0a6d20e3a474cb58a6dd48a8a85eb6ace. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:39:41 -07:00
NeoandGitHub cde3bcd546 Add new chunked loss impl based on torchtitan (#3673)
Port of torchtitan based chunked loss, which greatly imporves perf on
hopper for smaller models:

<html>
<head>

</head>
<body>
<html>
<head>

</head>
<body>

Model | Old chunked head | New chunked head | Gain
-- | -- | -- | --
Qwen3-30B-A3B, 8×H200, no AC, chunk 1024 | 6.71s | 6.20s | −7.6% step
time (+8.2% throughput)
Qwen3-235B-A22B, 4×8 H200, full AC, chunk 2048 | 14.09s | 14.00s | −0.6%
step time


</body>
</html>


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core LM-head autograd and SFT loss computation; RL/temperature
paths are mostly untouched but shared head code affects all training
modes using injected heads.
> 
> **Overview**
> Adds a **torchtitan-style chunked summed cross-entropy** path on the
fused LM head when `labels` are passed **without** `temperature`, so SFT
no longer fakes unit temperature and negates logprobs (or materializes
full logits on the vanilla path).
> 
> **`FusedOutputLinear`** now branches: no temperature →
`_ChunkedCrossEntropySumFn` returns scalar `loss` and folds
softmax-minus-one-hot grads into hidden/weight during forward (one token
chunk’s full-vocab logits at a time; backward only scales by the
upstream scalar). With temperature, behavior stays on the existing
logprob/entropy path.
> 
> **Vanilla and Gemma** heads mirror the same contract
(`cross_entropy_sum` or Gemma’s chunked logprob sum). SFT **`train.py`**
is unified to masked `IGNORE_INDEX` labels and `out["loss"]`. Config
docs now describe SFT fused-head behavior instead of claiming it is
disabled.
> 
> New unit tests check loss and gradients across fused/vanilla/Gemma
heads and chunk sizes, plus that temperature still uses logprobs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c4d2601e4cc55d6a921d80a33d19eb2e1407a230. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 00:33:18 +02:00
Xuan-Phi NguyenandGitHub f962e9c104 feat(rl): add PPO and CISPO loss options (#3697)
## Motivation

The trainer exposes IPO and IcePop but has no built-in PPO or CISPO loss
for controlled math-RL comparisons. PPO clips the token importance-ratio
surrogate; CISPO clips a **detached** importance weight multiplying the
current log probability, so an out-of-band ratio still has a policy
gradient. Both need to operate on the trainer's existing eligible-token
masks and optional per-token weights.

## Design

- Add `PPOLossConfig` / `PPOLoss` with a sign-aware clipped surrogate
(`ratio_low=.8`, `ratio_high=1.2` by default). A separate
`max_importance_ratio=1e4` bounds the otherwise unbounded side while
preserving its capped gradient; metrics report clipped and capped
fractions.
- Add `CISPOLossConfig` / `CISPOLoss`:
`-stop_gradient(clip(p_trainer/p_inference, low, high)) * advantage *
log p_trainer` on eligible tokens. The default lower bound `0` disables
lower clipping; the default upper bound is `5`. Metrics report the
clipped fraction.
- Register both as explicit `trainer.loss.type` choices. Existing loss
defaults and model precision fields are unchanged. #3696 is merged into
main and supplies the stable ratio arithmetic used by the new losses.

## Validation completed

- On the pre-restack head, the GPU loss and config suite had **213
passed**, covering PPO/CISPO values, advantage signs, clipping
gradients, masks, and config validation. Focused rerun after metric
cleanup: **4 passed**. Ruff check/format and SLURM dry run passed.
- At the current #3697 head, 192 config tests, a CPU PPO/CISPO
forward/backward smoke check, and Ruff check/format passed. Four focused
PPO/CISPO GPU tensor tests passed on GPU 7 of
`prime-nebius-puku-h200-gpu-059`, covering clipping, gradients, extreme
ratios, and masks. No full model test was run.
- One-node CISPO smoke job `1575` completed two optimizer updates with
finite loss, entropy, and mismatch KL; orchestrator reward was `0.3125`
then `0.4062` on 32 trainable traces per step, with no episode errors.
It was intentionally stopped after that validation: [W&B
run](https://wandb.ai/primeintellect/qwen30b-math/runs/0c0bb28ed7734551b600cbe52253d7f5).

## Ongoing experiment and private TOML provenance

CISPO job on math qwen3-30b-3a is pending validation. The long-run
reward and stability outcome remains pending.
2026-09-28 13:34:56 -07:00
eligottsandGitHub 771953ee01 Train from inline multimodal rollouts (#3320) 2026-09-28 12:59:05 -07:00
Xuan-Phi NguyenandGitHub e3dd67633d fix(rl): stabilize IPO, IcePop, and ref-KL loss masking (#3696)
## Motivation

Packed RL batches can contain masked tokens with invalid or extreme log
probabilities. IPO, IcePop, and ref-KL previously formed importance
ratios before removing those tokens, so a nominally excluded token could
still produce `0 * inf` or `0 * NaN`. Accepted rare actions could also
overflow `exp(log p_trainer - log p_inference)`, including in
mismatch-KL diagnostics.

## Design

- Select eligible tokens before ratio and KL arithmetic; IcePop and
ref-KL also select accepted tokens before exponentiating their policy
terms.
- Compute IPO's absolute probability-difference gate using `exp(max(log
p, log q)) * -expm1(min(log p, log q) - max(log p, log q))`, retaining
the same `eps` decision with better behavior for nearby small
probabilities.
- Add `IPOLossConfig.max_importance_ratio` (default `1e4`) and cap
accepted IPO/ref-KL forward weights while retaining the capped
policy-gradient coefficient. Bound squared-log-ratio terms and mismatch
diagnostics so they remain finite for extreme finite log ratios.
- Keep masked/unmasked diagnostics, namespace ref-KL metrics, and treat
the shared mismatch-KL helper as internal; leave model precision
settings unchanged.

## Validation completed

- GPU loss tests: **17 passed**, including extreme-ratio forward and
gradient cases. Expanded config suite: **205 passed**. Ruff check and
format passed.
- The stacked CISPO and IPOv2 two-update smoke runs both completed with
finite trainer metrics and no episode errors:
[CISPO](https://wandb.ai/primeintellect/qwen30b-math/runs/0c0bb28ed7734551b600cbe52253d7f5),
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/3ab7fbd7805d4ebca1d7ff2d1dc0cc84).
These validate this fix in downstream training paths; there was no
standalone PR1 training run.

## Ongoing experiments and config provenance

The 300-step CISPO and IPOv2 runs use this fix through stacked commits.
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/9045de5680a44a1d9a9f6bd84e9c30f2)
is running; the CISPO job is queued for an 8-GPU node. Long-run outcomes
are pending.

The actual run TOMLs at
`docs/study/examples/qwen3-30b-a3b/math16k_slurm.toml`,
`math_cispo.toml`, and `math_ipov2.toml` are **local and uncommitted**.
Relative to the checked-in [advanced math
example](https://github.com/PrimeIntellect-ai/prime-rl/blob/f87fd0eb3372cded4cf6cfb20e41189796354eae/examples/advanced/qwen3-30b-a3b/math.toml),
the shared local base uses one 8-H200 node (2 trainer, 6 inference GPUs)
instead of two trainer plus two inference nodes; 16,384 sequence tokens
and 15,000 completion tokens instead of 32,768 each; EP 2 + Ulysses CP 2
instead of EP 8; batch size 32, zero allowed off-policy steps, and 64
inflight episodes instead of batch size 512, eight off-policy steps, and
1,024 initial inflight episodes (group size 8 is shared); and vLLM TP 2
/ DP 3 instead of TP 8. It runs 300 steps without the example's AIME
eval source. The model, math taskset, AdamW learning rate (`1e-6`), and
W&B project are shared. The private overlays select CISPO
(`ratio_high=5`) or IPOv2 (`eps=.3`, `ratio_cap=5`, entropy floor `.15`)
and point SLURM at this worktree.
2026-09-28 12:24:58 -07:00
Mika SenghaasandGitHub 0a437ae340 fix: bump verifiers and prime-envs for timeouts (#3709)
## Summary

- Bump Verifiers to
[`c35ebd32`](https://github.com/PrimeIntellect-ai/verifiers/commit/c35ebd320126ee17f6a570a4f3fb8ef0fe0b0ae1).
This includes [the merged timeout
fix](https://github.com/PrimeIntellect-ai/verifiers/pull/2697): an unset
agent rollout timeout no longer falls back to four hours.
- Bump prime-envs to
[`565e8a74`](https://github.com/PrimeIntellect-ai/prime-envs/commit/565e8a74c001b25706d7c958f36d7bb0cd504ddc).
Its Lean helper now works with Verifiers' taskset API.

## Breaking

- An unset agent rollout timeout now inherits the task timeout, or has
no separate limit. Set a positive `env.<agent>.timeout.rollout` to
retain a stage limit.
- `env.<agent>.timeout.rollout = 0` is rejected. Remove the field to
request no separate stage limit.

## Verification

- `uv lock --check --offline` passed with the updated submodules.
- A focused UV smoke test confirmed that an unset agent timeout resolves
to no limit, a positive override resolves as given, and zero fails
validation.
- `git diff --check` passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Behavior change to rollout timeout defaults affects how long agent
stages can run; misconfigured envs may run longer or fail validation
until configs are updated.
> 
> **Overview**
> Updates **Verifiers** and **prime-envs** dependency pins to pick up
upstream fixes and API alignment.
> 
> The Verifiers bump fixes agent rollout timeout resolution: an
**unset** `env.<agent>.timeout.rollout` no longer silently defaults to
four hours—it now follows the task timeout or has no separate stage cap.
**`env.<agent>.timeout.rollout = 0` is now invalid**; omit the field
instead of using zero to mean “no separate limit.” Configs that relied
on the old default or zero need an explicit positive rollout timeout if
they still want a stage limit.
> 
> The **prime-envs** bump updates its Lean helper for Verifiers’ taskset
API.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
dead789c54f98ce0e57ab3fe47f9e819a9b802eb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-28 12:02:31 -07:00
9a55a0899c [ENG-6355] feat(docker): in-place PRIME_RL_REF source overlay for chart pods (#3686)
## Summary

Reworks the entrypoint's `PRIME_RL_REF` runtime source override so the
prime-rl-fft chart can run a branch on hosted FFT without building an
image for it. Inert unless `PRIME_RL_REF` is set; the default `docker
run` / chart path is unchanged.

The hook already existed (#2850) but was tuned for long-lived
containers: it cloned the full repo (~700 MB of `.git`) and `cp -a`'d
the 20 GB baked venv into a per-ref dir before syncing. As a per-pod
startup step that is unusable. Kubernetes `command:` also replaces the
image ENTRYPOINT, so the fft chart never ran this script at all; the
companion chart PR (PrimeIntellect-ai/fft#101) routes every prime-rl
container through it with a dispatcher-pinned sha.

## Changes

- **Shallow fetch by ref.** Fresh `git init` + `fetch --depth 1 origin
<ref>` + `checkout FETCH_HEAD`, then `submodule update --init
--recursive --depth 1` for the same four public submodules
`build_image.yaml` inits. GitHub serves branches, tags and full shas
alike; abbreviated shas are not fetchable and the comment says so. The
checkout is always fresh: a container is, and the fetch is seconds.
- **Sync into the baked venv instead of copying it.**
`UV_PROJECT_ENVIRONMENT=/app/.venv uv sync --inexact --locked ...` from
the checkout, with the same extras list as `Dockerfile.cuda`. uv
re-points the first-party editables at the checkout and reinstalls only
third-party pins that differ; flash-attn, deep-ep, mamba-ssm and friends
stay as baked. The chart's `uv run --no-sync <entrypoint>` commands
resolve the project from the new cwd.
- **Heavy-pin preflight.** Before syncing, compare the checkout's
`uv.lock` against `/app/uv.lock` for torch, torchvision, torchaudio,
triton, vllm, vllm-router, flash-attn, flash-attn-3, flashinfer-python,
tilelang, deep-ep, deep-gemm, mamba-ssm, nixl, prime-kernels and
quack-kernels. Any difference exits with a message to build an image
instead. The validator in fft runs the same check at dispatch
(PrimeIntellect-ai/fft#102); this is the backstop.
- **Pretend versions like the image build.** The shallow submodule
clones carry no tags, so hatch-vcs stamped verifiers/renderers
`0.0.1.dev1` and every `verifiers>=…` floor in the tree was unmet.
Resolve the same versions the Dockerfile does
(`docker-editable-pretend-versions.sh`), bake them into
`fallback-version` and drop the submodules' git metadata so the fallback
applies. (setuptools-scm's per-dist env vars turned out not to be
honored by hatch-vcs.)
- **Replay the image's prime CLI install, with its verifiers pin
overridden.** `Dockerfile.cuda` installs `prime>=0.7` after its lockfile
sync, which pulls prime-traces / prime-sandboxes / openai past the
lock's pins; the `--locked` sync here rolled them back and `prime env
install` could no longer import. The CLI also pins `verifiers==0.2.0`,
which replaces the editable with the PyPI wheel and breaks prime-rl's
own imports (see below). The replayed install passes `--overrides` with
a one-line file containing `verifiers`. **Workaround, marked
`FIXME(prime#940)` in the script:** remove the override once the prime
CLI drops verifiers as a dependency (PrimeIntellect-ai/prime#940),
together with the matching override in `Dockerfile.cuda` (#3705).
- **Git URL rewrite via `GIT_CONFIG_*` env** instead of `git config
--global`, so pods whose `HOME` is not writable by their uid still clone
the ssh-listed submodules.
- **`PRIME_RL_SOURCE_COMMIT`** is exported and logged so runs record
what actually ran.

## Found along the way: published images ship a broken verifiers

Since #3635 (2026-09-22) the Dockerfile's `uv pip install 'prime>=0.7'`
step replaces the submodule verifiers (0.3.x) with the PyPI
`verifiers==0.2.0` wheel that every prime release since 0.6.30 pins. On
the pristine image and on main-built `v0.9.1.dev128`, `uv run --no-sync
orchestrator --help` and `env-server --help` fail at import
(`verifiers.v1` has no `SingleAgentEnvConfig`; no
`set_base_sandbox_labels`). Runs that install a Hub env at pod start
survive by accident, because that install pulls verifiers 0.3.x back in;
baked-env runs like the nightly FFT configs do not, and nightly FFT has
failed daily since 9/24. The same override fixes the Dockerfile in
#3705.

## Verified on telus (namespace `minh-dev`, image built from this branch
at 478481593, later revisions of the script fetched into the same image)

Overlaying main tip `b94487324`, which adds `get_global_moe_stats` to
the trainer model module, a marker the baked source lacks:

| Check | Result |
|---|---|
| depth-1 fetch + four submodules | 9 s |
| container start → pod command, including the CLI install | ~35 s; ~60
s with a Hub env install |
| `prime_rl`, `verifiers`, `renderers` import from the checkout; marker
present in the overlay, absent in `/app/src` | pass, as root and as uid
1000 (`HOME` on an emptyDir, like the chart's env-servers) |
| vllm / torch / flash-attn versions and site-packages mtimes untouched
| pass |
| editables report `verifiers 0.3.2.dev137`, `renderers 0.1.12.dev2` |
pass |
| `prime --version`, `prime env install --help`, `uv run --no-sync prime
env install primeintellect/wordle` | pass; the install swaps the baked
`wordle` for the Hub's and leaves verifiers alone |
| `uv run --no-sync orchestrator --help`, `env-server --help` | pass
(they fail on the pristine image, see above) |
| `uv pip check` | 7 incompatibilities, down from the image's 107: six
are the image's own lockfile inconsistencies (mamba-ssm/tilelang,
torch/cudnn, vllm/transformers, openai-agents/openai and
python-multipart, flash-attn-4/tvm), the seventh is the intentional
`prime requires verifiers==0.2.0` |
| ref whose lock pins vllm 0.28.0 vs the image's 0.29.0 | refused in 9
s, before any sync, naming `flashinfer-python, vllm` |
| a `PRIME_CLI_SPEC` knob tried in one revision | removed: a
caller-supplied env var must not choose what gets installed into a
hosted pod |

Not exercised: a GPU workload through the overlay (the pods were
CPU-only), and the chart path end to end (needs fft#101 deployed).

## Related

- fft: chart `source` values (PrimeIntellect-ai/fft#101) and validator
`source.ref` resolution with the same lockfile preflight
(PrimeIntellect-ai/fft#102).
- platform `sourceRef` on the dedicated run dispatch and `prime train
--ref` / `--pr` follow.
- Dockerfile fix for the verifiers clobbering: #3705.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how chart/FFT pods bootstrap Python when `PRIME_RL_REF` is set
by mutating `/app/.venv` at startup; mis-synced lockfiles or override
logic could break training entrypoints, though heavy-pin preflight and
the default no-ref path limit blast radius.
> 
> **Overview**
> When **`PRIME_RL_REF`** is set, the Docker entrypoint no longer does a
full repo clone and a 20 GB venv copy into `/tmp`. It
**shallow-fetches** the ref (depth‑1 + four submodules), exports
**`PRIME_RL_SOURCE_COMMIT`**, and **`uv sync`s the checkout into the
baked `/app/.venv`** so editables point at the overlay while heavy GPU
wheels stay untouched.
> 
> Startup adds **guardrails and parity with the image build**: compare
checkout vs image **`uv.lock`** for torch/vllm/flash-attn-style packages
and **exit early** if they drift; apply
**`docker-editable-pretend-versions.sh`** so shallow submodules satisfy
`verifiers`/`renderers` floors; **reinstall `prime>=0.7`** with a
**`verifiers` pip override** so the CLI does not clobber editables.
GitHub SSH URLs are rewritten via **`GIT_CONFIG_*`** (writable without a
global git config), and the process **`cd`s into the checkout** instead
of swapping **`VIRTUAL_ENV`** to a per-ref venv.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b2fddf150dcaadfbe66cc7945ac34dac649d2fc6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 10:29:40 -07:00
Andrew KirillovandGitHub 666297d09c Require prime-sandboxes>=0.3.2 (#3682)
Raises the pyproject floor to `prime-sandboxes>=0.3.2` and refreshes the
lock accordingly (resolves 0.3.2, wheel/sdist hashes cross-checked
against PyPI).

## Why

The hosted-eval stress runner bootstraps this repo with `uv sync
--no-dev --frozen`, so the 429-retry fixes in prime-sandboxes 0.3.2
(status-aware backoff on platform API and gateway retries) only reach
eval rollouts through this lock. 0.3.0 satisfied the old `>=0.3.0` floor
indefinitely - `lock-check` enforces consistency, not freshness - so the
behavioral fix could not arrive without either this bump or a new
automation mechanism.

The floor raise (rather than a lock-only refresh) encodes the actual
requirement: the runtime depends on the 429-retry semantics, and any
future lock regeneration can no longer backslide below 0.3.2. Precedent
for this shape: #3571 (`chore: require prime-runs 0.1.3`).

## What changed

- `pyproject.toml`: `prime-sandboxes>=0.3.0` -> `>=0.3.2`
- `uv.lock`: the matching specifier line; the prime-sandboxes resolution
entries already point at 0.3.2

## Validation

- `uv lock --check` passes (581 packages)
- `uv sync --no-dev --frozen` resolves prime-sandboxes 0.3.2
- `uv run pytest tests/unit/eval -v`: 9 passed
- Regenerated with uv 0.12.19 (older uv reorders unrelated lock tables)

Linear: ENG-5966 (eval-based stress testing).
2026-09-28 09:08:05 -07:00
Scott CabrinhaandGitHub 202f108f33 fix(docker): build NIXL from source by default; isolate the prime CLI install (#3667)
## What

- **NIXL from source (default on).** `Dockerfile.cuda` builds NIXL
0.10.1 against the baked `/opt/ucx` (UCX 1.19.1) by default. The wheel
is renamed to `nixl-cu13` before building, and the build asserts the UCX
plugin links `/opt/ucx/lib/libucp.so`.
`scripts/install_nixl_from_source.sh` gets the same rename for the SLURM
path.
- **prime CLI as an isolated uv tool.** It's installed into
`/app/.tools` instead of `uv pip install`-ing it into `/app/.venv`, with
the executable linked into `/app/.venv/bin`. The build asserts the
workspace `verifiers` is still the one installed.

## Why

**NIXL.** The PyPI `nixl-cu13` wheel bundles its own UCX, which
segfaults on the prefill→decode KV transfer (#2883). The existing
`INCLUDE_NIXL_FROM_SOURCE` option was:
1. **Off by default, never enabled in CI.** Every published image ships
the PyPI wheel. On SLURM, research works around this with a
`pre_run_command` reinstall after each `uv sync`.
2. **Broken when enabled.** NIXL 0.10.1's pyproject names the package
`nixl-cu12`, so the `nixl_cu13-*.whl` glob matched nothing.
3. **A no-op even when installed.** The `nixl` shim imports `nixl_cu13`
before `nixl_cu12`, so the source build sat unused. Upstream's
`contrib/build-wheel.sh` renames via `contrib/tomlutil.py --wheel-name
nixl-cu<major>`, and this PR does the same.

The plugin has `RUNPATH=/opt/ucx/lib`, so it doesn't depend on
`LD_LIBRARY_PATH`.

**prime CLI (regression from #3635).** Every `prime` 0.7.x on PyPI pins
`verifiers==0.2.0`. Running `uv pip install 'prime>=0.7'` into the app
venv resolves against it and replaces:
- workspace `verifiers` (0.3.2.dev) → 0.2.0
- `openai` 2.54 → 3.15
- workspace `prime-pydantic-config` → the PyPI one
- `prime-sandboxes` / `prime-traces` → newer versions

As a result, `prime_rl.configs.orchestrator` fails to import (`module
'verifiers.v1' has no attribute 'SingleAgentEnvConfig'`), and every
component crashes at startup. This affects every image built since
#3635.

## Test plan

- [x] Image `commit-0039ddc20-amd64` (NIXL fix only): the build passed,
and inference pods on telus confirmed the UCX plugin links `/opt/ucx`
1.19.1. The run then crashed on the `verifiers` downgrade above.
- [x] On `commit-a1822f7a0-amd64` (pre-#3635): `uv tool install
'prime>=0.7'` gives a working CLI 0.7.5, and `uv run --no-sync prime env
install primeintellect/reverse-text` installs into `/app/.venv`.
`verifiers` still has `SingleAgentEnvConfig`, and `openai` stays at
2.54.0.
- [x] Earlier, a GLM-5.3 10-node P/D run on FFT/telus with the same NIXL
build (installed in-pod): a chat request through the PD router
succeeded, with 1 NIXL KV transfer of 5.65 MB / 18.8 ms and no segfault
(ENG-6348).
- [x] Image `commit-cef7100c7-amd64` (both fixes, newest main): build
passed, including the new workspace-verifiers assertion. The GLM-5.3
10-node P/D run on telus used it with no in-pod bootstrap: the NIXL UCX
plugin links `/opt/ucx` 1.19.1, all components import cleanly, the
PD-router chat request returned correctly, and NIXL KV transfers
succeeded. Prefill also needed `VLLM_USE_BREAKABLE_CUDAGRAPH=0` on vLLM
0.29; that is separate, in #3669.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Scott Cabrinha <scott.cabrinha@primeintellect.ai>
2026-09-27 19:35:41 -07:00
72 changed files with 1446 additions and 610 deletions
+13 -10
View File
@@ -153,22 +153,25 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& rm /tmp/prime-cli-overrides.txt \
&& /app/.venv/bin/python -c 'import pathlib, verifiers; assert pathlib.Path(verifiers.__file__).is_relative_to("/app/deps/verifiers"), verifiers.__file__'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
# the disaggregated P/D path — default off so training-only / single-node
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
ARG INCLUDE_NIXL_FROM_SOURCE=0
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
# rebuilding against our UCX is the documented fix. The rename is required: an
# unrenamed source build is `nixl_cu12`, and the `nixl` shim imports nixl_cu13
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
ARG INCLUDE_NIXL_FROM_SOURCE=1
ARG NIXL_VERSION=0.10.1
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
VIRTUAL_ENV=/app/.venv uv pip install pip \
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
&& cd /tmp/nixl \
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
&& ldd /app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so \
&& rm -rf /tmp/nixl /tmp/nixl-whl; \
fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
+3 -1
View File
@@ -22,7 +22,9 @@ lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.select]
limit = 32
[eval.sampling]
max_completion_tokens = 1024
+3 -1
View File
@@ -1,8 +1,10 @@
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
# Prime Inference — the eval path end to end without a GPU or sandbox.
num_examples = 4
dashboard = false
[select]
limit = 4
[sampling]
max_completion_tokens = 8192
@@ -48,7 +48,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
@@ -54,7 +54,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -29,7 +29,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -29,7 +29,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -48,7 +48,9 @@ algo.teacher.base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -41,7 +41,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -41,7 +41,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -31,7 +31,9 @@ env.player1.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
+3 -1
View File
@@ -37,7 +37,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -46,7 +46,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+3 -1
View File
@@ -46,7 +46,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -117,7 +117,7 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
select.limit = 100
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
+2 -1
View File
@@ -5,7 +5,8 @@
#
# uv run eval @ configs/debug/eval/multi-env.toml
num_examples = 16
[select]
limit = 16
[[source]]
name = "tb2-bash"
+2 -1
View File
@@ -4,7 +4,8 @@
#
# uv run eval @ configs/debug/eval/multi-turn.toml
num_examples = 16
[select]
limit = 16
[[source]]
env.taskset.id = "terminal-bench-2"
+3 -1
View File
@@ -7,9 +7,11 @@
# <Ctrl-C partway>
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
num_examples = 8
group_size = 2
[select]
limit = 8
[concurrency]
min_inflight = 2
max_inflight = 2
+3 -1
View File
@@ -3,9 +3,11 @@
#
# uv run eval @ configs/debug/eval/single-turn.toml
num_examples = 8
group_size = 2
[select]
limit = 8
[sampling]
max_completion_tokens = 8192
+3 -1
View File
@@ -31,7 +31,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
num_examples = 64
[orchestrator.eval.select]
limit = 64
[orchestrator.eval.sampling]
max_completion_tokens = 128
+1 -1
+7
View File
@@ -180,6 +180,13 @@ retries.include = ["ProviderError", "SandboxError"]
timeout.episode = 7200
```
Each source also takes a `select` block that picks which tasks of its taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit`, in that order. A group's `select` block works like its `env` block: every source inherits it field by field, and a source's own fields win. A source's `include` or `exclude` replaces the group's whole block. To evaluate 128 tasks of each taskset:
```toml
[orchestrator.eval.select]
limit = 128
```
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
+10 -5
View File
@@ -32,19 +32,21 @@ uv run inference --vllm.model Qwen/Qwen3-4B
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
```
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-s`/`-r` set `select.limit`/`select.shuffle`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
## Configuration
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `num_examples`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `[select]`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
```toml
model = "Qwen/Qwen3-4B"
num_examples = 32
group_size = 4
[select] # every source inherits these
limit = 32
[client]
base_url = "http://localhost:8000/v1"
@@ -67,9 +69,12 @@ env.agent.harness.id = "bash"
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
select.include.idx = ["0:30"]
```
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Per-source `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
@@ -85,7 +90,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `num_examples` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The model, the sampling and each source's env must match the config the landed episodes were measured with (kept beside them in `monitors/file/eval.json`); a resume that changes them stops with the differing config paths. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
## Monitors
+4 -2
View File
@@ -184,12 +184,14 @@ Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manag
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `select` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
```toml
[eval]
interval = 25
num_examples = 32
[eval.select]
limit = 32
[[eval.source]]
name = "reverse-text"
+1 -1
View File
@@ -148,7 +148,7 @@ interval = 20
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
select.limit = 500 # full set is 1266; cap eval at 500
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/alphabet-sort/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/reverse-text/eval.toml
model = "Qwen/Qwen3-0.6B"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+1 -1
View File
@@ -29,7 +29,7 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text-eval"
num_examples = 256
select.limit = 256
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+3 -1
View File
@@ -15,7 +15,9 @@ lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.select]
limit = 32
[eval.sampling]
max_completion_tokens = 1024
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/wiki-search/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/wordle/eval.toml
model = "Qwen/Qwen3-1.7B"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.2.dev143",
"verifiers>=0.3.2.dev152",
]
[build-system]
@@ -1,6 +1,7 @@
import uuid
from pathlib import Path
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
@@ -57,14 +58,15 @@ class EvalConfig(ServedEvalConfig):
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
"""Client of the inference server. Defaults to Prime Inference."""
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
"""Task selection that every source inherits (``-n`` sets ``limit``, ``-s`` sets
``shuffle``). Each field a source sets on its own ``select`` wins over this one."""
concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128)
"""In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM
``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to
let the band adapt to KV usage like the orchestrator's."""
num_examples: int = Field(-1, validation_alias=AliasChoices("num_examples", "n"))
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r"))
"""Default rollouts per example. Can be overridden per env."""
@@ -87,9 +89,7 @@ class EvalConfig(ServedEvalConfig):
resume: bool = False
"""Continue the interrupted run named by ``run.name`` from its trace stream: the
landed episodes rejoin the epoch and only the rollouts still owed run. The model,
sampling and env config must match the interrupted run; ``num_examples`` and
``group_size`` may change."""
landed episodes rejoin the epoch and only the rollouts still owed run."""
log: LogConfig = LogConfig()
@@ -166,8 +166,8 @@ class EnvConfig(BaseConfig):
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
shuffle: bool = False
"""Shuffle the source's finite taskset once with a fixed seed. The shuffled order is fixed for the whole run; infinite tasksets cannot be shuffled."""
select: vf.SelectConfig = vf.SelectConfig()
"""Which of the taskset's tasks this source uses: ``include``/``exclude`` by ``idx``, ``ids``, ``keys`` or ``names``, then ``shuffle``, ``skip`` and ``limit``, applied in that order."""
@model_validator(mode="before")
@classmethod
@@ -194,22 +194,51 @@ class EnvConfig(BaseConfig):
return self
def merge_group_env(data: Any) -> Any:
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` block
under the ``env`` block of each raw source."""
if not isinstance(data, dict) or data.get("env") is None:
def merge_group_defaults(data: Any) -> Any:
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` and
``select`` blocks under those of each raw source. A source's own values win; a
source's ``include`` or ``exclude`` replaces the group's whole block."""
if not isinstance(data, dict):
return data
try:
shared = vf.SharedEnvConfig.model_validate(data["env"])
except ValidationError:
return data # the ``env`` field reports the errors once, not once per source
data["source"] = [
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))} if isinstance(source, dict) else source
for source in data.get("source") or []
]
sources = data.get("source") or []
if data.get("env") is not None:
try:
shared = vf.SharedEnvConfig.model_validate(data["env"])
except ValidationError:
shared = None # the ``env`` field reports the errors once, not once per source
if shared is not None:
sources = [
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))}
if isinstance(source, dict)
else source
for source in sources
]
if data.get("select") is not None:
group = select_fields(data["select"], vf.SelectCLIConfig)
if group is not None:
sources = [
{**source, "select": group | own}
if isinstance(source, dict)
and (own := select_fields(source.get("select"), vf.SelectConfig)) is not None
else source
for source in sources
]
if sources:
data["source"] = sources
return data
def select_fields(raw: Any, select_type: type[vf.SelectConfig]) -> dict | None:
"""The fields a raw ``select`` block sets, under their canonical names; None when
the block is invalid, which leaves it to report its own errors."""
if raw is None:
return {}
try:
return select_type.model_validate(raw).model_dump(exclude_unset=True)
except ValidationError:
return None
class StandardSamplerConfig(BaseConfig):
type: Literal["standard"] = "standard"
@@ -306,9 +335,6 @@ class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
num_examples: int = -1
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
group_size: int = Field(1, ge=1)
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
@@ -331,10 +357,14 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
select: vf.SelectConfig = vf.SelectConfig()
"""Task selection that every training source inherits. Each field a source sets on
its own ``select`` wins over this one."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
def resolve_group_defaults(cls, data):
return merge_group_defaults(data)
@model_validator(mode="after")
def resolve_env_defaults(self):
@@ -373,21 +403,23 @@ class EvalSourcesConfig(BaseConfig):
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
num_examples: int = -1
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
select: vf.SelectConfig = vf.SelectConfig()
"""Task selection that every eval source inherits, e.g. ``limit = 128`` to evaluate
128 tasks of each taskset. Each field a source sets on its own ``select`` wins over
this one."""
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
def resolve_group_defaults(cls, data):
return merge_group_defaults(data)
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
group_size (the worker ``pool`` is configured per env, default elastic)."""
"""Resolve per-env overrides: inherit group-level sampling and group_size (the
worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for source in self.source:
if "sampling" not in source.model_fields_set:
@@ -395,8 +427,6 @@ class EvalSourcesConfig(BaseConfig):
else:
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
return self
@@ -345,7 +345,7 @@ class ModelConfig(BaseModelConfig):
"""Debugging knobs for the model and distributed training."""
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
@@ -574,6 +574,9 @@ class IPOLossConfig(BaseConfig):
eps: float = Field(0.3, ge=0)
"""Maximum absolute probability change before a token is masked."""
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
"""Cap the importance weight of accepted tokens while preserving its policy gradient."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
@@ -600,6 +603,41 @@ class IcePopLossConfig(BaseConfig):
return self
class PPOLossConfig(BaseConfig):
type: Literal["ppo"] = "ppo"
ratio_low: float = Field(0.8, gt=0, le=1, allow_inf_nan=False)
"""Lower ratio bound for the clipped surrogate."""
ratio_high: float = Field(1.2, ge=1, allow_inf_nan=False)
"""Upper ratio bound for the clipped surrogate."""
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
"""Cap the unbounded side of the surrogate while preserving its gradient."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
@model_validator(mode="after")
def validate_max_importance_ratio(self):
if self.max_importance_ratio < self.ratio_high:
raise ValueError("max_importance_ratio must be at least ratio_high")
return self
class CISPOLossConfig(BaseConfig):
type: Literal["cispo"] = "cispo"
ratio_low: float = Field(0.0, ge=0, le=1, allow_inf_nan=False)
"""Lower bound for the detached importance weight; zero disables lower clipping."""
ratio_high: float = Field(5.0, ge=1, allow_inf_nan=False)
"""Upper bound for the detached importance weight."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
class CustomLossConfig(BaseConfig):
type: Literal["custom"] = "custom"
@@ -610,7 +648,9 @@ class CustomLossConfig(BaseConfig):
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[
IPOLossConfig | IcePopLossConfig | PPOLossConfig | CISPOLossConfig | CustomLossConfig, Field(discriminator="type")
]
class FakeDataLoaderConfig(BaseConfig):
+2 -2
View File
@@ -16,7 +16,7 @@ dependencies = [
"transformers==5.6.2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime-sandboxes>=0.3.0",
"prime-sandboxes>=0.3.2",
"prime-runs[train]>=0.1.3",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
@@ -29,7 +29,7 @@ dependencies = [
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.2.dev143",
"verifiers[harbor]>=0.3.2.dev152",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
+119 -45
View File
@@ -5,67 +5,141 @@ set -e
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the prime-rl source itself.
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
# PRIME_RL_REF can be a git tag, branch, or full commit hash. PRIME_RL_REPO
# optionally points at a fork; defaults to the upstream repo.
#
# We clone into a per-ref dir under /tmp, seed the venv from the baked
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
# `uv sync --inexact` re-installs prime_rl from the override source.
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
# resolves the entrypoints from the override venv.
# The ref is fetched shallowly under /tmp and synced INTO the baked
# /app/.venv: uv re-points the first-party editables (prime_rl, verifiers,
# renderers, ...) at the checkout and reinstalls only third-party pins
# that differ from the image's lockfile, so the heavy prebuilt wheels
# (flash-attn, deep-ep, mamba-ssm, ...) are never rebuilt. A container
# starts from a fresh filesystem, so mutating /app/.venv in place is safe.
# The pods of the prime-rl-fft chart run this with a sha pinned by the
# dispatcher; the exported PRIME_RL_SOURCE_COMMIT records what ran.
if [ -n "$PRIME_RL_REF" ]; then
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
# Slug + content hash for the cache dir name. Slug keeps the path
# Slug + content hash for the checkout dir name. Slug keeps the path
# human-readable; the hash (over repo + ref) prevents collisions
# between distinct refs that slugify the same way (e.g. `feat/foo`
# vs `feat-foo`) and between the same ref on different forks.
REF_SLUG="${PRIME_RL_REF//\//-}"
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
# Rewrite ssh://git@github.com URLs to https so submodules listed
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
# can be cloned from the pod without ssh keys.
git config --global url."https://github.com/".insteadOf "git@github.com:"
if [ ! -d "$DEST/.git" ]; then
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
rm -rf "$DEST"
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
# Rewrite git@github.com URLs to https so submodules listed with SSH
# URLs (deps/verifiers, deps/renderers, deps/prime-envs) clone from the
# pod without ssh keys. Via GIT_CONFIG_* rather than `git config
# --global`: the pod's HOME may not be writable by its uid.
export GIT_CONFIG_COUNT=1
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
export GIT_CONFIG_VALUE_0="git@github.com:"
rm -rf "$DEST"
git init --quiet "$DEST"
git -C "$DEST" remote add origin "$PRIME_RL_REPO"
# Depth-1 fetch of the ref itself: GitHub serves branches, tags and
# full commit shas alike (abbreviated shas are not fetchable), and
# prime-rl's history (~700 MB of .git) is not needed to run it.
echo "[prime-rl] fetching ${PRIME_RL_REF} from ${PRIME_RL_REPO}"
git -C "$DEST" fetch --quiet --depth 1 origin "$PRIME_RL_REF"
git -C "$DEST" checkout --quiet --force --detach FETCH_HEAD
# Same public submodules the image build inits (build_image.yaml);
# a pinned commit that isn't the submodule's branch tip is fetched by
# sha, which GitHub allows.
git -C "$DEST" submodule sync --quiet --recursive
git -C "$DEST" submodule update --quiet --init --recursive --depth 1 -- \
deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
PRIME_RL_SOURCE_COMMIT=$(git -C "$DEST" rev-parse HEAD)
export PRIME_RL_SOURCE_COMMIT
echo "[prime-rl] source overlay at ${PRIME_RL_SOURCE_COMMIT}"
# Give the verifiers/renderers editables the same versions the image
# build does (Dockerfile.cuda): resolve them with the repo's script
# (git describe, else the highest `>=` floor any pyproject declares),
# then bake them into hatch-vcs's fallback-version and drop the
# submodules' git metadata so the fallback is what gets used. The
# shallow clones carry no tags, so hatch-vcs would otherwise stamp
# them 0.0.1.dev1 and every `verifiers>=…` floor in the tree would be
# unmet, letting the CLI install below swap the editable for a wheel.
if [ -f "$DEST/scripts/docker-editable-pretend-versions.sh" ]; then
eval "$(bash "$DEST/scripts/docker-editable-pretend-versions.sh" --shell "$DEST")"
rm -f "$DEST/deps/verifiers/.git" "$DEST/deps/renderers/.git"
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" "$DEST/deps/verifiers/pyproject.toml"
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" "$DEST/deps/renderers/pyproject.toml"
fi
# Always fetch + checkout so mutable refs (branches/tags) pick up new
# commits between pod restarts. No-op for immutable SHAs.
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
git -C "$DEST" fetch --quiet --tags --force origin
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
# Refresh submodules to whatever the parent commit pins. `sync`
# picks up URL changes in .gitmodules between checkouts on cache
# hit; `update --init --recursive` applies the pinned SHAs.
git -C "$DEST" submodule sync --recursive
git -C "$DEST" submodule update --init --recursive
if [ ! -d "$DEST/.venv" ]; then
# Seed from the baked venv so the heavy wheels (flash-attn,
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
# hardlinks): a subsequent `uv sync` writes into this tree, and
# hardlinks would leak those writes back into /app/.venv when
# /tmp and /app share a filesystem.
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
# lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
# Wheels the in-place sync cannot rebuild: a lockfile that pins any of
# these differently from the image needs a real image build. Fail here
# rather than minutes later inside a half-installed torch. Stdlib only;
# --project /app pins the interpreter to the baked venv whatever the cwd.
uv run --no-sync --project /app python - "$DEST/uv.lock" /app/uv.lock <<'HEAVY_PINS_PY'
import sys
import tomllib
HEAVY = {
"torch", "torchvision", "torchaudio", "triton", "vllm", "vllm-router",
"flash-attn", "flash-attn-3", "flashinfer-python", "tilelang",
"deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels",
}
def pins(path):
with open(path, "rb") as f:
lock = tomllib.load(f)
out = {}
for pkg in lock.get("package", []):
if pkg.get("name") in HEAVY:
source = repr(sorted((pkg.get("source") or {}).items()))
out.setdefault(pkg["name"], set()).add((pkg.get("version"), source))
return out
ref_pins, image_pins = pins(sys.argv[1]), pins(sys.argv[2])
drift = sorted(name for name in HEAVY if ref_pins.get(name) != image_pins.get(name))
if drift:
print(
f"[prime-rl] {sys.argv[1]} pins {', '.join(drift)} differently from the image; "
"the runtime source overlay cannot rebuild these. Build an image for this ref "
"(build_image.yaml) or run it on an image whose lockfile matches.",
file=sys.stderr,
)
sys.exit(1)
HEAVY_PINS_PY
# Sync the checkout into the baked venv. Same extras as Dockerfile.cuda
# so an unchanged lockfile is a no-op for third-party packages (keep
# the two lists in sync). --inexact leaves packages the checkout
# doesn't declare in place instead of uninstalling them.
export UV_PROJECT_ENVIRONMENT=/app/.venv
export VIRTUAL_ENV=/app/.venv
echo "[prime-rl] syncing ${DEST} into /app/.venv"
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
--extra flash-attn-cute --extra disagg --extra quack --extra kernels \
--group mamba-ssm )
# Replay the image's post-sync step (Dockerfile.cuda; keep the two in
# sync): the prime CLI pulls prime-traces / prime-sandboxes / openai
# past the lock's pins, and the --locked sync above just rolled them
# back, which leaves `prime env install` unable to import.
#
# FIXME(prime#940): workaround, remove once the prime CLI drops
# verifiers as a dependency
# (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI pins
# verifiers==0.2.0, which would swap the editable for the PyPI wheel
# and break prime-rl's imports; the --overrides file ignores that one
# requirement. When removing it, drop the overrides file and the
# --overrides flag here and in Dockerfile.cuda.
echo "[prime-rl] installing the prime CLI"
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt
uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7'
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
# project from the cwd; the venv itself stays /app/.venv via
# UV_PROJECT_ENVIRONMENT above.
cd "$DEST"
fi
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
# PRIME_RL_REF swap so when both are set the install lands in the override
# venv (uv pip install targets $VIRTUAL_ENV when exported).
# PRIME_RL_REF overlay so when both are set verifiers is installed last
# (uv pip install targets $VIRTUAL_ENV, which is /app/.venv either way).
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
+5 -1
View File
@@ -82,6 +82,10 @@ else
fi
cd "$NIXL_SRC"
git checkout "$NIXL_VERSION"
# Name the wheel nixl-cu13 (pyproject says nixl-cu12): the `nixl` shim imports
# nixl_cu13 first, so a nixl_cu12 build would sit unused next to the PyPI wheel.
git checkout -- pyproject.toml
uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml
export PKG_CONFIG_PATH="$UCX_INSTALL/lib/pkgconfig"
export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}"
@@ -92,5 +96,5 @@ mkdir -p "$WHEEL_DIR"
uv pip install pip 2>/dev/null
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
WHEEL=$(ls "$WHEEL_DIR"/nixl*.whl | head -1)
WHEEL=$(ls "$WHEEL_DIR"/nixl_cu13-"$NIXL_VERSION"-*.whl | head -1)
echo "=== NIXL wheel built at: $WHEEL ==="
+1 -1
View File
@@ -65,7 +65,7 @@ env.agent.runtime.type = "subprocess"
Source lists are set in TOML. The CLI has no list-index paths (`--orchestrator.eval.source.0.env.taskset.id` does not parse); a whole list can be passed as JSON (`--orchestrator.eval.source '[{"env": {"taskset": {"id": "reverse-text"}}}]'`), which replaces the list wholesale.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `num_examples`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -r N -c N -m MODEL` (see the `eval` skill).
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `[select]`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -s -r N -c N -m MODEL` (see the `eval` skill).
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
+38 -4
View File
@@ -23,18 +23,20 @@ uv run eval @ eval.toml --monitors.prime # stream eac
- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/eval.py`); `uv run eval -h` lists the fields.
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `num_examples`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `select.limit`, `-s` `select.shuffle`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `num_examples`, `group_size`, `sampling` override the top level):
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `select`, `group_size`, `sampling` override the top level):
```toml
model = "Qwen/Qwen3-4B"
num_examples = 32
group_size = 4
[select]
limit = 32
[client]
base_url = "http://localhost:8000/v1"
@@ -48,6 +50,38 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
## Select tasks
`select` picks which tasks of a source's taskset run. The steps apply in a fixed order: `include` and `exclude` (by `idx` position, `ids`, `keys` or `names`), then `shuffle` (under `seed`, default 0), `skip`, `limit`. Set it once for every source of a group (`[select]` in an eval TOML, `[orchestrator.eval.select]`, `[orchestrator.train.select]`), or per source (`select.limit = 50` in a `[[source]]`); a source's own fields win.
```bash
uv run eval gsm8k -n 50 # the first 50 tasks
uv run eval gsm8k -n 50 -s # a random subset of 50 (same tasks every run)
uv run eval gsm8k -n 50 -s --select.seed 1 # another random subset
uv run eval gsm8k --select.include.idx 0:10,42 # tasks by position (ints and Python slices)
uv run eval terminal-bench-2 --select.include.names '["fix-git"]' # tasks by name; `ids` and `keys` work the same
uv run eval terminal-bench-2 --select.exclude.keys '["<task.key>"]' # drop known-broken tasks (keys are on every trace)
```
Disjoint train/test splits from one taskset:
```toml
# contiguous: eval on the first 100 tasks, train on the rest
[[orchestrator.eval.source]]
env.taskset.id = "gsm8k"
select.include.idx = [":100"]
[[orchestrator.train.source]]
env.taskset.id = "gsm8k"
select.exclude.idx = [":100"]
# random: the same shuffle on both sides; eval takes 100, train skips them
# eval: select.shuffle = true, select.limit = 100
# train: select.shuffle = true, select.skip = 100
```
The shuffle comes before `skip` and `limit`, so a larger `limit` extends the same selection: resuming a `-n 50 -s` run with `-n 100` keeps the 50 landed tasks and adds 50 more.
## Monitor an eval
Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t outputs | head -1` finds the latest). The console stays quiet while the eval runs; everything is in the files and the dashboard (`dashboard` skill).
@@ -72,4 +106,4 @@ The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · runn
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed (`num_examples`/`group_size` may change, the model, sampling and env config may not). Env servers are children of the eval process and exit with it.
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env servers are children of the eval process and exit with it.
+8 -7
View File
@@ -272,13 +272,14 @@ def eval_env(config: dict) -> str | None:
def source_total_episodes(source: dict) -> int | None:
"""What one ``[[source]]`` will produce, from its config alone: ``num_examples = -1``
means the whole taskset, unknown up front unless the source names its tasks."""
tasks = ((source.get("env") or {}).get("taskset") or {}).get("tasks")
count = source.get("num_examples") or -1
if count < 0 and not tasks:
"""What one ``[[source]]`` will produce, from its config alone: without a
``select.limit`` the count is unknown up front unless the source names its tasks."""
taskset = (source.get("env") or {}).get("taskset") or {}
limit = (source.get("select") or {}).get("limit")
tasks = taskset.get("tasks")
if limit is None and not tasks:
return None
return (count if count >= 0 else len(tasks)) * (source.get("group_size") or 1)
return (limit if limit is not None else len(tasks)) * (source.get("group_size") or 1)
def eval_totals(config: dict) -> dict[str, int | None]:
@@ -294,7 +295,7 @@ def eval_total_episodes(config: dict) -> int | None:
if sources:
totals = [source_total_episodes(s) for s in sources]
return None if any(t is None for t in totals) else sum(totals) or None
return (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None
return ((config.get("select") or {}).get("limit") or 0) * (config.get("num_rollouts") or 0) or None
def run_meta(run_dir: Path) -> dict:
+1 -1
View File
@@ -21,7 +21,7 @@ from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes, set_proc_title
USAGE = """\
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c N] [-m MODEL] [options]
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-s] [-r N] [-c N] [-m MODEL] [options]
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
+80 -24
View File
@@ -2,21 +2,27 @@
vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
defaulting and ``usage`` reporting. We subclass it for the one bit still
missing from the upstream handler: compact ``routed_experts`` export — when the
engine emits routing decisions, surface them as ``{data, shape, start, dtype}``
base64 raw-byte objects (the form the PD router can merge and the renderers
parse) instead of upstream's single ``.npy`` base64 string.
prefix-cache salting, lora dispatch, multimodal content parts and features,
prompt logprobs, priority, ``data_parallel_rank`` header routing, server-side
``max_tokens`` defaulting and ``usage`` reporting. We subclass it for the bits
still missing from the upstream handler:
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. Prompt metadata — return the effective engine prompt and authoritative
multimodal placeholder ranges after expansion. Drop this once upstream's
response includes these fields.
Everything else delegates to upstream so we track future vLLM changes for free.
"""
from __future__ import annotations
from collections.abc import AsyncGenerator
from collections.abc import AsyncGenerator, AsyncIterable
from contextvars import ContextVar
from typing import Any
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
@@ -24,6 +30,7 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
PlaceholderRangeInfo,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
@@ -33,14 +40,34 @@ from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
# Overrides upstream's base64 ``.npy`` string form with the compact
# ``{data, shape, start, dtype}`` object the PD router merges and the
# renderers parse.
# Overrides upstream's base64 ``.npy`` string form with the compact object
# the PD router merges and the renderers parse.
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
prompt_token_ids: list[int] | None = None
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
_response_mm_placeholders: ContextVar[dict[str, list[PlaceholderRangeInfo]] | None] = ContextVar(
"response_mm_placeholders", default=None
)
def _extract_mm_placeholders(
engine_input: Any,
) -> dict[str, list[PlaceholderRangeInfo]] | None:
if not isinstance(engine_input, dict) or engine_input.get("type") != "multimodal":
return None
return {
modality: [
PlaceholderRangeInfo(offset=placeholder.offset, length=placeholder.length)
for placeholder in sorted(ranges, key=lambda placeholder: placeholder.offset)
]
for modality, ranges in engine_input["mm_placeholders"].items()
}
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -52,11 +79,32 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
)
for choice in response.choices
]
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
return PrimeRlGenerateResponse(**{**response.model_dump(exclude={"choices"}), "choices": choices})
class _PromptTokenIdsCapture:
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
self._source = source
self.prompt_token_ids: list[int] | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for output in self._source:
self.prompt_token_ids = output.prompt_token_ids
yield output
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + compact routed experts."""
"""ServingTokens with Prime's remaining response and PD extensions."""
def _log_inputs(
self,
request_id: str,
inputs: Any,
params: Any,
lora_request: Any,
) -> None:
_response_mm_placeholders.set(_extract_mm_placeholders(inputs))
super()._log_inputs(request_id, inputs, params, lora_request)
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -66,22 +114,30 @@ class PrimeRlServingTokens(ServingTokens):
model_name: str,
request_metadata: RequestResponseMetadata,
) -> ErrorResponse | GenerateResponse:
# 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
routed_experts: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
capture = _GenerateRoutedExpertsCapture(
routed_experts = _GenerateRoutedExpertsCapture(
result_generator,
start=request.sampling_params.routed_experts_prompt_start,
)
result_generator = capture
result_generator = routed_experts
prompt_capture = _PromptTokenIdsCapture(result_generator)
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
request,
prompt_capture,
request_id,
model_name,
request_metadata,
)
if capture is not None and isinstance(response, GenerateResponse):
response = capture.post_process(response)
if not isinstance(response, GenerateResponse):
return response
if routed_experts is not None:
response = routed_experts.post_process(response)
else:
response = PrimeRlGenerateResponse(**response.model_dump())
response.prompt_token_ids = prompt_capture.prompt_token_ids
response.mm_placeholders = _response_mm_placeholders.get()
return response
+9
View File
@@ -0,0 +1,9 @@
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, MultimodalAdapter
from prime_rl.multimodal.registry import get_multimodal_adapter
__all__ = [
"ForwardPolicy",
"MaterializedMM",
"MultimodalAdapter",
"get_multimodal_adapter",
]
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Protocol
import torch
from PIL.Image import Image
@dataclass(frozen=True)
class ForwardPolicy:
pass_position_ids: bool = True
requires_mm_token_type_ids: bool = False
defer_context_parallelism: bool = False
@dataclass(frozen=True)
class MaterializedMM:
kwargs: dict[str, torch.Tensor]
forward_policy: ForwardPolicy
class MultimodalAdapter(Protocol):
model_types: frozenset[str]
forward_policy: ForwardPolicy
def materialize(
self,
image_processor: Any,
images: list[Image],
placeholder_lengths: list[int],
) -> MaterializedMM: ...
def required_tensors(values: Any, keys: tuple[str, ...]) -> dict[str, torch.Tensor]:
data = dict(values)
missing = [key for key in keys if key not in data]
if missing:
raise ValueError(f"Image processor did not return {', '.join(missing)}")
return {key: torch.as_tensor(data[key]).contiguous() for key in keys}
+33
View File
@@ -0,0 +1,33 @@
from __future__ import annotations
from typing import Any
from PIL.Image import Image
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, required_tensors
class KimiK25Adapter:
model_types = frozenset({"kimi_k25"})
forward_policy = ForwardPolicy()
def materialize(
self,
image_processor: Any,
images: list[Image],
placeholder_lengths: list[int],
) -> MaterializedMM:
preprocess = getattr(image_processor, "preprocess", None)
if preprocess is None:
raise ValueError("Kimi image processor is missing preprocess")
media = [{"type": "image", "image": image} for image in images]
kwargs = required_tensors(
preprocess(media, return_tensors="pt"),
("pixel_values", "grid_thws"),
)
lengths = [1] * len(kwargs["grid_thws"].reshape(-1, 3))
if lengths != placeholder_lengths:
raise ValueError(
f"Kimi image placeholder lengths differ from vLLM: expected {placeholder_lengths}, got {lengths}"
)
return MaterializedMM(kwargs=kwargs, forward_policy=self.forward_policy)
+35
View File
@@ -0,0 +1,35 @@
from __future__ import annotations
from typing import Any
from PIL.Image import Image
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, required_tensors
class QwenVLAdapter:
model_types = frozenset({"qwen3_vl", "qwen3_vl_moe", "qwen3_5", "qwen3_5_moe"})
forward_policy = ForwardPolicy(
pass_position_ids=False,
requires_mm_token_type_ids=True,
defer_context_parallelism=True,
)
def materialize(
self,
image_processor: Any,
images: list[Image],
placeholder_lengths: list[int],
) -> MaterializedMM:
kwargs = required_tensors(
image_processor(images=images, return_tensors="pt"),
("pixel_values", "image_grid_thw"),
)
merge_size = int(image_processor.merge_size)
# HF Qwen-VL / renderer pad count: T*H*W / merge_size^2.
lengths = [int(grid.prod()) // (merge_size * merge_size) for grid in kwargs["image_grid_thw"].reshape(-1, 3)]
if lengths != placeholder_lengths:
raise ValueError(
f"Qwen image placeholder lengths differ from vLLM: expected {placeholder_lengths}, got {lengths}"
)
return MaterializedMM(kwargs=kwargs, forward_policy=self.forward_policy)
+17
View File
@@ -0,0 +1,17 @@
from __future__ import annotations
from prime_rl.multimodal.base import MultimodalAdapter
from prime_rl.multimodal.kimi_k25 import KimiK25Adapter
from prime_rl.multimodal.qwen_vl import QwenVLAdapter
_ADAPTERS = (QwenVLAdapter(), KimiK25Adapter())
_BY_MODEL_TYPE: dict[str, MultimodalAdapter] = {
model_type: adapter for adapter in _ADAPTERS for model_type in adapter.model_types
}
def get_multimodal_adapter(model_type: str) -> MultimodalAdapter:
try:
return _BY_MODEL_TYPE[model_type]
except KeyError as exc:
raise NotImplementedError(f"Raw image training is not implemented for model type {model_type!r}") from exc
+12 -25
View File
@@ -20,10 +20,8 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
from __future__ import annotations
import asyncio
import random
import time
from collections.abc import Callable, Iterator, Sequence
from itertools import islice
from pathlib import Path
from typing import Generic, TypeVar
@@ -41,11 +39,6 @@ from prime_rl.utils.pathing import env_address_file
# before serving.
ENV_SERVER_STARTUP_TIMEOUT = 600.0
# Fixed seed for shuffle=True sources: the finite taskset is shuffled once at
# startup and the shuffled order is fixed for the whole run (train curricula and
# eval selection both consume it).
TASKSET_SHUFFLE_SEED = 42
async def wait_for_address(path: Path, timeout: float) -> str:
"""The address a launcher-managed env server published, polling for the file the
@@ -74,11 +67,11 @@ class Env:
is None."""
self.sampling_args: dict = {}
self.num_tasks: int | None = 0
"""Task count; ``None`` means the taskset is infinite."""
"""Task count; ``None`` means the selected tasks never end."""
self.tasks: Iterator[vf.Task] | None = None
"""The env's tasks, client-side, set at ``start()``. A finite taskset is
materialized (``num_tasks`` is its count) and iterated from there; an infinite
one streams off its generator. Consumed once — by ``TrainSource`` (train) or
"""The env's selected tasks (``select``), client-side, set at
``start()``. A bounded selection is materialized (``num_tasks`` is its count)
and iterated from there; an unbounded one streams off the taskset. Consumed once — by ``TrainSource`` (train) or
``EvalEnv.start`` (eval)."""
self._env_client: EnvClient | None = None
@@ -102,19 +95,15 @@ class Env:
# The server may still be coming up (the launcher spawns it concurrently with
# the orchestrator), so poll until it answers.
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
if self.config.shuffle:
raise ValueError(f"Env {self.name} has an infinite taskset — cannot shuffle it")
self.tasks = iter(taskset)
self.num_tasks = None
else:
taskset = vf.load_taskset(self.config.env.taskset).select(self.config.select)
if taskset.bounded:
# Materialize off the event loop — iterating may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset))
if self.config.shuffle:
random.Random(TASKSET_SHUFFLE_SEED).shuffle(materialized)
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
else:
self.tasks = iter(taskset)
self.num_tasks = None
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
@@ -186,12 +175,10 @@ class EvalEnv(Env):
async def start(self) -> None:
await super().start()
n = self.config.num_examples
if self.num_tasks is None and n < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
if self.num_tasks is None:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set select.limit to bound it")
# A fixed eval set, pulled off the tasks once and reused every epoch.
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
self.examples = tasks
self.examples = list(self.tasks)
EnvT = TypeVar("EnvT", bound=Env)
+51 -35
View File
@@ -8,9 +8,8 @@ training sample directly. Token-length readers (`completion_len`, `total_tokens`
live on `vf.Trace` itself.
Training is renderer-only across every mode (RL/OPD student, SFT teacher), so every node
always carries its tokens — no backfill needed. For multimodal rollouts the branch also carries
the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat `mm_kwargs` /
`mm_token_type_ids` the trainer forwards.
always carries its tokens — no backfill needed. Multimodal RL keeps the inline image URLs on
the messages and pairs them with vLLM's expanded image-token runs here.
"""
from __future__ import annotations
@@ -20,33 +19,48 @@ from collections.abc import Iterator
import numpy as np
import verifiers.v1 as vf
from prime_rl.transports.batch import TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts, SamplingMask
from prime_rl.transports.batch import MMImageRef, MMRefs, TrainingSample
from prime_rl.transports.batch.types import RoutedExperts, SamplingMask
from prime_rl.utils.logger import get_logger
def _to_numpy(val) -> np.ndarray:
"""A renderer mm item value (torch tensor or numpy array) -> a contiguous numpy array."""
if hasattr(val, "detach"): # torch tensor
val = val.detach().cpu().numpy()
return np.ascontiguousarray(val)
def _image_urls(branch: vf.Branch) -> list[str]:
urls: list[str] = []
for node in branch.nodes:
content = node.message.content
if not isinstance(content, list):
continue
for part in content:
if getattr(part, "type", None) == "image_url":
urls.append(part.image_url.url)
return urls
def _encode_mm_kwargs(mm_items: dict[str, list[dict]]) -> dict[str, EncodedTensor] | None:
"""Concatenate the branch's per-image renderer items into the flat `mm_kwargs` the trainer
forwards — one `EncodedTensor` per kwarg key (e.g. `pixel_values`, `image_grid_thw`), images
cat'd along dim 0 in branch token order. Model-agnostic: the keys are whatever the processor
emits. Returns None when there are no items."""
bins: dict[str, list[np.ndarray]] = {}
for items in mm_items.values(): # per modality
for item in items: # per image
for key, val in item.items():
bins.setdefault(key, []).append(_to_numpy(val))
encoded: dict[str, EncodedTensor] = {}
for key, arrs in bins.items():
arr = np.concatenate(arrs, axis=0)
encoded[key] = EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
return encoded or None
def _image_runs(token_types: list[int]) -> list[tuple[int, int]]:
runs: list[tuple[int, int]] = []
start: int | None = None
for index, token_type in enumerate([*token_types, 0]):
if token_type == 1 and start is None:
start = index
elif token_type != 1 and start is not None:
runs.append((start, index - start))
start = None
return runs
def _build_mm_refs(urls: list[str], token_types: list[int]) -> MMRefs | None:
runs = _image_runs(token_types)
if len(urls) != len(runs):
raise ValueError(
f"Inline image count does not match expanded placeholder runs: images={len(urls)}, runs={len(runs)}"
)
if not urls:
return None
return MMRefs(
images=[
MMImageRef(url=url, offset=offset, length=length) for url, (offset, length) in zip(urls, runs, strict=True)
]
)
def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExperts | None:
@@ -140,19 +154,21 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. Errored traces are dropped upstream (`TrainSink.process_episode`), so no error
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
pixel tensors) and `mm_token_type_ids` (`branch.mm_token_type_ids`, computed from the
trace's renderer-stamped `mm_token_type_id_map`). Branches with no sampled tokens
(e.g. an openai client carrying none) yield nothing.
handling happens here. A branch carrying images gets raw image refs paired with expanded
placeholder ranges and `mm_token_type_ids`. Branches with no sampled tokens yield nothing.
"""
samples: list[TrainingSample] = []
trained_loss_nodes: dict[str, set[int]] = {"rl": set(), "ce": set(), "ref_kl": set()}
for branch, mask in iter_trainable_branches(trace):
token_ids = branch.token_ids
mm_kwargs: dict[str, EncodedTensor] | None = None
mmd = branch.multi_modal_data
if mmd is not None:
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
mm_token_type_ids: list[int] | None = None
mm_refs: MMRefs | None = None
image_urls = _image_urls(branch)
if image_urls:
mm_token_type_ids = branch.mm_token_type_ids
if mm_token_type_ids is None:
raise ValueError("Inline images have no expanded multimodal prompt tokens")
mm_refs = _build_mm_refs(image_urls, mm_token_type_ids)
samples.append(
TrainingSample(
token_ids=token_ids,
@@ -161,8 +177,8 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
temperatures=[], # filled by TrainSink.process_group
env_name=env_name,
ref_logprobs=branch.reference_logprobs,
mm_kwargs=mm_kwargs,
mm_token_type_ids=branch.mm_token_type_ids,
mm_refs=mm_refs,
mm_token_type_ids=mm_token_type_ids,
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
rl_weights=_loss_weights(branch, "rl", trained_loss_nodes["rl"]),
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
+41 -94
View File
@@ -6,7 +6,7 @@ from typing import Any
import numpy as np
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, SamplingMask, TrainingSample
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, SamplingMask, TrainingSample
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
@@ -303,56 +303,17 @@ def _pad_sampling_mask(micro_batch: MicroBatch, padding_size: int) -> None:
sampling_mask.counts += b"\0" * (padding_size * _SAMPLING_MASK_ITEMSIZE)
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
itemsize = np.dtype(tensor.dtype).itemsize
return EncodedTensor(
dtype=tensor.dtype,
shape=[n_rows, *tensor.shape[1:]],
data=tensor.data[: n_rows * row * itemsize],
)
def _truncate_mm(
mm_token_type_ids: list[int], mm_kwargs: dict[str, EncodedTensor], seq_len: int
) -> tuple[int, dict[str, EncodedTensor] | None]:
"""Truncating a sample must not split an image's placeholder block, else the surviving image
token count no longer matches the image embeddings in `mm_kwargs`. Returns the cut point
(<= seq_len, never inside an image block) and `mm_kwargs` sliced to the images whose
placeholders fully survive (None if no image survives)."""
grid = np.frombuffer(bytearray(mm_kwargs["image_grid_thw"].data), dtype=mm_kwargs["image_grid_thw"].dtype).reshape(
mm_kwargs["image_grid_thw"].shape
)
patches_per_image = [int(g.prod()) for g in grid]
total_patches = mm_kwargs["pixel_values"].shape[0]
total_tokens = sum(1 for t in mm_token_type_ids if t)
ppt = total_patches // total_tokens if total_tokens else 1 # patches per token (merge^2)
tokens_per_image = [p // ppt for p in patches_per_image]
surviving = sum(1 for t in mm_token_type_ids[:seq_len] if t)
kept = acc = 0
for n in tokens_per_image:
if acc + n > surviving:
def _truncate_mm_refs(refs: MMRefs, seq_len: int) -> tuple[int, MMRefs | None]:
cut = seq_len
kept: list[MMImageRef] = []
for image in refs.images:
end = image.offset + image.length
if image.offset < seq_len < end:
cut = image.offset
break
acc += n
kept += 1
if acc == surviving:
cut = seq_len # surviving image tokens are exactly `kept` whole images
else:
# `surviving` lands inside image `kept`; cut to its first placeholder, dropping it.
seen, cut = 0, seq_len
for i, t in enumerate(mm_token_type_ids):
if t:
seen += 1
if seen == acc + 1:
cut = i
break
if not kept:
return cut, None
kept_patches = sum(patches_per_image[:kept])
sliced = {k: _slice_encoded(v, kept if k == "image_grid_thw" else kept_patches) for k, v in mm_kwargs.items()}
return cut, sliced
if end <= seq_len:
kept.append(image)
return cut, MMRefs(images=kept) if kept else None
def multimodal_sample_error(sample: TrainingSample) -> str | None:
@@ -362,8 +323,14 @@ def multimodal_sample_error(sample: TrainingSample) -> str | None:
"mm_token_type_ids length must match token_ids length "
f"({len(mm_token_type_ids)} != {len(sample.token_ids)})"
)
if sample.mm_kwargs is not None and "image_grid_thw" in sample.mm_kwargs and mm_token_type_ids is None:
return "image_grid_thw multimodal samples require mm_token_type_ids"
if sample.mm_refs is not None and mm_token_type_ids is None:
return "multimodal samples require mm_token_type_ids"
if sample.mm_refs is not None:
previous_end = 0
for image in sample.mm_refs.images:
if image.offset < previous_end or image.offset + image.length > len(sample.token_ids):
return "multimodal image refs must be ordered, non-overlapping, and within token_ids"
previous_end = image.offset + image.length
return None
@@ -395,7 +362,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
ref_kl_weights = list(training_example.ref_kl_weights) if training_example.ref_kl_weights is not None else None
position_ids = list(range(len(input_ids)))
mm_token_type_ids = training_example.mm_token_type_ids
mm_kwargs = training_example.mm_kwargs
mm_refs = training_example.mm_refs
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
env_names = [training_example.env_name] * len(input_ids)
@@ -413,11 +380,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
sampling_mask = training_example.sampling_mask
if len(input_ids) > seq_len:
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
# and slice mm_kwargs to match, so image-token count == image-embedding count.
cut = seq_len
if mm_token_type_ids is not None and mm_kwargs is not None:
cut, mm_kwargs = _truncate_mm(mm_token_type_ids, mm_kwargs, seq_len)
if mm_refs is not None:
cut, mm_refs = _truncate_mm_refs(mm_refs, seq_len)
input_ids = input_ids[:cut]
loss_mask = loss_mask[:cut]
inference_logprobs = inference_logprobs[:cut]
@@ -488,7 +453,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
sampling_mask=sampling_mask,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=mm_kwargs,
mm_refs=mm_refs,
rl_weights=rl_weights,
ce_weights=ce_weights,
ref_kl_weights=ref_kl_weights,
@@ -500,7 +465,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
def _is_multimodal_sample(sample: MicroBatch) -> bool:
"""Check if a sample contains multimodal data (images)."""
return sample.mm_kwargs is not None
return sample.mm_refs is not None
@dataclass
@@ -516,36 +481,15 @@ class _MicroBatchBin:
def first_sample(self) -> MicroBatch:
return self.samples[0]
@property
def first_multimodal_sample(self) -> MicroBatch | None:
for sample in self.samples:
if _is_multimodal_sample(sample):
return sample
return None
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
# Loss routing is per token (component weight streams), so samples of
# different loss types pack together freely. Multimodal packing is still
# constrained by modality sidecars, length, and routed experts.
# different loss types and raw-image refs pack together freely.
first_sample = self.first_sample
if self.length + len(sample.input_ids) > max_seq_len:
return False
if (first_sample.routed_experts is None) != (sample.routed_experts is None):
return False
sample_is_mm = _is_multimodal_sample(sample)
existing_mm_sample = self.first_multimodal_sample
if existing_mm_sample is not None and sample_is_mm:
dst = existing_mm_sample.mm_kwargs
src = sample.mm_kwargs
assert dst is not None and src is not None, "multimodal samples must carry mm_kwargs"
return set(dst) == set(src) and all(
dst[key].dtype == src[key].dtype
and len(dst[key].shape) > 0
and len(dst[key].shape) == len(src[key].shape)
and dst[key].shape[1:] == src[key].shape[1:]
for key in dst
)
return True
def add(self, sample: MicroBatch) -> None:
@@ -594,7 +538,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
env_names: list[str] = []
ref_logprobs: list[float] | None = [] if has_ref_logprobs else None
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
mm_kwargs: dict[str, EncodedTensor] | None = None
mm_refs: MMRefs | None = None
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
seq_lens: list[int] = []
routed_experts: RoutedExperts | None = None
@@ -630,13 +574,17 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
routed_experts.data += sample.routed_experts.data
routed_experts.shape[0] += sample.routed_experts.shape[0]
if sample.mm_kwargs is not None:
if mm_kwargs is None:
mm_kwargs = copy.deepcopy(sample.mm_kwargs)
else:
for key in mm_kwargs:
mm_kwargs[key].data += sample.mm_kwargs[key].data
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
if sample.mm_refs is not None:
if mm_refs is None:
mm_refs = MMRefs(images=[])
mm_refs.images.extend(
MMImageRef(
url=image.url,
offset=len(input_ids) - sample_len + image.offset,
length=image.length,
)
for image in sample.mm_refs.images
)
seq_lens.extend(sample.seq_lens)
if sampling_mask is not None:
sample_mask = sample.sampling_mask if sample.sampling_mask is not None else _empty_sampling_mask(sample_len)
@@ -662,7 +610,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
sampling_mask=sampling_mask,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=mm_kwargs,
mm_refs=mm_refs,
rl_weights=streams["rl_weights"],
ce_weights=streams["ce_weights"],
ref_kl_weights=streams["ref_kl_weights"],
@@ -679,7 +627,7 @@ def _expand_bins_by_splitting(
candidates = [
(bin_content.workload(bin_cost), idx)
for idx, bin_content in enumerate(bins)
if len(bin_content.samples) > 1 and bin_content.first_multimodal_sample is None
if len(bin_content.samples) > 1
]
if not candidates:
break
@@ -700,9 +648,8 @@ 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.
Multimodal samples pack with text spans and with compatible eager
``mm_kwargs`` samples. Packed batches preserve sample boundaries in
``seq_lens``.
Multimodal samples pack with text spans and other raw-image samples. Packed
batches preserve sample boundaries in ``seq_lens``.
"""
# Sort by decreasing length for packing efficiency
samples.sort(key=lambda sample: -len(sample.input_ids))
+8 -9
View File
@@ -31,6 +31,7 @@ from prime_rl.configs.trainer import (
MXFP8Config,
TokenizerConfig,
)
from prime_rl.multimodal import ForwardPolicy
from prime_rl.trainer.activation_checkpointing import get_activation_checkpoint_wrapper
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
from prime_rl.trainer.models import (
@@ -1088,12 +1089,8 @@ def forward(
temperature: Tensor | None = None,
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
sampling_mask: Int[Tensor, "batch seq mask"] | 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 comes from the renderer rather than the processor.
mm_kwargs: dict[str, Tensor] | None = None,
mm_forward_policy: ForwardPolicy | None = None,
mm_token_type_ids: Int[Tensor, "batch seq"] | None = None,
# True when seq_lens holds the full pre-CP-shard document boundaries
# (kept global because documents can straddle the shard cut).
@@ -1111,13 +1108,15 @@ def forward(
kwargs["sampling_mask"] = sampling_mask
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
if "image_grid_thw" not in mm_kwargs:
# SFT still uses its existing eager processor path and does not provide
# an adapter policy yet, so preserve its current kwargs-based behavior.
policy = mm_forward_policy or ForwardPolicy(pass_position_ids="image_grid_thw" not in mm_kwargs)
if policy.requires_mm_token_type_ids and mm_token_type_ids is None:
raise ValueError("Multimodal forward policy requires mm_token_type_ids")
if policy.pass_position_ids:
kwargs["position_ids"] = position_ids
else:
kwargs["position_ids"] = position_ids
+98 -5
View File
@@ -5,11 +5,15 @@ from typing import TypedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
# Same as torch's cross entropy loss
IGNORE_INDEX = -100
class PrimeLmOutput(TypedDict, total=False):
"""Output from LM head - a TypedDict so pytree can find tensors for FSDP2 hooks."""
@@ -35,6 +39,13 @@ def cast_float_and_contiguous(output: PrimeLmOutput) -> PrimeLmOutput:
class FusedOutputLinear(torch.nn.Linear):
"""Chunked LM head that never materializes the full [N, V] logits.
With ``labels`` and no ``temperature`` it returns the summed cross-entropy over labels != IGNORE_INDEX
as ``loss``, computing the gradients chunk by chunk in the forward pass (see ``_ChunkedCrossEntropySumFn``).
With ``temperature`` it returns per-token ``logprobs`` and ``entropy``.
"""
def __init__(self, in_features: int, out_features: int, chunk_size: int):
super().__init__(in_features, out_features, bias=False)
self.chunk_size = chunk_size
@@ -47,11 +58,16 @@ class FusedOutputLinear(torch.nn.Linear):
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
assert labels is not None, "FusedOutputLinear requires labels for chunked logprob computation"
assert temperature is not None, "FusedOutputLinear requires per-token temperatures"
b, s, h = hidden_states.shape
hidden_states = hidden_states.reshape(b * s, h).contiguous()
labels = labels.reshape(b * s).contiguous()
if temperature is None:
assert sampling_mask is None, "sampling-mask replay requires per-token temperatures"
loss = _ChunkedCrossEntropySumFn.apply(hidden_states, self.weight, labels, self.chunk_size)
return PrimeLmOutput(loss=loss)
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
if sampling_mask is not None:
sampling_mask = sampling_mask.reshape(b * s, sampling_mask.shape[-1]).contiguous()
@@ -66,6 +82,9 @@ class FusedOutputLinear(torch.nn.Linear):
class VanillaOutputLinear(torch.nn.Linear):
"""LM head that returns the full logits, or with ``labels`` and no ``temperature`` the summed fp32
cross-entropy over labels != IGNORE_INDEX as ``loss``."""
def __init__(self, in_features: int, out_features: int):
super().__init__(in_features, out_features, bias=False)
@@ -76,9 +95,18 @@ class VanillaOutputLinear(torch.nn.Linear):
temperature: Tensor | None = None,
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
# VanillaOutputLinear just returns logits. train.py applies temperature
# scaling and sampling-mask replay.
return PrimeLmOutput(logits=super().forward(hidden_states))
logits = super().forward(hidden_states)
if labels is not None and temperature is None:
return PrimeLmOutput(loss=cross_entropy_sum(logits, labels))
# train.py applies temperature scaling and sampling-mask replay to the logits.
return PrimeLmOutput(logits=logits)
def cross_entropy_sum(logits: Tensor, labels: Tensor) -> Tensor:
"""Summed fp32 cross-entropy over labels != IGNORE_INDEX."""
return F.cross_entropy(
logits.view(-1, logits.shape[-1]).float(), labels.reshape(-1), ignore_index=IGNORE_INDEX, reduction="sum"
)
def _online_logsumexp_and_weighted_update(
@@ -266,6 +294,71 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
return grad_hidden, grad_weight, None, None, None, None
class _ChunkedCrossEntropySumFn(torch.autograd.Function):
"""Summed cross-entropy over labels != IGNORE_INDEX, with the gradients computed during forward.
Per chunk of ``chunk_size`` tokens: one full-vocab logits GEMM, the loss, and the gradient
(softmax minus one-hot) folded straight into ``grad_hidden`` and ``grad_weight``. Only one chunk's
logits are alive at a time and backward does no recompute: it scales the stored gradients by the
incoming scalar. That drops the head's matmul passes from four to three (forward logits, dX, dW).
Same approach as torchtitan's ChunkedLossWrapper.
Backward only accepts a scalar upstream gradient (e.g. ``loss_sum / k``). Per-token weighted losses
must pass a temperature and go through the logprob path instead.
"""
@staticmethod
def forward( # type: ignore[override]
ctx,
hidden: torch.Tensor, # [N, H]
weight: torch.Tensor, # [V, H]
labels: torch.Tensor, # [N], IGNORE_INDEX where the token has no loss
chunk_size: int,
) -> torch.Tensor:
assert hidden.dim() == 2 and weight.dim() == 2 and labels.dim() == 1
assert hidden.shape[0] == labels.shape[0] and hidden.shape[1] == weight.shape[1]
assert chunk_size > 0
needs_hidden, needs_weight = ctx.needs_input_grad[0], ctx.needs_input_grad[1]
grad_hidden = torch.empty_like(hidden) if needs_hidden else None
grad_weight = torch.zeros_like(weight) if needs_weight else None
loss = torch.zeros((), device=hidden.device, dtype=torch.float32)
for start in range(0, hidden.shape[0], chunk_size):
end = min(start + chunk_size, hidden.shape[0])
hidden_chunk = hidden[start:end]
labels_chunk = labels[start:end]
valid = labels_chunk != IGNORE_INDEX
target = labels_chunk.clamp(min=0).unsqueeze(-1)
logits = (hidden_chunk @ weight.t()).float()
logz = torch.logsumexp(logits, dim=-1)
target_logits = logits.gather(1, target).squeeze(1)
loss += torch.where(valid, logz - target_logits, 0.0).sum()
if needs_hidden or needs_weight:
# dx(loss)/dx(logits) is softmax minus one-hot on valid rows and zero elsewhere so it reuses the logits buffer
grad_logits = logits.sub_(logz.unsqueeze(-1)).exp_()
grad_logits.scatter_add_(1, target, torch.full_like(target, -1, dtype=grad_logits.dtype))
grad_logits = grad_logits.mul_(valid.unsqueeze(-1)).to(hidden.dtype)
if needs_hidden:
torch.mm(grad_logits, weight, out=grad_hidden[start:end])
if needs_weight:
grad_weight.addmm_(grad_logits.t(), hidden_chunk)
ctx.save_for_backward(grad_hidden, grad_weight)
return loss
@staticmethod
def backward(ctx, grad_loss: torch.Tensor):
grad_hidden, grad_weight = ctx.saved_tensors
if grad_hidden is not None:
grad_hidden = grad_hidden * grad_loss.to(grad_hidden.dtype)
if grad_weight is not None:
grad_weight = grad_weight * grad_loss.to(grad_weight.dtype)
return grad_hidden, grad_weight, None, None
def inject_prime_lm_head(
model: nn.Module,
chunk_size: int | None = None,
@@ -279,7 +372,7 @@ def inject_prime_lm_head(
Args:
model: The model to wrap.
chunk_size: When set to an int, uses FusedOutputLinear with sequence-token chunked
logprob/entropy computation.
loss/logprob/entropy computation.
"""
# Guards so we have nicer error messages when a non-standard model is used
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
@@ -5,9 +5,11 @@ import torch.nn as nn
from torch import Tensor
from prime_rl.trainer.models.layers.lm_head import (
IGNORE_INDEX,
PrimeLmOutput,
_online_logsumexp_and_weighted_update,
_patch_model_forward,
cross_entropy_sum,
)
from prime_rl.utils.logger import get_logger
@@ -26,14 +28,21 @@ class GemmaFusedOutputLinear(torch.nn.Linear):
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
assert labels is not None, "GemmaFusedOutputLinear requires labels for chunked logprob computation"
assert temperature is not None, "GemmaFusedOutputLinear requires per-token temperatures"
assert sampling_mask is None, "sampling-mask replay is not supported with Gemma softcapped lm_heads"
b, s, h = hidden_states.shape
hidden_states = hidden_states.reshape(b * s, h).contiguous()
labels = labels.reshape(b * s).contiguous()
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
if temperature is None:
# Summed cross-entropy through the logprob path; IGNORE_INDEX rows are masked at the sum.
inv_t = torch.ones(b * s, device=hidden_states.device, dtype=torch.float32)
logprobs, _ = _GemmaChunkedLogProbEntropyFn.apply(
hidden_states, self.weight, labels, inv_t, self.chunk_size, self.softcap
)
return PrimeLmOutput(loss=-logprobs[labels != IGNORE_INDEX].sum())
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
logprobs, entropy = _GemmaChunkedLogProbEntropyFn.apply(
hidden_states, self.weight, labels, inv_t, self.chunk_size, self.softcap
)
@@ -57,6 +66,8 @@ class GemmaVanillaOutputLinear(torch.nn.Linear):
) -> PrimeLmOutput:
logits = super().forward(hidden_states)
logits = self.softcap * torch.tanh(logits / self.softcap)
if labels is not None and temperature is None:
return PrimeLmOutput(loss=cross_entropy_sum(logits, labels))
return PrimeLmOutput(logits=logits)
+26
View File
@@ -0,0 +1,26 @@
from __future__ import annotations
import base64
from io import BytesIO
from typing import Any
from PIL import Image
from prime_rl.multimodal import MaterializedMM, MultimodalAdapter
from prime_rl.transports.batch import MMRefs
def _load_image(data_url: str) -> Image.Image:
header, separator, payload = data_url.partition(",")
if not separator or not header.startswith("data:image/") or ";base64" not in header:
raise ValueError("Multimodal training requires base64 data image URLs")
with Image.open(BytesIO(base64.b64decode(payload, validate=True))) as image:
return image.convert("RGB")
def materialize_mm_refs(refs: MMRefs, processor: Any, adapter: MultimodalAdapter) -> MaterializedMM:
image_processor = getattr(processor, "image_processor", None)
if image_processor is None:
raise ValueError("Multimodal samples require a model image processor")
images = [_load_image(ref.url) for ref in refs.images]
return adapter.materialize(image_processor, images, [ref.length for ref in refs.images])
+6 -18
View File
@@ -11,6 +11,7 @@ from prime_rl.trainer.world import get_world
from prime_rl.transports.batch import (
BatchReceiver,
MicroBatch,
MMRefs,
TransportConfig,
setup_batch_receiver,
)
@@ -46,12 +47,8 @@ class TensorMicroBatch(TypedDict):
# maximum mask size. A row containing only -1 has no mask.
sampling_mask: Int[Tensor, "batch seq mask"] | 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
# Materialized immediately before this microbatch's forward pass.
mm_refs: MMRefs | 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
@@ -135,7 +132,7 @@ class FakeDataLoader:
"seq_lens": torch.tensor(sequence_lengths, dtype=torch.long),
"routed_experts": None,
"sampling_mask": None,
"mm_kwargs": None,
"mm_refs": None,
"mm_token_type_ids": None,
"rl_weights": None,
"ce_weights": None,
@@ -167,7 +164,7 @@ class FakeDataLoader:
"seq_lens": torch.tensor([self.seq_len], dtype=torch.long),
"routed_experts": None,
"sampling_mask": None,
"mm_kwargs": None,
"mm_refs": None,
"mm_token_type_ids": None,
"rl_weights": None,
"ce_weights": None,
@@ -201,15 +198,6 @@ class DataLoader:
def _micro_batch_to_tensor(self, micro_batch: MicroBatch) -> TensorMicroBatch:
"""Convert a MicroBatch (msgspec struct with lists) to a TensorMicroBatch (dict with tensors)."""
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:
@@ -249,7 +237,7 @@ class DataLoader:
# Single adapter: every token in the batch belongs to it (padding included).
lora_num_tokens=torch.tensor([len(micro_batch.input_ids)], dtype=torch.int32),
seq_lens=torch.tensor(micro_batch.seq_lens, dtype=torch.long),
mm_kwargs=mm_kwargs,
mm_refs=micro_batch.mm_refs,
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,
+144 -65
View File
@@ -6,7 +6,14 @@ from beartype import beartype as typechecker
from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.configs.trainer import CustomLossConfig, IcePopLossConfig, IPOLossConfig, LossConfig
from prime_rl.configs.trainer import (
CISPOLossConfig,
CustomLossConfig,
IcePopLossConfig,
IPOLossConfig,
LossConfig,
PPOLossConfig,
)
from prime_rl.trainer.models.layers.lm_head import sampling_replay_mask
from prime_rl.utils.utils import import_object
@@ -39,7 +46,7 @@ class LossOutputs:
class Loss(Protocol):
"""Interface for the config-initialized rl loss objects built by
``setup_rl_loss_fn``: ``IPOLoss``, ``IcePopLoss`` and ``CustomLoss``."""
``setup_rl_loss_fn``."""
def loss(self, inputs: LossInputs) -> LossOutputs: ...
@@ -125,54 +132,64 @@ def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None =
def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
"""Mean of values over a boolean mask; returns 0 when mask is empty."""
denom = torch.clamp_min(mask.sum(), 1)
return values[mask].sum() / denom
return (values[mask] / denom).sum()
def compute_importance_ratio_and_mismatch_kl(
trainer_logprobs: Tensor, inference_logprobs: Tensor
) -> tuple[Tensor, Tensor, Tensor]:
log_importance_ratio = trainer_logprobs - inference_logprobs
importance_ratio = torch.exp(log_importance_ratio)
mismatch_kl = importance_ratio - log_importance_ratio - 1
return log_importance_ratio, importance_ratio, mismatch_kl
def _mismatch_kl_from_log_ratio(log_importance_ratio: Tensor) -> Tensor:
# Keep headroom for FP32 reductions across tokens and ranks.
metric_limit = log_importance_ratio.new_tensor(1e30)
mismatch_kl = torch.expm1(log_importance_ratio.clamp(max=metric_limit.log())) - log_importance_ratio
return mismatch_kl.clamp(max=metric_limit)
def _capped_importance_ratio(log_importance_ratio: Tensor, max_ratio: float) -> Tensor:
capped_log_ratio = log_importance_ratio.detach().clamp(max=log_importance_ratio.new_tensor(max_ratio).log())
return torch.exp(capped_log_ratio + (log_importance_ratio - log_importance_ratio.detach()))
class IPOLoss:
"""IPO loss type: a symmetric trust region (mask tokens whose probability
moved more than ``eps`` in absolute terms), policy gradient via
the importance ratio, and a squared-log-ratio KL regularizer."""
a capped importance ratio, and a squared-log-ratio KL regularizer."""
def __init__(self, config: IPOLossConfig):
self.config = config
def loss(self, inputs: LossInputs) -> LossOutputs:
loss_config = self.config
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
advantages = inputs.advantages[inputs.loss_mask]
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
log_importance_ratio = trainer_logprobs - inference_logprobs
larger_logprob = torch.maximum(trainer_logprobs, inference_logprobs)
smaller_logprob = torch.minimum(trainer_logprobs, inference_logprobs)
# |e^logp - e^logq| = e^max(logp, logq) - e^min(logp, logq)
# = e^max(logp, logq) * (1 - e^(min(logp, logq) - max(logp, logq)))
# = e^max(logp, logq) * -expm1(min(logp, logq) - max(logp, logq)).
# expm1 avoids cancellation in 1 - e^x when x is near zero.
abs_probs_diff = torch.exp(larger_logprob) * -torch.expm1(smaller_logprob - larger_logprob)
is_masked = abs_probs_diff > loss_config.eps
keep_mask = loss_mask & ~is_masked
keep_mask = ~is_masked
advantages = loss_config.adv_tau * advantages
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], loss_config.max_importance_ratio)
pg_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
if weights is not None:
pg_loss = pg_loss * weights[keep_mask]
loss = pg_loss.sum()
if loss_config.kl_tau:
kl_loss = loss_config.kl_tau * log_importance_ratio.clamp(-1e4, 1e4).square()
if weights is not None:
kl_loss = kl_loss * weights
loss = loss + kl_loss.sum()
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
"is_masked": _safe_mean(is_masked, loss_mask),
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
}
return LossOutputs(loss=loss, metrics=metrics)
@@ -187,28 +204,88 @@ class IcePopLoss:
def loss(self, inputs: LossInputs) -> LossOutputs:
loss_config = self.config
log_importance_ratio, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
inputs.trainer_logprobs, inputs.inference_logprobs
)
log_importance_ratio = inputs.trainer_logprobs[inputs.loss_mask] - inputs.inference_logprobs[inputs.loss_mask]
advantages = inputs.advantages[inputs.loss_mask]
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
log_ratio_low = log_importance_ratio.new_tensor(loss_config.ratio_low).log()
log_ratio_high = log_importance_ratio.new_tensor(loss_config.ratio_high).log()
detached_log_ratio = log_importance_ratio.detach()
is_masked = (detached_log_ratio < log_ratio_low) | (detached_log_ratio > log_ratio_high)
keep_mask = inputs.loss_mask & ~is_masked
keep_mask = ~is_masked
# Mask before exponentiation so rejected extreme ratios cannot produce
# 0 * inf = NaN in the loss or its gradient.
safe_log_ratio = torch.where(keep_mask, log_importance_ratio, torch.zeros_like(log_importance_ratio))
importance_ratio = torch.exp(safe_log_ratio)
per_token_loss = -(keep_mask * loss_config.adv_tau * inputs.advantages * importance_ratio)
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
importance_ratio = torch.exp(log_importance_ratio[keep_mask])
per_token_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
if weights is not None:
per_token_loss = per_token_loss * weights[keep_mask]
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, inputs.loss_mask & is_masked),
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"is_masked": _safe_mean(is_masked, inputs.loss_mask),
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
}
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
class PPOLoss:
"""Token-level PPO clipped surrogate with bounded importance weights."""
def __init__(self, config: PPOLossConfig):
self.config = config
def loss(self, inputs: LossInputs) -> LossOutputs:
config = self.config
logprobs = inputs.trainer_logprobs[inputs.loss_mask]
log_ratio = logprobs - inputs.inference_logprobs[inputs.loss_mask]
advantages = config.adv_tau * inputs.advantages[inputs.loss_mask]
ratio = _capped_importance_ratio(log_ratio, config.max_importance_ratio)
clipped_ratio = ratio.clamp(config.ratio_low, config.ratio_high)
per_token_loss = -torch.minimum(advantages * ratio, advantages * clipped_ratio)
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights[inputs.loss_mask]
clipped = ((advantages > 0) & (log_ratio.detach() > log_ratio.new_tensor(config.ratio_high).log())) | (
(advantages < 0) & (log_ratio.detach() < log_ratio.new_tensor(config.ratio_low).log())
)
metrics = {
"is_clipped": clipped.sum() / max(clipped.numel(), 1),
"ratio_capped": (log_ratio.detach() > log_ratio.new_tensor(config.max_importance_ratio).log()).sum()
/ max(log_ratio.numel(), 1),
}
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
class CISPOLoss:
"""CISPO uses a detached clipped importance weight on the current logprob."""
def __init__(self, config: CISPOLossConfig):
self.config = config
def loss(self, inputs: LossInputs) -> LossOutputs:
config = self.config
logprobs = inputs.trainer_logprobs[inputs.loss_mask]
log_ratio = logprobs - inputs.inference_logprobs[inputs.loss_mask]
advantages = config.adv_tau * inputs.advantages[inputs.loss_mask]
detached_log_ratio = log_ratio.detach()
log_ratio_high = log_ratio.new_tensor(config.ratio_high).log()
clipped_log_ratio = detached_log_ratio.clamp(max=log_ratio_high)
is_clipped = detached_log_ratio > log_ratio_high
if config.ratio_low:
log_ratio_low = log_ratio.new_tensor(config.ratio_low).log()
clipped_log_ratio = clipped_log_ratio.clamp(min=log_ratio_low)
is_clipped = is_clipped | (detached_log_ratio < log_ratio_low)
importance_weight = clipped_log_ratio.exp()
per_token_loss = -importance_weight * advantages * logprobs
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights[inputs.loss_mask]
metrics = {
"is_clipped": is_clipped.sum() / max(is_clipped.numel(), 1),
}
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
@@ -222,39 +299,37 @@ def ref_kl_loss_fn(inputs: LossInputs) -> LossOutputs:
inference probability; a squared-log-ratio term regularizes drift. Scalar
advantages are not read — ref_kl algorithms ship none.
"""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
ref_logprobs = inputs.ref_logprobs
loss_mask = inputs.loss_mask
if ref_logprobs is None:
if inputs.ref_logprobs is None:
raise ValueError("ref_kl loss type requires ref_logprobs — use the 'opd' or 'opsd' algorithm.")
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
ref_logprobs = inputs.ref_logprobs[inputs.loss_mask]
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
log_importance_ratio = trainer_logprobs - inference_logprobs
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
is_masked = probs_diff < -0.2
drop_mask = loss_mask & is_masked
keep_mask = loss_mask & ~is_masked
keep_mask = ~is_masked
ref_kl = ref_logprobs - trainer_logprobs
pg_loss = keep_mask * ref_kl.detach() * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
per_token_loss = -pg_loss + 1e-3 * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], 1e4)
pg_loss = -ref_kl[keep_mask].detach() * importance_ratio
kl_loss = 1e-3 * log_importance_ratio.clamp(-1e4, 1e4).square()
if weights is not None:
pg_loss = pg_loss * weights[keep_mask]
kl_loss = kl_loss * weights
loss = pg_loss.sum() + kl_loss.sum()
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
# Namespaced: the rl loss fn emits same-named trust-region metrics with a
# different definition, and mixed batches run both fns in one step.
metrics = {
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, drop_mask),
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
"ref_kl/unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"ref_kl/is_masked": _safe_mean(is_masked, loss_mask),
"ref_kl": _safe_mean(ref_kl, loss_mask),
"ref_kl/is_masked": is_masked.sum() / max(is_masked.numel(), 1),
"ref_kl": ref_kl.sum() / max(ref_kl.numel(), 1),
}
return LossOutputs(loss=loss, metrics=metrics)
@@ -298,6 +373,10 @@ def setup_rl_loss_fn(loss_config: LossConfig) -> Loss:
return IPOLoss(loss_config)
case IcePopLossConfig():
return IcePopLoss(loss_config)
case PPOLossConfig():
return PPOLoss(loss_config)
case CISPOLossConfig():
return CISPOLoss(loss_config)
case _:
raise TypeError(f"Unsupported RL loss config: {type(loss_config).__name__}")
+35 -19
View File
@@ -29,20 +29,23 @@ from prime_rl.utils.logger import format_time, setup_logger
from prime_rl.trainer.rl.loss import (
compute_entropy,
compute_loss,
compute_importance_ratio_and_mismatch_kl,
_mismatch_kl_from_log_ratio,
selective_log_softmax,
selective_log_softmax_with_sampling_mask,
setup_rl_loss_fn,
shift_tensor_left,
shift_tensor_right,
)
from prime_rl.multimodal import get_multimodal_adapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.trainer.rl.annotations import AnnotationWriter
from prime_rl.trainer.model import (
forward,
get_full_offload_dtype_policy,
setup_model,
is_tt_moe_model,
get_global_moe_stats,
is_tt_moe_model,
setup_model,
setup_processor,
)
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
from prime_rl.trainer.perf import get_perf_counter
@@ -142,13 +145,21 @@ def train(config: TrainerConfig):
if checkpoint_step is None:
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
# Initialize the model and tokenizer
# Initialize the model
logger.info(f"Initializing model ({config.model})")
t0 = time.perf_counter()
loading_from_ckpt_later = checkpoint_step is not None
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
logger.debug(f"Initialized model in {format_time(time.perf_counter() - t0)}")
processor = None
mm_adapter = None
if config.model.vlm is not None:
processor = setup_processor(config.model)
if processor is None:
raise ValueError("Multimodal training requires a model image processor")
mm_adapter = get_multimodal_adapter(model.config.model_type)
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
@@ -362,17 +373,17 @@ def train(config: TrainerConfig):
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] 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
if mm_kwargs is not None and config.model.vlm is None:
raise ValueError(
"Received multimodal samples but [model.vlm] is not set. "
"Set [model.vlm] to train on multimodal samples."
)
mm_kwargs = None
mm_forward_policy = None
mm_refs = micro_batch.get("mm_refs")
if mm_refs is not None:
if processor is None or mm_adapter is None:
raise ValueError("Received multimodal samples but [model.vlm] is not set")
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
mm_kwargs = {key: value.to("cuda") for key, value in materialized.kwargs.items()}
mm_forward_policy = materialized.forward_policy
micro_batch["mm_refs"] = None
del materialized, mm_refs
mm_token_type_ids = (
micro_batch["mm_token_type_ids"].to("cuda")
if micro_batch.get("mm_token_type_ids") is not None
@@ -390,8 +401,9 @@ def train(config: TrainerConfig):
seq_lens_are_pre_shard = False
if cp_enabled:
# MRoPE batches must merge image embeddings before sharding.
defer_vlm_cp_to_model = mm_kwargs is not None and "image_grid_thw" in mm_kwargs
defer_vlm_cp_to_model = bool(
mm_forward_policy is not None and mm_forward_policy.defer_context_parallelism
)
if not defer_vlm_cp_to_model:
input_ids, position_ids = setup_cp_params(
input_ids,
@@ -444,6 +456,7 @@ def train(config: TrainerConfig):
labels=labels,
temperature=temperatures,
mm_kwargs=mm_kwargs,
mm_forward_policy=mm_forward_policy,
mm_token_type_ids=mm_token_type_ids,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
@@ -500,6 +513,8 @@ def train(config: TrainerConfig):
loss.backward()
finish_backward(gradient_manager)
mm_kwargs = None
# Add relevant tensors to tensor dict for logging purposes
entropy = out["entropy"][loss_mask].detach().to("cpu")
tensors["entropy/all"].append(entropy)
@@ -528,8 +543,9 @@ def train(config: TrainerConfig):
has_mismatch_tokens = bool(mismatch_mask.any())
if has_mismatch_tokens:
with torch.no_grad():
_, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(out["logprobs"], inference_logprobs)
mismatch_kl = mismatch_kl[mismatch_mask].detach().to("cpu")
log_ratio = out["logprobs"][mismatch_mask] - inference_logprobs[mismatch_mask]
mismatch_kl = _mismatch_kl_from_log_ratio(log_ratio)
mismatch_kl = mismatch_kl.detach().to("cpu")
tensors["mismatch_kl/all"].append(mismatch_kl)
mismatch_env_names = [
env_name for env_name, keep in zip(env_names, mismatch_mask.flatten().tolist()) if keep
+15 -34
View File
@@ -6,8 +6,6 @@ import asyncio
from contextlib import nullcontext
from datetime import timedelta
from torch.nn import CrossEntropyLoss
# Import environment before any other imports
# ruff: noqa: I001
@@ -21,6 +19,7 @@ from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
from prime_rl.utils.cp import setup_context_parallel, setup_cp_params, shard_for_cp
from prime_rl.trainer.lora import get_lora_state
from prime_rl.trainer.models.layers.lm_head import IGNORE_INDEX
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.logger import format_time, setup_logger
from prime_rl.trainer.optim import setup_optimizer
@@ -279,39 +278,21 @@ def train(config: SFTConfig):
token_count = loss_mask.sum(dtype=torch.int64)
# Labels without a temperature make the LM head return the summed cross-entropy directly.
labels = target_ids.masked_fill(~loss_mask, IGNORE_INDEX)
with maybe_activation_offloading(config.model.ac_offloading):
if isinstance(config.model.fused_lm_head_token_chunk_size, int):
# Same path as the RL trainer: the chunked LM head computes per-token
# logprobs without materializing the [N, V] logits, and per-token
# cross-entropy is the negative target logprob.
temperature = torch.ones_like(target_ids, dtype=torch.float32)
out = forward(
model,
input_ids,
position_ids,
seq_lens=seq_lens,
labels=target_ids,
temperature=temperature,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_type_ids,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
loss_sum = -out["logprobs"][loss_mask].sum()
else:
out = forward(
model,
input_ids,
position_ids,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_type_ids,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
logits = out["logits"]
B, L, V = logits.shape
token_loss = CrossEntropyLoss(reduction="none")(logits.view(-1, V), target_ids.view(-1)).view(B, L)
loss_sum = token_loss[loss_mask].sum()
del logits
out = forward(
model,
input_ids,
position_ids,
seq_lens=seq_lens,
labels=labels,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_type_ids,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
loss_sum = out["loss"]
del out
return loss_sum, token_count
@@ -8,6 +8,8 @@ from prime_rl.transports.batch.filesystem import (
)
from prime_rl.transports.batch.types import (
MicroBatch,
MMImageRef,
MMRefs,
RoutedExperts,
SamplingMask,
TrainingSample,
@@ -47,6 +49,8 @@ __all__ = [
"ZMQBatchReceiver",
"BatchReceiver",
"BatchSender",
"MMImageRef",
"MMRefs",
"TrainingSample",
"MicroBatch",
"SamplingMask",
+10 -18
View File
@@ -1,13 +1,14 @@
import msgspec
# Encoded tensor: {dtype: "float32", shape: [...], data: <bytes>}.
# Mirrors verifiers' env-serve 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
class MMImageRef(msgspec.Struct, array_like=True, gc=False):
url: str
offset: int
length: int
class MMRefs(msgspec.Struct, array_like=True, gc=False):
images: list[MMImageRef]
# Routed experts are large per-token arrays. tolist() is too expensive, so we
@@ -42,15 +43,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
env_name: str
ref_logprobs: list[float] | None = None # reference-model logprobs (ref_kl component)
# 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
mm_refs: MMRefs | None = None
routed_experts: RoutedExperts | None = None
@@ -103,8 +96,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
ref_logprobs: list[float] | None = None
routed_experts: RoutedExperts | None = None
# See TrainingSample.mm_kwargs.
mm_kwargs: dict[str, EncodedTensor] | None = None
mm_refs: MMRefs | 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
+1 -1
View File
@@ -36,7 +36,7 @@ def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest() -> None
_record("math", "m0"),
_record("math", "m0"), # a third rollout of m0 exceeds group_size 2
_record("math", "m1"),
_record("math", "m9"), # no longer selected (num_examples shrank)
_record("math", "m9"), # no longer selected (select.limit shrank)
_record("code", "c0", ok=False), # errored: owed again
]
+16 -4
View File
@@ -14,12 +14,17 @@ from __future__ import annotations
import numpy as np
import pybase64
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateResponse, GenerateResponseChoice
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateResponse,
GenerateResponseChoice,
)
from vllm.entrypoints.serve.engine.protocol import UsageInfo
from vllm.multimodal.inputs import PlaceholderRange
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
from prime_rl.inference.vllm.serving_tokens import (
PrimeRlServingTokens,
_extract_mm_placeholders,
_GenerateRoutedExpertsCapture,
)
@@ -58,7 +63,7 @@ def test_serialize_routed_experts_uses_compact_raw_payload():
np.testing.assert_array_equal(decoded, routed_experts)
def test_generate_response_post_process_replaces_upstream_routed_experts():
def test_generate_response_post_process_preserves_prompt_metadata():
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3], "start": 0}
capture = _GenerateRoutedExpertsCapture(_empty_request_outputs())
capture.routed_experts[0] = compact_routed_experts
@@ -77,12 +82,19 @@ def test_generate_response_post_process_replaces_upstream_routed_experts():
)
processed = capture.post_process(response)
processed.prompt_token_ids = [10, 11, 12, 13]
processed.mm_placeholders = _extract_mm_placeholders(
{
"type": "multimodal",
"mm_placeholders": {"image": [PlaceholderRange(offset=1, length=2)]},
}
)
assert processed.choices[0].routed_experts == compact_routed_experts
assert processed.model == "test-model"
assert processed.usage == usage
# The compact object form must survive JSON serialization (the parent
# declares ``routed_experts`` as a base64 string).
payload = processed.model_dump(mode="json")
assert payload["choices"][0]["routed_experts"] == compact_routed_experts
assert payload["prompt_token_ids"] == [10, 11, 12, 13]
assert payload["mm_placeholders"] == {"image": [{"offset": 1, "length": 2}]}
assert payload["usage"]["total_tokens"] == 7
+39 -30
View File
@@ -4,7 +4,7 @@ import numpy as np
import pytest
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, TrainingSample
def _routed_experts(data, dtype=np.uint8):
@@ -16,11 +16,6 @@ def _routed_experts(data, dtype=np.uint8):
)
def _encoded(arr) -> EncodedTensor:
a = np.asarray(arr)
return EncodedTensor(data=a.tobytes(), shape=list(a.shape), dtype=str(a.dtype))
@pytest.fixture
def make_training_example():
def _make_training_example(
@@ -435,12 +430,8 @@ def test_prepare_sample_truncates_routed_experts():
def test_prepare_sample_truncates_mm_at_image_boundary():
"""Truncation never splits an image's placeholder block: it cuts to a whole-image boundary
and slices mm_kwargs to match, so image-token count stays == image-embedding count."""
# Two 2-token images (patches-per-token = 1): image-pad at indices 1,2 (img0) and 4,5 (img1).
"""Truncation never splits an image's expanded placeholder block."""
mm_token_type_ids = [0, 1, 1, 0, 1, 1, 0]
pixel_values = np.array([[1.0], [1.0], [2.0], [2.0]], dtype=np.float32) # img0=1.0, img1=2.0
grid = np.array([[1, 2, 1], [1, 2, 1]], dtype=np.int64)
sample = TrainingSample(
token_ids=[10, 11, 12, 13, 14, 15, 16],
mask=[False, False, False, False, False, True, True],
@@ -449,7 +440,12 @@ def test_prepare_sample_truncates_mm_at_image_boundary():
advantages=[0.0] * 6 + [1.0],
env_name="test-env",
mm_token_type_ids=mm_token_type_ids,
mm_kwargs={"pixel_values": _encoded(pixel_values), "image_grid_thw": _encoded(grid)},
mm_refs=MMRefs(
images=[
MMImageRef(url="data:image/png;base64,first", offset=1, length=2),
MMImageRef(url="data:image/png;base64,second", offset=4, length=2),
]
),
)
# seq_len=5 falls inside img1 (one of its two placeholders survives) -> drop img1 entirely.
@@ -458,12 +454,8 @@ def test_prepare_sample_truncates_mm_at_image_boundary():
assert len(mb.mm_token_type_ids) == len(mb.input_ids)
n_placeholders = sum(1 for t in mb.mm_token_type_ids if t)
assert n_placeholders == 2 # only img0's two placeholders remain
# No mismatch: placeholders == image embeddings, and only img0's pixels are kept.
assert mb.mm_kwargs["pixel_values"].shape == [2, 1]
assert mb.mm_kwargs["image_grid_thw"].shape == [1, 3]
kept = np.frombuffer(bytearray(mb.mm_kwargs["pixel_values"].data), dtype=np.float32)
assert kept.tolist() == [1.0, 1.0]
assert n_placeholders == mb.mm_kwargs["pixel_values"].shape[0] # ppt == 1 here
assert mb.mm_refs is not None
assert [(ref.url, ref.offset, ref.length) for ref in mb.mm_refs.images] == [("data:image/png;base64,first", 1, 2)]
def test_prepare_batch_packs_multimodal_with_text():
@@ -475,10 +467,7 @@ def test_prepare_batch_packs_multimodal_with_text():
advantages=[0.0, 1.0, 1.0],
env_name="mm-env",
mm_token_type_ids=[0, 1, 0],
mm_kwargs={
"pixel_values": _encoded(np.array([[1.0, 2.0]], dtype=np.float32)),
"image_grid_thw": _encoded(np.array([[1, 2, 2]], dtype=np.int64)),
},
mm_refs=MMRefs(images=[MMImageRef(url="data:image/png;base64,image", offset=1, length=1)]),
)
text_sample = TrainingSample(
token_ids=[20, 21],
@@ -492,14 +481,10 @@ def test_prepare_batch_packs_multimodal_with_text():
batches_per_gpu = prepare_batch(
rollouts=[mm_sample, text_sample],
seq_len=8,
num_train_workers=2,
num_train_workers=1,
bin_cost=build_bin_cost(None),
)
# FSDP requires uniform modality at each step index across ranks
for step_mbs in zip(*batches_per_gpu):
assert len({_is_multimodal_sample(mb) for mb in step_mbs}) == 1
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
assert len(real_batches) == 1
batch = real_batches[0]
@@ -507,12 +492,36 @@ def test_prepare_batch_packs_multimodal_with_text():
assert batch.sequence_lengths == [3, 2]
assert batch.position_ids == [0, 1, 2, 0, 1]
assert batch.mm_token_type_ids == [0, 1, 0, 0, 0]
assert batch.mm_kwargs is not None
assert batch.mm_kwargs["pixel_values"].shape == [1, 2]
assert batch.mm_kwargs["image_grid_thw"].shape == [1, 3]
assert batch.mm_refs is not None
assert [(ref.offset, ref.length) for ref in batch.mm_refs.images] == [(1, 1)]
assert batch.env_names == ["mm-env"] * 3 + ["text-env"] * 2
def test_split_to_align_splits_multimodal_bins():
def make_mm_sample(token: int) -> TrainingSample:
return TrainingSample(
token_ids=[token, token + 1, token + 2],
mask=[False, True, True],
logprobs=[0.0, -0.1, -0.2],
temperatures=[1.0, 1.0, 1.0],
advantages=[0.0, 1.0, 1.0],
env_name=f"mm-{token}",
mm_token_type_ids=[0, 1, 0],
mm_refs=MMRefs(images=[MMImageRef(url=f"data:image/png;base64,{token}", offset=1, length=1)]),
)
batches_per_gpu = prepare_batch(
rollouts=[make_mm_sample(10), make_mm_sample(20)],
seq_len=8,
num_train_workers=2,
bin_cost=build_bin_cost(None),
)
batches = _flatten_batches(batches_per_gpu)
assert len(batches) == 2
assert all(_has_loss_tokens(batch) and _is_multimodal_sample(batch) for batch in batches)
def test_prepare_sample_none_routed_experts():
"""When routed_experts is None, micro_batch.routed_experts is None."""
sample = TrainingSample(
+27 -78
View File
@@ -1,20 +1,11 @@
"""End-to-end integration test for the Qwen3-VL renderer path.
Walks a multimodal request through ``renderers.client.generate`` — the
tokenize + /inference/v1/generate features payload path the v1 train
client drives — 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.
"""
"""End-to-end request-shape check for raw Qwen3-VL inference."""
from __future__ import annotations
import asyncio
import base64
import json
from io import BytesIO
from pathlib import Path
from typing import Any
@@ -47,25 +38,31 @@ class _FakeOpenAI:
generate response so the parse-side of the flow runs.
"""
def __init__(self):
def __init__(self, image_pad_id: int):
self.calls: list[dict[str, Any]] = []
self.base_url = "http://fake-host:8000/v1"
self.image_pad_id = image_pad_id
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.
prompt_ids = list(body["token_ids"])
pad_index = prompt_ids.index(self.image_pad_id)
prompt_ids[pad_index : pad_index + 1] = [self.image_pad_id] * 4
payload = {
"request_id": "qwen-vl-e2e",
"prompt_token_ids": prompt_ids,
"mm_placeholders": {"image": [{"offset": pad_index, "length": 4}]},
"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},
{"token": "token_id:50", "logprob": -0.1},
{"token": "token_id:60", "logprob": -0.2},
{"token": "token_id:151645", "logprob": -0.3},
]
},
"finish_reason": "stop",
@@ -75,43 +72,30 @@ class _FakeOpenAI:
return httpx.Response(200, content=json.dumps(payload).encode())
def test_generate_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
"""Walk a Qwen3-VL multimodal turn through ``renderers.client.generate``
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.
"""
def test_generate_qwen3_vl_sends_raw_content_and_uses_expanded_prompt_ids():
from PIL import Image
from renderers.base import load_tokenizer
from renderers.client import generate
from renderers.qwen3_vl import Qwen3VLRenderer
from transformers import AutoProcessor
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
from vllm.entrypoints.scale_out.token_in_token_out.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)
renderer = Qwen3VLRenderer(tokenizer)
image_pad_id = tokenizer.convert_tokens_to_ids("<|image_pad|>")
fake = _FakeOpenAI()
fake = _FakeOpenAI(image_pad_id)
# ── Build a user message with an image (OpenAI content-part shape). ─
img = Image.new("RGB", (224, 224), color=(64, 128, 255))
buffer = BytesIO()
img.save(buffer, format="PNG")
image_url = f"data:image/png;base64,{base64.b64encode(buffer.getvalue()).decode()}"
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this picture?"},
# Embed the PIL image directly; the renderer consumes it as-is.
{"type": "image", "image": img},
{"type": "image_url", "image_url": {"url": image_url}},
],
}
]
@@ -125,51 +109,16 @@ def test_generate_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
sampling_params={"max_tokens": 16},
# Explicit cap so generate() skips the /v1/models discovery round-trip.
max_prompt_len=1_000_000,
process_multimodal=False,
)
)
# ── The HTTP body should carry a features payload. ──────────────────
assert len(fake.calls) == 1
body = fake.calls[0]["body"]
assert "features" in body, "generate 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 "features" not in body
assert body["content_parts"] == [{"type": "image_url", "url": image_url}]
assert body["token_ids"].count(image_pad_id) == 1
assert result["renderer_prompt_ids"] == body["token_ids"]
assert result["prompt_ids"].count(image_pad_id) == 4
assert result["mm_placeholders"] == {"image": [{"offset": body["token_ids"].index(image_pad_id), "length": 4}]}
assert result["completion_ids"] == [50, 60, 151645]
# multi_modal_data surfaces on the result so the caller can persist it.
assert result["multi_modal_data"] is not None
assert len(result["multi_modal_data"].mm_items["image"]) == 1
+6
View File
@@ -193,6 +193,12 @@ def test_icepop_is_an_optional_loss_with_validated_ratio_bounds():
with pytest.raises(ValidationError, match="ratio_low must not exceed ratio_high"):
TrainerConfig.model_validate({"loss": {"type": "icepop", "ratio_low": 5.0, "ratio_high": 0.2}})
assert TrainerConfig.model_validate({"loss": {"type": "ppo"}}).loss.type == "ppo"
assert TrainerConfig.model_validate({"loss": {"type": "cispo"}}).loss.type == "cispo"
with pytest.raises(ValidationError, match="max_importance_ratio must be at least ratio_high"):
TrainerConfig.model_validate({"loss": {"type": "ppo", "max_importance_ratio": 1.0, "ratio_high": 1.2}})
def test_moe_runtime_defaults_are_independent_from_dense_quantization():
config = TrainerModelConfig.model_validate({"quantization": {"type": "mxfp8"}})
+157 -1
View File
@@ -1,13 +1,15 @@
import pytest
import torch
from prime_rl.configs.trainer import CustomLossConfig, IcePopLossConfig, IPOLossConfig
from prime_rl.configs.trainer import CISPOLossConfig, CustomLossConfig, IcePopLossConfig, IPOLossConfig, PPOLossConfig
from prime_rl.trainer.rl.loss import (
IcePopLoss,
LossInputs,
LossOutputs,
_mismatch_kl_from_log_ratio,
compute_entropy,
compute_loss,
ref_kl_loss_fn,
setup_rl_loss_fn,
)
@@ -124,10 +126,164 @@ def test_icepop_loss_masks_extreme_ratio_without_nan():
result = IcePopLoss(IcePopLossConfig()).loss(inputs)
assert torch.equal(result.loss, torch.zeros_like(result.loss))
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
assert torch.equal(trainer_logprobs.grad, torch.zeros_like(trainer_logprobs.grad))
@pytest.mark.parametrize("config", [IPOLossConfig(kl_tau=0.01), IcePopLossConfig()])
def test_ipo_icepop_match_original_on_finite_ratios(config):
torch.manual_seed(23)
trainer_logprobs = (-8 * torch.rand(128, device="cuda")).requires_grad_()
inference_logprobs = -8 * torch.rand(128, device="cuda")
advantages = torch.randn(128, device="cuda")
loss_mask = torch.rand(128, device="cuda") > 0.3
weights = torch.rand(128, device="cuda")
inputs = LossInputs(trainer_logprobs, inference_logprobs, None, advantages, loss_mask, weights)
result = setup_rl_loss_fn(config).loss(inputs)
log_ratio = trainer_logprobs - inference_logprobs
ratio = log_ratio.exp()
if isinstance(config, IPOLossConfig):
keep = loss_mask & ((trainer_logprobs.exp() - inference_logprobs.exp()).abs() <= config.eps)
expected = (
(-(keep * config.adv_tau * advantages * ratio) + loss_mask * config.kl_tau * log_ratio.square()) * weights
).sum()
else:
keep = (
loss_mask
& (log_ratio.detach() >= torch.tensor(config.ratio_low, device="cuda").log())
& (log_ratio.detach() <= torch.tensor(config.ratio_high, device="cuda").log())
)
expected = (-(keep * config.adv_tau * advantages * ratio) * weights).sum()
torch.testing.assert_close(result.loss, expected, rtol=1e-5, atol=1e-5)
actual_grad = torch.autograd.grad(result.loss, trainer_logprobs, retain_graph=True)[0]
expected_grad = torch.autograd.grad(expected, trainer_logprobs)[0]
torch.testing.assert_close(actual_grad, expected_grad, rtol=1e-5, atol=1e-5)
def test_ipo_excludes_masked_tokens_and_caps_accepted_extreme_ratio():
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
ref_logprobs=None,
advantages=torch.ones(3, device="cuda"),
loss_mask=torch.tensor([True, True, False], device="cuda"),
)
result = setup_rl_loss_fn(IPOLossConfig()).loss(inputs)
torch.testing.assert_close(result.loss, torch.tensor(-1e4, device="cuda"))
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-1e4, 0.0, 0.0], device="cuda"))
def test_ref_kl_loss_stays_finite_with_extreme_ratios_and_masked_nan():
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
ref_logprobs=torch.tensor([-1.0, -1.0, float("nan")], device="cuda"),
advantages=torch.zeros(3, device="cuda"),
loss_mask=torch.tensor([True, True, False], device="cuda"),
)
result = ref_kl_loss_fn(inputs)
assert torch.isfinite(result.loss)
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
assert torch.isfinite(trainer_logprobs.grad).all()
def test_mismatch_kl_retains_small_positive_values():
log_ratio = torch.tensor([1e-4], device="cuda")
torch.testing.assert_close(
_mismatch_kl_from_log_ratio(log_ratio), torch.tensor([5e-9], device="cuda"), rtol=1e-3, atol=0
)
def test_ppo_clips_by_advantage_sign_and_keeps_unclipped_gradients():
ratios = torch.tensor([0.5, 0.9, 1.0, 1.1, 2.0, 2.0], device="cuda")
trainer_logprobs = (-10 + ratios.log()).requires_grad_()
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.full_like(trainer_logprobs, -10),
ref_logprobs=None,
advantages=torch.tensor([1.0, 1.0, 1.0, 1.0, 1.0, -1.0], device="cuda"),
loss_mask=torch.ones(6, dtype=torch.bool, device="cuda"),
)
result = setup_rl_loss_fn(PPOLossConfig()).loss(inputs)
torch.testing.assert_close(result.loss, torch.tensor(-2.7, device="cuda"))
torch.testing.assert_close(result.metrics["is_clipped"], torch.tensor(1 / 6, device="cuda"))
result.loss.backward()
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-0.5, -0.9, -1.0, -1.1, 0.0, 2.0], device="cuda"))
def test_ppo_caps_unbounded_negative_advantage_ratio():
trainer_logprobs = torch.tensor([-10.0, float("nan")], device="cuda", requires_grad=True)
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.tensor([-100.0, float("nan")], device="cuda"),
ref_logprobs=None,
advantages=torch.tensor([-1.0, 1.0], device="cuda"),
loss_mask=torch.tensor([True, False], device="cuda"),
)
result = setup_rl_loss_fn(PPOLossConfig()).loss(inputs)
torch.testing.assert_close(result.loss, torch.tensor(1e4, device="cuda"))
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([1e4, 0.0], device="cuda"))
def test_cispo_clips_detached_weight_without_dropping_gradients():
ratios = torch.tensor([0.1, 1.0, 5.0, 10.0], device="cuda")
trainer_logprobs = (-10 + ratios.log()).requires_grad_()
advantages = torch.tensor([1.0, -1.0, 1.0, 1.0], device="cuda")
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.full_like(trainer_logprobs, -10),
ref_logprobs=None,
advantages=advantages,
loss_mask=torch.ones(4, dtype=torch.bool, device="cuda"),
)
result = setup_rl_loss_fn(CISPOLossConfig()).loss(inputs)
expected_weight = torch.tensor([0.1, 1.0, 5.0, 5.0], device="cuda")
torch.testing.assert_close(result.loss, -(expected_weight * advantages * trainer_logprobs.detach()).sum())
torch.testing.assert_close(result.metrics["is_clipped"], torch.tensor(0.25, device="cuda"))
result.loss.backward()
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-0.1, 1.0, -5.0, -5.0], device="cuda"))
def test_cispo_handles_extreme_ratio_and_optional_lower_clip():
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.tensor(
[-10.0 - torch.log(torch.tensor(0.1)).item(), -100.0, float("nan")], device="cuda"
),
ref_logprobs=None,
advantages=torch.ones(3, device="cuda"),
loss_mask=torch.tensor([True, True, False], device="cuda"),
)
result = setup_rl_loss_fn(CISPOLossConfig(ratio_low=0.2)).loss(inputs)
assert torch.isfinite(result.loss)
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-0.2, -5.0, 0.0], device="cuda"))
def test_ce_component_matches_masked_nll():
trainer_logprobs = [torch.tensor([-0.1, -0.5, -0.2], dtype=torch.float32).cuda()]
inference_logprobs = [torch.zeros(3, dtype=torch.float32).cuda()]
+74
View File
@@ -0,0 +1,74 @@
import pytest
import torch
import torch.nn.functional as F
from prime_rl.trainer.models.layers.lm_head import IGNORE_INDEX, FusedOutputLinear, VanillaOutputLinear
from prime_rl.trainer.models.layers.lm_head_gemma import GemmaFusedOutputLinear, GemmaVanillaOutputLinear
B, S, H, V = 2, 7, 8, 37
SOFTCAP = 5.0
UPSTREAM = 0.25 # stands in for the 1 / grad_accum_steps scaling in the SFT loop
HEADS = {
"fused": (lambda chunk_size: FusedOutputLinear(H, V, chunk_size=chunk_size), None),
"vanilla": (lambda chunk_size: VanillaOutputLinear(H, V), None),
"gemma_fused": (lambda chunk_size: GemmaFusedOutputLinear(H, V, chunk_size=chunk_size, softcap=SOFTCAP), SOFTCAP),
"gemma_vanilla": (lambda chunk_size: GemmaVanillaOutputLinear(H, V, softcap=SOFTCAP), SOFTCAP),
}
def _reference_and_grads(hidden, weight, target_ids, loss_mask, softcap):
hidden = hidden.detach().clone().requires_grad_(True)
weight = weight.detach().clone().requires_grad_(True)
logits = hidden @ weight.t()
if softcap is not None:
logits = softcap * torch.tanh(logits / softcap)
loss = F.cross_entropy(logits.view(-1, V), target_ids.view(-1), reduction="none")[loss_mask.view(-1)].sum()
(loss * UPSTREAM).backward()
return loss.detach(), hidden.grad, weight.grad
def _inputs():
torch.manual_seed(0)
hidden = torch.randn(B, S, H)
weight = torch.randn(V, H)
target_ids = torch.randint(0, V, (B, S))
loss_mask = torch.rand(B, S) > 0.3
return hidden, weight, target_ids, loss_mask
@pytest.mark.parametrize("head", list(HEADS))
@pytest.mark.parametrize("chunk_size", [1, 5, 64])
def test_lm_head_labels_without_temperature_returns_summed_cross_entropy(head, chunk_size):
make_head, softcap = HEADS[head]
hidden, weight, target_ids, loss_mask = _inputs()
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask, softcap)
lm_head = make_head(chunk_size)
lm_head.weight = torch.nn.Parameter(weight.clone())
hidden = hidden.clone().requires_grad_(True)
out = lm_head(hidden, target_ids.masked_fill(~loss_mask, IGNORE_INDEX))
assert set(out) == {"loss"}
(out["loss"] * UPSTREAM).backward()
torch.testing.assert_close(out["loss"], reference, rtol=1e-5, atol=1e-5)
torch.testing.assert_close(hidden.grad, ref_hidden_grad, rtol=1e-5, atol=1e-5)
torch.testing.assert_close(lm_head.weight.grad, ref_weight_grad, rtol=1e-5, atol=1e-5)
@pytest.mark.parametrize("chunk_size", [1, 5, 64])
def test_fused_lm_head_with_temperature_keeps_logprob_path(chunk_size):
hidden, weight, target_ids, loss_mask = _inputs()
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask, None)
lm_head = FusedOutputLinear(H, V, chunk_size=chunk_size)
lm_head.weight = torch.nn.Parameter(weight.clone())
hidden = hidden.clone().requires_grad_(True)
out = lm_head(hidden, target_ids, temperature=torch.ones(B, S))
assert set(out) == {"logprobs", "entropy"}
loss = -out["logprobs"][loss_mask].sum()
(loss * UPSTREAM).backward()
torch.testing.assert_close(loss, reference, rtol=1e-5, atol=1e-5)
torch.testing.assert_close(hidden.grad, ref_hidden_grad, rtol=1e-5, atol=1e-5)
torch.testing.assert_close(lm_head.weight.grad, ref_weight_grad, rtol=1e-5, atol=1e-5)
+2 -1
View File
@@ -3,6 +3,7 @@ from types import SimpleNamespace
import torch
import torch.nn as nn
from prime_rl.multimodal.qwen_vl import QwenVLAdapter
from prime_rl.trainer.model import forward
@@ -35,11 +36,11 @@ def test_forward_passes_renderer_mm_token_type_ids_through():
position_ids,
seq_lens=torch.tensor([input_ids.shape[1]]),
mm_kwargs={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw},
mm_forward_policy=QwenVLAdapter.forward_policy,
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)
+56
View File
@@ -0,0 +1,56 @@
from types import SimpleNamespace
import pytest
import torch
from prime_rl.multimodal import get_multimodal_adapter
from prime_rl.multimodal.kimi_k25 import KimiK25Adapter
from prime_rl.multimodal.qwen_vl import QwenVLAdapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.transports.batch import MMImageRef, MMRefs
_IMAGE_URL = (
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
)
def _refs(length: int) -> MMRefs:
return MMRefs(images=[MMImageRef(url=_IMAGE_URL, offset=1, length=length)])
def test_qwen_adapter_materializes_and_validates_expansion():
class ImageProcessor:
merge_size = 1
def __call__(self, *, images, return_tensors):
assert len(images) == 1 and images[0].mode == "RGB" and return_tensors == "pt"
return {
"pixel_values": torch.ones(2, 3),
"image_grid_thw": torch.tensor([[1, 1, 2]]),
}
processor = SimpleNamespace(image_processor=ImageProcessor())
adapter = get_multimodal_adapter("qwen3_vl")
materialized = materialize_mm_refs(_refs(2), processor, adapter)
assert set(materialized.kwargs) == {"pixel_values", "image_grid_thw"}
assert materialized.forward_policy == QwenVLAdapter.forward_policy
with pytest.raises(ValueError, match="placeholder lengths differ"):
materialize_mm_refs(_refs(1), processor, adapter)
def test_kimi_adapter_materializes_sparse_image_position():
class ImageProcessor:
def preprocess(self, media, *, return_tensors):
assert len(media) == 1 and media[0]["type"] == "image"
assert media[0]["image"].mode == "RGB" and return_tensors == "pt"
return {
"pixel_values": torch.ones(4, 3),
"grid_thws": torch.tensor([[1, 2, 2]]),
}
processor = SimpleNamespace(image_processor=ImageProcessor())
materialized = materialize_mm_refs(_refs(1), processor, get_multimodal_adapter("kimi_k25"))
assert set(materialized.kwargs) == {"pixel_values", "grid_thws"}
assert materialized.forward_policy == KimiK25Adapter.forward_policy
Generated
+5 -5
View File
@@ -5049,7 +5049,7 @@ requires-dist = [
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
{ name = "prime-sandboxes", specifier = ">=0.3.0" },
{ name = "prime-sandboxes", specifier = ">=0.3.2" },
{ name = "prometheus-client", specifier = ">=0.20.0" },
{ name = "psutil", specifier = ">=7.0.0" },
{ name = "pyarrow", specifier = ">=21.0.0" },
@@ -5118,7 +5118,7 @@ requires-dist = [
{ name = "renderers", specifier = ">=0.1.11" },
{ name = "tomli", specifier = ">=2.2.1" },
{ name = "tomli-w", specifier = ">=1.2.0" },
{ name = "verifiers", specifier = ">=0.3.2.dev143" },
{ name = "verifiers", specifier = ">=0.3.2.dev152" },
]
[[package]]
@@ -5141,7 +5141,7 @@ train = [
[[package]]
name = "prime-sandboxes"
version = "0.3.0"
version = "0.3.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiofiles" },
@@ -5153,9 +5153,9 @@ dependencies = [
{ name = "pyqwest" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b6/46/2d118d8bbb901b729f3bc0678725eb28088d757a872db04cffa1492d0208/prime_sandboxes-0.3.0.tar.gz", hash = "sha256:c99075ed82a9bbfe5a453cee84b9f09565a7f6b07fd5ace072401cce59a1fe08", size = 132759, upload-time = "2026-09-18T01:32:31.263Z" }
sdist = { url = "https://files.pythonhosted.org/packages/f8/fe/69195c7c9e3d0f938e84ae54a8ffd386529019fb7635cad65d318e96271d/prime_sandboxes-0.3.2.tar.gz", hash = "sha256:6ded2497cbff8b5760e3f7897e1f00f2b789463daa397481620361bb148bfc45", size = 135266, upload-time = "2026-09-25T21:35:16.33Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5f/04/c77c7f260babf93978f912b85511e76f63a3cfa5bb11a8c34108177d5825/prime_sandboxes-0.3.0-py3-none-any.whl", hash = "sha256:19078ff508fa72de8f565422918faf367e2831ed8a2f26a5a6a98110e4062941", size = 71441, upload-time = "2026-09-18T01:32:30.062Z" },
{ url = "https://files.pythonhosted.org/packages/26/fc/6eefb673bbcbdd33105b5d14e8d7329a0b10a30c893ac8c74a8f2373a477/prime_sandboxes-0.3.2-py3-none-any.whl", hash = "sha256:d47f07fe90e662464ddd33468fa538f37c962e7bec5c2cbbbd170eb57d0ef89e", size = 72421, upload-time = "2026-09-25T21:35:14.99Z" },
]
[[package]]