Compare commits

...
Author SHA1 Message Date
Matej SirovatkaandGitHub c935497d71 fix sparse MLA backward tilelang pass (#2520)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-16 22:10:12 +02:00
halleriteandGitHub cd2f3daeb2 chore(renderers): advance to latest main (PR #38) (#2518)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-16 17:40:39 +02:00
897b935cae feat: turn prime-rl into a monorepo (#2507)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: turn prime-rl into a monorepo with submodules

Add verifiers, renderers, and research-environments as git submodules and
uv workspace members. Source edits in any of them now apply to prime-rl's
venv without a re-sync. Drops the PrimeIntellect PyPI index in favor of
installing env packages editable from the submodule trees.

- envs extra expanded from ~14 curated packages to ~98 env packages across
  verifiers/environments and research-environments/environments
- 11 envs excluded from the workspace due to upstream dependency conflicts
  (tau2 fork divergence, openenv-core unreleased, scicode protobuf clash,
  gem-wordle nltk pin, two envs with hardcoded verifiers git URLs)
- override-dependencies adds torch>=2.9.0 (to override verifiers[rl]'s
  torch<2.9 pin) and openenv-core (to avoid an unreleased version pin)
- scripts/install.sh now initializes submodules per-path so a missing
  private repo (e.g. configs/private) does not abort the install
- installation/config/entrypoints skills updated to mention submodules and
  the configs/private path

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

* chore: scope ruff to prime-rl source only

Submodules (verifiers, renderers, research-environments) have their own
ruff configuration and style. Excluding them from prime-rl's checks avoids
spurious CI failures on third-party code that we don't own.

- pyproject.toml: extend-exclude the three submodule paths
- style.yaml: don't fetch submodules in the ruff job (nothing to lint there)

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

* feat: add configs/private submodule pointing to research-configs

The private repo holds training/eval configs not meant for the public
prime-rl tree. People without access skip the submodule init via the
install script.

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

* chore: bump configs/private + lock CI to public submodules only

- configs/private: pulls in all 88 TOML configs from research-prod
- CI workflows: replace 'submodules: true' with explicit init of just
  verifiers/renderers/research-environments, so no CI run ever attempts
  to fetch the private configs/private submodule

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

* refactor: move submodules under packages/ + scope config tests

- packages/{verifiers,renderers,research-environments}: submodules now
  live alongside packages/prime-rl-configs as workspace members
- pyproject.toml: workspace members/exclude and ruff extend-exclude
  updated to the new paths
- CI workflows: revert to submodules: true (the GITHUB_TOKEN doesn't
  give access to configs/private, so it can't leak); the test fix
  below handles the in-tree case
- tests/unit/test_configs.py: skip configs/private/ when collecting
  TOMLs so private configs aren't loaded through public schemas
- scripts/install.sh: drop redundant -c url.insteadOf on clone; the
  later persistent git config line is what actually rewrites URLs
  for the submodule init step
- skills/installation/SKILL.md: point to packages/<submodule>/ paths

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

* refactor: scope envs extra to union of main + research-prod

Drop the "install everything" approach. The envs extra now installs only
the union of (1) envs prime-rl main shipped before this PR and (2) envs
referenced in research-prod TOMLs. The rest of the env packages remain
workspace members (installable via `uv add <name>`), but aren't pulled
in by `--extra envs`.

This trims the install set from ~95 to 27 packages — fewer transitive
dep conflicts to keep alive, and the install set actually matches what
our active configs use.

tau2-bench is un-excluded from the workspace and added as a source so
research-prod's tau2-bench configs install cleanly. The other tau2 forks
(tau2-bench-v1, tau2-synth, tau3-bench, tau3-bench-rlm) stay excluded —
they pull tau2 from divergent forks/commits that can't coexist in a
single venv.

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

* refactor: scope workspace members to installed envs only

The previous setup pulled every env subdir under packages/verifiers
and packages/research-environments into the workspace via globs, then
maintained an exclude list for envs that couldn't co-resolve. With the
envs extra now narrowed to the union of (prime-rl main + research-prod),
the workspace can list exactly those env packages and skip the rest —
no exclude list needed.

Also: extend-exclude in ruff config simplified to ["packages"] so
prime-rl's checks ignore anything under packages/. The submodules
have their own ruff configs.

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

* fix(ci): don't try to fetch the private configs/private submodule

The default GITHUB_TOKEN that actions/checkout uses is scoped to the
current repo only, so 'submodules: true' aborts with 404 when it
hits configs/private (the research-configs repo). Skip the checkout
action's submodule init and explicitly update just the three public
submodules.

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

* chore: strip noisy comments

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

* refactor: prune [tool.uv.sources] to installed env packages only

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

* fix(ci): rewrite SSH to HTTPS for submodule init

Runners have no SSH key, so cloning git@github.com:... fails. The
actions/checkout step handles this automatically when submodules: true
is set, but the explicit submodule update we run after submodules: false
doesn't. Set the insteadOf rewrite before the update.

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

* refactor: move third-party submodules from packages/ to deps/

packages/ is reserved for first-party prime-rl subpackages
(packages/prime-rl-configs). Vendored submodules live under deps/.
Ruff extend-exclude switches to deps/ so prime-rl-configs gets linted
again.

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

* fix(install): apply SSH->HTTPS rewrite in SKIP_CLONE path too

The rewrite was inside the else branch of the clone check, so users
running with SKIP_CLONE=1 without SSH access would hit the same submodule
init failures the rewrite was meant to prevent. Move it after the
clone/skip block so it runs in either path.

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

* fix(docker): copy deps/ and init submodules in release workflow

The submodule move from packages/ to deps/ left the Dockerfile and the
release workflow inconsistent: Dockerfile.cuda only COPYs packages/, and
release.yaml never initialized submodules. Add the deps/ COPY and the
explicit submodule init (matching the test workflows).

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

* docs: warn against --recursive submodule init, use explicit paths

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

* docs: remove note from submodule init step in README

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

* chore: pin renderers to v0.1.6 and verifiers to aa428f3

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

* chore(verifiers): patch out renderers git source for workspace compat

uv requires workspace members to reference each other as workspace
sources. verifiers@aa428f3 still has renderers as a git source; this
local patch removes it so the workspace resolves.

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

* chore(verifiers): advance to latest main

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

* chore(renderers): advance to latest main (v0.1.8.dev2)

Required by verifiers main which now pins renderers>=0.1.8.dev0.

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

* chore: revert ruff pre-commit hook to v0.13.0 to match CI

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 23:31:33 -07:00
81f9e9512b fix(ci): fix recurring failures + speedup ci (#2512)
* fix(wandb): respect WANDB_MODE env var in WandbMonitor

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

* fix(ci): disable W&B on PR runs to prevent ID collision and missing key crashes

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

* refactor(ci): rename test_rl.py to test_reverse_text.py and split into own CI job

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

* chore(ci): reduce reverse-text RL run to 15+5 steps

Reward plateaus at step 8-9 and stays above the 0.65 threshold from
step 8 onward. 20 steps was ~40% wasted compute.

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

* test: add average mismatch KL check to reverse-text integration test

Asserts the average mismatch KL across the last 10 trainer steps stays
below 0.01, catching numerical instability early without being brittle
to per-step noise.

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

* test(alphabet-sort): add mismatch KL guard, tighten reward threshold, reduce steps

Cut max_steps 10→8 (reward plateaus by step 7 at ~0.22, saves ~16s).
Tighten reward min_threshold 0.05→0.10 to catch regressions earlier.
Add avg mismatch KL check (last 5 steps ≤ 0.15) based on observed ~0.05-0.09
range; 0.15 gives CI headroom while catching numerical instability.

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

* test(reverse-text): rename wandb run, reduce mismatch KL check window

Rename W&B run from test-rl to test-reverse-text:{branch} to match the
test file rename. Reduce last_n_steps from 10→3 for the mismatch KL
check to make it less brittle (3 steps is sufficient to catch instability).

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

* chore: remove unused alphabet_sort_branch CI config

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

* fix(tests): update config paths after renames, fix double newline in error output

- configs/ci/integration/rl/ → reverse_text/
- configs/ci/integration/alphabet_sort/start.toml → alphabet_sort.toml
- sep="\n" → sep="" in check_no_error (readlines() lines already end in \n)

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

* fix(ci): respect WANDB_MODE in shared mode, align lora/alphabet-sort configs

- wandb.py: WANDB_MODE=disabled/offline now bypasses shared mode entirely
  (shared mode requires a server connection and can't work offline)
- reverse_text_lora: reduce steps 20+5 → 15+5 to match reverse_text config
- gpu_tests.yaml: rename rl_lora job → reverse_text_lora, update ignore list
- test_reverse_text_lora.py: use colon separator in wandb run name
- test_alphabet_sort.py: drop rl_output_dir wrapper, use output_dir directly;
  use colon separator in wandb run name

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

* refactor: rename test_rl_moe → test_reverse_text_moe, split into own CI job

- Rename test file and config dir (rl_moe → reverse_text_moe)
- Add reverse_text_moe as a dedicated CI job; exclude from base
- Update config paths, wandb name (colon separator), output subdirs (hf/custom)

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

* fix(test): add missing test function to test_reverse_text_moe

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

* fix(ci): update config paths for renamed sft/multi-run dirs, tail orch logs

- test_sft.py: sft/ → reverse_text_sft/
- test_sft_lora.py: sft_lora/ → reverse_text_sft_lora/
- test_reverse_text_multi_run.py: rl_multi_run/ → reverse_text_multi_run/
- gpu_tests.yaml: rename rl_multi_run job → reverse_text_multi_run, update
  ignore list to use test_reverse_text_multi_run.py
- rl.py: tail orchestrator.log instead of trainer.log on startup

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

* refactor(tests): rename CI integration tests and configs to use descriptive names

Rename test files and config directories from generic rl/sft/rl_lora/rl_multi_run
prefixes to descriptive reverse_text/alphabet_sort/reverse_text_sft/etc names.
Flatten alphabet_sort config from a directory to a single file.

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

* chore(ci): reduce SFT integration test steps from 10+10 to 5+5

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

* chore(ci): simplify CI - always offline W&B, drop OPENAI_API_KEY, fix wandb names

- WANDB_MODE hardcoded to offline (removes flaky conditional logic)
- Remove OPENAI_API_KEY (not referenced in code, client defaults to EMPTY)
- Remove WANDB_API_KEY (no longer needed with offline mode)
- Drop -m gpu from integration test args (all integration tests already carry the mark)
- Standardize wandb run names to use colon separator in sft/sft_lora/multi_run tests

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

* chore(ci): replace base integration job with explicit sft matrix jobs

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

* chore: ignore .claude/scheduled_tasks.lock

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

* chore: untrack deps/renderers/_version.py, add to gitignore

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

* chore(ci): use dynamic matrix to avoid expanded skipped entries on draft PRs

Static matrix jobs get pre-registered by GitHub even when skipped, showing 8
individual "Skipped" entries on draft PRs. A dynamic matrix (output from a prior
job) can't be pre-expanded, so GitHub shows a single entry instead.

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

* Revert "chore(ci): use dynamic matrix to avoid expanded skipped entries on draft PRs"

This reverts commit 0e835ed63ef467f8a33018f809b8ab182ebb2c56.

* chore(ci): disable uv cache on GPU jobs

The post-job cache save tars multi-GB pytorch/CUDA packages, adding 3+ min of
overhead. The save cost exceeds the restore benefit for large GPU dependencies.

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

* chore: remove deps/renderers/_version.py from gitignore

Handled in a separate PR.

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

* chore(ci): run integration tests with -vvs

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

* only 5 alphabet sort steps [skip ci]

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 22:25:40 -07:00
d4385029c8 feat(sft): accept tool_defs column alongside tools (#2494)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(sft): accept tool_defs column alongside tools

The verifiers rollout format stores tool definitions under tool_defs
(list[dict] or list[str]); SFT was only reading the OAI tools column
(single JSON string), so rollout-derived datasets trained with an empty
system block — a major training/inference mismatch since vLLM injects
the tool definitions at inference time.

Falls back to tool_defs when tools is absent and parses both shapes.

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

* accept both JSON-encoded and pre-parsed shapes for tools/tool_defs

Either key may now arrive as: a JSON-encoded list string, a list[dict],
or a list[str] of JSON-encoded tool dicts. Result is always list[dict].

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

* narrow accepted shapes to str | list[dict]

list[str] (each item a JSON-encoded tool) wasn't a real-world shape; drop it.

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

* simplify tools lookup

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

* normalize tool defs to OAI shape before chat template

The orchestrator does this conversion in _convert_tools_to_oai_format
(trajectories.py); SFT was passing the raw verifiers shape directly. That
worked for chat templates that handle both shapes (e.g. NemotronH) but
would silently render an empty <tools> block on most others.

Detects verifiers-shape tools (top-level name/description/parameters) and
wraps them as {type: 'function', function: {...}}. Pre-wrapped OAI tools
pass through unchanged.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
2026-05-15 15:27:50 -07:00
samsjaandGitHub c654dc1d4d log masked advantage sign rates (#2481)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-14 19:17:32 -07:00
6ba37c2c21 feat: opt-in renderer-based tokenization for SFT (#2496)
Release / Push CUDA image to Docker (push) Canceled after 0s
Adds `use_renderer` flag to SFTConfig, mirroring the RL path. When enabled,
SFTDataset tokenizes via `renderers.base.build_training_sample` instead of
the incremental Jinja `apply_chat_template` path, fixing multiturn sample
drops and position-dependent template crashes.

Co-authored-by: Eric Botti <ericjbotti@gmail.com>
2026-05-14 23:25:10 +02:00
halleriteandGitHub 458b16ef47 Revert "feat: opt-in renderer-based tokenization for SFT (#2493)" (#2495)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit b5f196a9c5.
2026-05-14 23:14:24 +02:00
halleriteandGitHub b5f196a9c5 feat: opt-in renderer-based tokenization for SFT (#2493)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-14 23:13:00 +02:00
6dda4a1466 chore: tell agents not to edit optimization_dtype / reduce_dtype (#2491)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 10:47:56 -07:00
halleriteandGitHub fa55779272 Fix disagg: thread kv_transfer_params into engine for /inference/v1/generate (#2490)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-14 17:56:28 +02:00
b2ba40b5eb Patch vLLM layerwise reload alias-buffer handling (#2482)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Patch vLLM layerwise alias-buffer reload

* Remove layerwise buffer copy-back guard

* Skip alias buffers during layerwise copy-back

* ruff

* Skip absent buffers during layerwise copy-back

* Precompute layerwise alias storage pointers

* ruff

* simpler fix for layerwise alias buffer reload (#2486)

* meow

* dont think theres a need for this singletoning behavior?

* Simplify layerwise alias-buffer patch to copy-back-only

Drop the capture-time skip and the absent-buffer guard; detect aliasing
at copy-back via parameter storage pointers (recursing into submodules
so views like mixer.conv_weights → mixer.conv1d.weight are caught).
_place_kernel_tensors then restores the original aliased buffer, which
trivially reflects the parameter's freshly-loaded storage.

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

* Apply suggestion from @Jackmin801

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 05:36:14 +08:00
samsjaandGitHub e4330c2d2c add poolside laguna custom model (#2479)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-12 21:13:34 -07:00
4a6b45487f feat(orchestrator): drop groups after max_error_reschedule_attempts (#2459)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): drop groups after max_error_reschedule_attempts

Adds a per-group retry cap to the rollout scheduler. Each `GroupState`
now tracks a `failed_attempts` counter, incremented whenever a batch of
rollouts comes back with at least one errored or empty trajectory. When
the counter reaches `orchestrator.max_error_reschedule_attempts`, the
group is dropped from the current step's batch (cancelling any
in-flight rollouts for that group) and the rest of the batch proceeds.

Default is `None` (retry indefinitely, current behavior). Set a value
to unblock single-example hangs in agent envs (e.g. a sandbox poll
that times out at 60s on every retry — that loop was previously
infinite because the AgentError surfaces as `rollout["error"]`, which
the scheduler treats as a normal "reschedule the group" signal with no
give-up condition).

Minimal local re-implementation of the abandoned PR #2076 — keeps the
retry-cap behavior without the larger GeneratedBatch / variable
group-size / deferred-scoring refactor in that PR.

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

* fix(orchestrator): report and clear dropped_groups_by_env in metrics

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

* fix(orchestrator): off-by-one in max_error_reschedule_attempts check

failed_attempts is incremented on the initial failure, so >= caused the
group to be dropped without any reschedule. Use > so max_attempts
matches the configured number of retries.

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

* chore(orchestrator): include last failure reason in drop log

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

* fix(orchestrator): count failed rounds, not failed rollouts, for drop cap

For non-group-scoring envs, each individual rollout returns as a
separate task, so a single failed dispatch round could increment
failed_attempts up to rollouts_per_example times and trip the cap before
any retry happened. Tag in-flight requests with a dispatch round and
dedupe failures by round.

Also switch the drop check to `>=` and reword the config description so
the field's semantics match — the group is dropped once this many of
its dispatch rounds have returned errored/empty rollouts.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 18:28:13 -07:00
minh hoangandGitHub 024abb2043 bump prime cli to 0.6.4 (#2480)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-12 16:09:18 -07:00
rasdaniandGitHub 5b11b8de33 Fix SLURM cleanup self-kill patterns (#2477)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-12 21:33:51 +02:00
halleriteandGitHub 7c434ec267 feat: unify renderer + teacher endpoints onto vLLM 0.20 /inference/v1/generate (#2408)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-11 19:19:40 +02:00
469a4e6714 chore: bump vllm to 0.20.2 (#2468)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 08:36:40 -07:00
319af10769 Fix: add layerwise as default (#2467)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Fix: add layerwise as default

* Fix; cleanup

* fix(filesystem): apply layerwise reload to filesystem transport

Mirror the same fix as the NCCL path: replace
`model.load_weights + process_weights_after_loading` with
`load_weights_checkpoint_layerwise`. Without it, MoE
+ filesystem transport hits the same
`Current vLLM config is not set` AssertionError at
`worker/filesystem.py` on the first weight update.

Verified end-to-end on Qwen3-30B-A3B-Thinking-2507 + reverse-text:
filesystem broadcast returns 200 OK, orchestrator step 2 consumed
new weights cleanly (off-policy level 1, reward 0.3583), trainer
steady-state at ~29K tok/s, MFU 21%, no NaN, no errors.

---------

Co-authored-by: hallerite <git@hallerite.com>
2026-05-10 16:10:09 +02:00
Matej SirovatkaandGitHub d11fc90469 Fix: third_party to .gitignore (#2463)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-09 15:18:24 -07:00
Matej SirovatkaandGitHub c9a4b3b199 Feat: kv offload for non-PD (#2457)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-09 09:17:44 -07:00
Matej SirovatkaandGitHub a252057978 [Weight Transfer]: Support quantize_in_weight_transfer + EPLB (#2454)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: support EPLB with quantize_in_weight_transfer

* Feat: EPLB+quantize_in_weight_transfer

* Nit: style
2026-05-09 18:07:27 +02:00
Matej SirovatkaandGitHub 429c1bb5e5 Nit: pass hybrid lb for non-pd DP case (#2455)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-09 18:07:17 +02:00
Matej SirovatkaandGitHub efb874b734 [Inference]: vLLM 20 + Prod Run compat (#2456)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: update vllm

* Fix: silu mul patch address overflow (DPEP16)

* Feat: fix weight transfer

* Chore: pin DeepEP DeepGEMM release wheels

* nit: style
2026-05-09 18:07:06 +02:00
Matej SirovatkaandGitHub 2171368063 [FP8]: Upcast addresses to int64 to avoid overflow (#2453)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Fix: upcast to i64

* Fix: 1 more upcast
2026-05-09 08:59:06 -07:00
Jackmin801andGitHub 7b7bde1fa0 drop ampere in fa4 (#2452) 2026-05-08 18:01:22 -07:00
Jackmin801andGitHub 0fe673c23c pin vllm down to cu129 (#2450)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-08 17:28:27 -07:00
minh hoangandGitHub 84ccb9507d fix(inference): make liveness timeout configurable with a 30s default (#2449)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make liveness timeout configurable; set default to 30s

* server config already sets up the default 30s value
2026-05-08 14:27:23 -07:00
samsjaandGitHub 09e403b4a4 Revert "Revert "bump vllm version (#2427)" (#2437)" (#2448)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit bb522cce53.
2026-05-08 12:28:05 -07:00
7da26cd651 fix(trainer): escape dots in FP8 ignore patterns (#2442)
Release / Push CUDA image to Docker (push) Canceled after 0s
`replace_linear_with_fp8_blockwise_linear` uses `re.search(pattern, name)`
to decide which linears to keep in BF16. The default ignore list had
"mlp.gate." which is a regex where `.` matches any character. As a
result, dense MLPs' `mlp.gate_proj` (the trailing `.` matched `_`)
were being skipped from FP8 conversion alongside the MoE router gate.

For FP8 inference checkpoints (e.g. `zai-org/GLM-5-FP8`) where the
dense MLP gate_proj IS quantized to FP8, this leaves the trainer's
copy in BF16 — causing hidden-state divergence in early dense layers
that propagates through the MoE router and inflates trainer↔inference
KL mismatch.

Escape the dots (`mlp\.gate\.`) so the pattern matches only the actual
MoE router gate (`mlp.gate.weight`, `mlp.gate.e_score_correction_bias`)
and not `mlp.gate_proj` / `mlp.gate_up_proj`.

Verified on a 12-node GLM-5.1-FP8 RL run: trainer log now reports
`Replaced 477` (was 474) with `mlp.gate_proj` no longer in the
`first skipped(name)` list.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 22:45:36 -07:00
5f2c004184 feat(inference): fp32 lm_head via native bf16xbf16 -> fp32 mm (#2441)
Release / Push CUDA image to Docker (push) Canceled after 0s
Alternative implementation of fp32 lm_head proposed by @Jackmin801 on
PR #2438: use torch.mm(..., out_dtype=torch.float32) (PyTorch >= 2.10) so
the matmul accumulates and emits fp32 directly without zero-padding the
bf16 operands or maintaining a separate fp32 weight copy.

The win is purely in the epilogue: F.linear(bf16, bf16) accumulates in
fp32 internally on tensor cores but truncates the output to bf16 before
returning. Native out_dtype=fp32 keeps the full mantissa for the
downstream softmax/sample.

Removes the cached fp32 weight + tensor-version invalidation logic from
PR #2438 — not needed when there's no separate fp32 copy.

Wired identically to PR #2438: inference.enable_fp32_lm_head config flag
-> additional_config["fp32_lm_head"] -> captured on LogitsProcessor.__init__
-> per-instance flag read in _get_logits.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 22:44:25 -07:00
c0d896f3f8 fix(gpt-oss): document temperature arg in GptOssForCausalLM.forward (#2439)
Release / Push CUDA image to Docker (push) Canceled after 0s
`temperature` is part of the forward signature but had no docstring entry,
which trips the auto_docstring check. Add a description matching the convention
used in the other model files.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 18:35:55 -07:00
samsjaandGitHub bb522cce53 Revert "bump vllm version (#2427)" (#2437)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit 3b01ce9d48.
2026-05-07 17:12:22 -07:00
95af0118db feat(cp): add ulysses all-to-all CP path alongside ring (#2418)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(cp): add ulysses all-to-all path alongside ring

Adds a `model.cp_style` arg ("ring" default | "ulysses") that selects
between the existing ring CP and a new Ulysses all-to-all variant.

Ulysses redistributes Q/K/V via two seq <-> head all-to-alls and runs
vanilla flash attention on the full sequence with H/cp heads, so the
attention kernel does not need to be CP-aware. Works OOB with FA2/3/4,
linear attention, mamba, etc.

Constraint: cp_size must divide both num_attention_heads and num_kv_heads.

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

* chore: ruff format ulysses_attn.py

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

* fix(cp): refuse cp_style='ring' on linear-attn / Mamba models

Ring CP is a softmax-attention algorithm (sequence ring all-gather of K/V).
It cannot correctly drive non-softmax kernels (Qwen3.5 DeltaNet linear-attn,
NemotronH Mamba). Previously the linear-attn CP setup hooks were called
unconditionally under ring, which silently mixed two different CP layouts
in the same model.

Now:
- Refuse cp_style='ring' at startup if the model has any linear/SSM
  attention layer, with a clear error pointing at cp_style='ulysses'.
- Only call setup_hybrid_cp / setup_nemotron_h_cp under cp_style='ulysses'.
- setup_sparse_mla_cp (still softmax) keeps working under both.

Ulysses' all-to-all is purely on Q/K/V tensors, so the linear/SSM kernel
runs unchanged on a sequence shard — this is the correct CP path for
hybrid models.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:05:21 -07:00
d7b3ae203c feat: agentic length-penalty ablations — weighted shaping over tool-response tokens (#2377)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: weighted length shaping over completion + tool-response tokens

Generalize the length_shaping brevity bonus to a weighted combination of
model-completion tokens and tool-response tokens, so the brevity signal
can penalize tool-response token consumption (read from a harness metric
like rlm_total_tool_response_tokens) independently from model output.

- Add `tool_response_lengths` to AdvantageInputs (optional)
- Add `length_shaping_completion_weight` (default 1.0) and
  `length_shaping_tool_response_weight` (default 0.0) to
  DefaultAdvantageConfig — defaults preserve existing behavior.
- effective_lengths = a * completion + b * tool_response, fed to the
  existing correctness-gated brevity bonus.
- Add get_tool_response_len() that pulls *_total_tool_response_tokens
  from rollout metrics and returns 0 if absent (no-op for non-tool envs).

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

* fix(advantage): guard zero-cost division in efficiency shaping

When `mean_correct_cost == 0` (e.g. tool-only shaping without a harness
metric, or all-zero turn counts), `costs / mean_correct_cost` was 0/0 →
NaN advantages. `clamp(0, 1)` doesn't recover from NaN.

Detect zero mean and zero out the bonus, falling back to plain GRPO for
that group. Also a latent bug for `length_penalty="turns"` if a group
ever had all empty trajectories — same fix covers it.

* fix(advantage): constrain weights to finite non-negative; cast rewards to float

- Config: add `ge=0, allow_inf_nan=False` on both weight fields. Negative
  weights would invert the shaping (reward more tokens); inf/nan poison
  advantages downstream.
- `default_advantage_fn`: cast rewards to float32. The previous
  `dtype=rewards.dtype` for costs truncated fractional weighted sums when
  rollouts emitted integer rewards. Casting also fixes a latent crash on
  int rewards in `_efficiency_shaping`'s `rewards.mean()` (Long unsupported).

* refactor(advantage): discriminated length_penalty sub-config

Replace the scalar `length_penalty: Literal["tokens","turns"] | None` plus
two flat weight fields with a discriminated union on `type`:

  TokensLengthPenaltyConfig(completion_weight, tool_response_weight)
  TurnsLengthPenaltyConfig

Default for the tokens config is (1.0, 1.0), making total-context shaping
the default when token-shaping is enabled. The discriminator pattern
matches the existing AdvantageConfig (default | custom) shape and keeps
weight semantics scoped to the variant they apply to — no cross-field
validator needed.

CHANGELOG entry added.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:04:51 -07:00
229391fa27 Feat: deep-gemm-fp8 (#2166)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: deep-gemm-fp8

* Feat: cleanup

* nit

* Style

* Feat: works now

* Feat: fp8 grouped gemm works

* Fix: skip unaligned + qwen3.5

* chore(deep_gemm): rebuild d30fc36 wheel against torch 2.11 / cu128

The wheel was built against torch 2.10 + cu128; the merge from main bumped
torch to 2.11.0+cu128 / vllm to 0.20.1, breaking ABI compat with the old
build. Rebuilt via scripts/install_deep_gemm.sh --wheel-dir tools/wheels.

Also updates install_deep_gemm.sh:
  - default ref pinned to d30fc36 (was 477618c)
  - script header documents the wheel-dir flow used to refresh tools/wheels/

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

* chore(deep_gemm): pin to v0.5.0 release URL (uploaded d30fc36 wheel)

The d30fc36 wheel is now hosted on the v0.5.0 GitHub release alongside the
existing 477618c build, so we can drop the local path-based pin.

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

* fix(fp8): make deep_gemm import optional for CPU-only envs

deep_gemm only ships CUDA wheels; importing prime_rl on a CPU box currently
fails with ImportError before any FP8 path is even touched. Wrap both call
sites in try/except so the import is graceful — actual deep_gemm calls live
inside autograd Function bodies that only run on GPU anyway.

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

* feat(fp8): wire FP8 grouped GEMM into NemotronH; assert disabled for GPT-OSS

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

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:04:19 -07:00
minh hoangandGitHub 1e9a3e9196 fix: exit early for unsupported platforms on install.sh (#2431)
Release / Push CUDA image to Docker (push) Canceled after 0s
* install: check platform and exit early on unsupported platforms

* handle stripped ansi escape prefix for color output

* Revert "handle stripped ansi escape prefix for color output"

This reverts commit b8850f73893c3189d86848fb3849986275a12963.
2026-05-06 11:51:24 -07:00
3b01ce9d48 bump vllm version (#2427)
Release / Push CUDA image to Docker (push) Canceled after 0s
* bump vllm version

* fix cuda version pin

* correct flash attn

* chore: drop monkey patches now upstream in vLLM 0.20

vLLM 0.20.1 ships fixes for the LoRA+MoE+DP>1 corruption (#40338) and
the OffloadingConnector CPU block-count miscalculation (#39617), so
remove the local monkey patches and the corresponding call site in
transformers_v5_compat. Refresh stale "vLLM 0.16/0.19" comments.

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

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 11:01:05 -07:00
38b524925d fix(configs): use FutureWarning so config deprecations are visible (#2429)
Release / Push CUDA image to Docker (push) Canceled after 0s
DeprecationWarning is silenced by default outside __main__, so users
never saw notices for max_tokens / [[orchestrator.env]] / [orchestrator.sampling].
FutureWarning is shown under default filters and is the right category
for "will be removed in a future release" notices.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 22:42:03 -07:00
d62c7539e4 feat: split prime-rl-configs into separate workspace package (#2416)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: split prime-rl-configs into separate workspace package

Goal: make `prime_rl.configs.*` pip-installable on its own (~13 deps)
without pulling the full GPU/ML stack (~329 deps).

Layout — uv workspace with two members:
- root `prime-rl` (heavy stack, unchanged location at src/prime_rl/)
- `packages/prime-rl-configs/` (slim wheel, owns prime_rl.configs.*
  and the small slim utils: utils/config.py, utils/logger.py,
  utils/validation.py)

Mechanism — both wheels contribute to a PEP 420 namespace package
`prime_rl/` (no __init__.py at the top level, nor under utils/). Each
wheel ships disjoint files; pip merges them at install time.
- `pip install prime-rl-configs` → schema only
- `pip install prime-rl` → full stack (depends on prime-rl-configs)

Code changes:
- Move src/prime_rl/configs/ → packages/prime-rl-configs/src/prime_rl/configs/
- Move utils/{config,logger,validation}.py → packages/prime-rl-configs/src/prime_rl/utils/
- Move rgetattr/rsetattr from utils/utils.py → utils/config.py (was the
  only heavy import the configs needed; this breaks the dep)
- Replace `Path(prime_rl.__file__).parent / "templates"` (None on a
  namespace package) with `find_package_resource("templates")` which
  iterates `prime_rl.__path__` to locate the heavy wheel's data dir
- Delete src/prime_rl/__init__.py; move its `import _compat` side-effect
  into the actual entrypoint scripts (orchestrator.py, entrypoints/rl.py,
  entrypoints/sft.py — trainer/{rl,sft}/train.py already had it)
- Dockerfile.cuda: also COPY packages/ so the workspace member is
  available during `uv sync`

Verified:
- `uv sync --all-extras` resolves and builds both wheels
- 333 unit tests pass (none touched)
- all 6 entrypoints (rl/sft/trainer/orchestrator/env-server/inference)
  load and print --help
- fresh `pip install ./packages/prime-rl-configs` (no extras) installs
  13 packages, imports all configs, parses examples/.../rl.toml with a
  [slurm] section, and sys.modules contains zero of:
  torch / transformers / vllm / wandb / ring_flash_attn / verifiers /
  prime / datasets / liger_kernel

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

* ci: add slim-configs-install job to cpu_tests

Fresh venv → `uv pip install ./packages/prime-rl-configs` → assert that:
- all 6 config modules import
- sys.modules contains zero of: torch, transformers, vllm, wandb,
  ring_flash_attn, verifiers, prime, datasets, liger_kernel
- find_package_resource("templates") returns None (the heavy wheel's
  data dir isn't shipped on slim)
- a real example config with [slurm] parses; template_path stays None

Guards the slim-import contract against future regressions where
something under prime_rl.configs.* might re-introduce a heavy import.

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

* chore(ruff): mark prime_rl as first-party for isort

Without this, ruff's import sorter classifies prime_rl.configs.* as
third-party (because those files now live under packages/, not src/),
and groups them apart from prime_rl.utils.* / prime_rl.trainer.* etc.

Telling ruff that prime_rl is a single first-party namespace keeps
all prime_rl.* imports in one block, regardless of which workspace
wheel ships the submodule.

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

* refactor(configs): drop logger dep, use stdlib warnings

Configs were doing get_logger().warning(...) at validation time, which
forced loguru into the slim wheel and a logger.py copy alongside it.
None of these warnings need a configured logger — they're config-time
deprecation notices and misconfiguration hints. Stdlib `warnings.warn`
covers the use case without any runtime infrastructure.

- Replace 7 `get_logger().warning(...)` call sites in configs/rl.py and
  configs/orchestrator.py with `warnings.warn(...)`. Deprecation messages
  use `DeprecationWarning`; the rest use the default `UserWarning`.
- Move `prime_rl/utils/logger.py` back to the heavy `prime-rl` wheel
  (`src/prime_rl/utils/`).
- Drop `loguru` from `prime-rl-configs` deps; add it to `prime-rl`.
- Slim CI: stop importing `prime_rl.utils.logger` (it's no longer in the
  slim wheel) and add `loguru` to the forbidden-modules list.

Slim install drops from 13 to 12 packages.

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

* fix: import _compat in remaining ring_flash_attn entry points

Integration tests like tests/integration/test_sft_lora.py import
prime_rl.trainer.weights, which transitively pulled ring_flash_attn
(via models layer / utils.cp) without prime_rl._compat ever running,
producing the ImportError that failed CI.

Add `import prime_rl._compat` to the two remaining top-level
ring_flash_attn import sites: utils/cp.py and trainer/models/layers/
ring_attn.py. The trainer entrypoints (rl/sft/train.py) already had
this import.

`# ruff: noqa: I001` on both files because ruff's isort, with
known-first-party=prime_rl, sorts the prime_rl._compat first-party
import after the third-party ring_flash_attn import — which defeats
the patch ordering. The shim must run before ring_flash_attn is
imported, so the file order is intentional.

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

* fix: pin pydantic-config to git fork in slim package

The PyPI package named `pydantic-config` is a different project that
doesn't expose BaseConfig / cli (those are in samsja's fork). Without
this pin, plain `pip install prime-rl-configs` resolves the wrong
package and configs.* imports crash with:

  ImportError: cannot import name 'BaseConfig' from 'pydantic_config'

uv pip install accidentally worked because it reads the root workspace
pyproject.toml's [tool.uv.sources] when installing from a git
subdirectory, which redirected pydantic-config to the fork. Plain pip
doesn't do that — it only sees the leaf pyproject.toml.

PEP 508 direct reference works for both uv and pip.

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

* ci: install slim wheel from /tmp to bypass workspace source discovery

The previous step did `uv pip install ./packages/prime-rl-configs` from
inside the cloned repo. uv silently reads the root pyproject.toml's
[tool.uv.sources] in that case and applies the pydantic-config git
override — masking the issue an external pip-only user would hit.

Build the wheel into /tmp/slim-wheel and install it from /tmp so uv
can't discover the workspace. This catches dep-resolution bugs that
only show up in a real external install.

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

* docs: explain dist-name vs import-path in slim package README

Distribution name (`prime-rl-configs`) and import path
(`prime_rl.configs.*`) are different — easy to trip on.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 21:59:37 -07:00
Jackmin801andGitHub edf41113fe Revert "chore: bump vllm 0.20.1 + migrate cu128 → cu130 (#2403)" (#2426)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit bcac552c3f.
2026-05-05 21:12:11 -07:00
bcac552c3f chore: bump vllm 0.20.1 + migrate cu128 → cu130 (#2403)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump vllm 0.19 → 0.20

vLLM 0.20.0 lands MoE LoRA refactor (#40338) and CPU offloading fix
(#39617) upstream — drop now-redundant prime-rl monkey patches:
monkey_patch_fused_moe_lora_dp and monkey_patch_offloading_connector_
cpu_block_count.

PyPI vllm-0.20.0 is built against CUDA 13 and links libcudart.so.13;
our env is pytorch-cu128 (CUDA 12). Pin vllm to the cu129 wheel from
wheels.vllm.ai (libcudart.so.12) for binary compat. Promote
torchvision/torchaudio to direct deps so [tool.uv.sources] pins them
to pytorch-cu128 (cu13 transitive resolution would break torch ops).

Add vllm = false exemption to the 7-day exclude-newer cooldown since
0.20.0 was published 2026-04-27, inside the window.

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

* feat: migrate cu128 → cu130

Now that vllm 0.20.0 is the floor and PyPI ships it for CUDA 13
natively, drop our cu129-wheel detour and move the rest of the
GPU stack to cu130:

- pytorch-cu128{,-test} indices → pytorch-cu130{,-test}
  torch/torchvision/torchaudio/flash_attn_3 follow.
- flash-attn extra: bump to v0.9.4 cu130torch2.11 prebuilt wheel.
- Drop the wheels.vllm.ai cu129 URL pin — PyPI vllm 0.20.0 (cu13)
  is now the default.
- override-dependencies: nvidia-cudnn-cu12 → nvidia-cudnn-cu13.

Lockfile pulls torch 2.11.0+cu130, torchvision/torchaudio 0.26.0/2.11.0
+cu130, flash-attn 2.8.3+cu130torch2.11, vllm 0.20.0, and swaps every
nvidia-*-cu12 transitive for its cu13 counterpart.

Not addressed in this change (draft until ready):
- Host driver upgrade: 575.64.03 → ≥580.65.06 required for CUDA 13.
- samsja prebuilt wheels (deep-ep, deep-gemm, nixl-cu12) still
  point at cu12 builds — runtime-incompatible with cu13. Need
  rebuilds before merging.

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

* chore(deps): bump vllm 0.20.0 → 0.20.1

Picks up the DeepSeek V4 patch release and a handful of bug fixes
(CUDA-graph max_num_batched_token, num_gpu_blocks_override, cumem
expandable_segments, structured-output kwargs). Strict patch — none
of the kept/dropped monkey-patches are touched.

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

* chore(deps): ship cu13 disagg wheels, switch nixl to PyPI

deep-ep / deep-gemm: rebuilt against CUDA 13.1, stamped with `.cu13`
local version, uploaded alongside the existing cu12 wheels at v0.5.0.

nixl: dropped the URL pin entirely. PyPI `nixl-cu13` 1.0.1 ships UCX
auditwheel'd with mlx5_ib / rdmacm / cuda transports — verified
end-to-end with a 2-node basic_two_peers.py run that picked rc_mlx5
for inter-node RMA. The custom install_nixl_from_source.sh path is
kept (now generates `nixl-cuMAJOR` per torch's CUDA major) for
clusters that need a vendored UCX, but it's no longer the default.

install_ep_kernels.sh:
- Falls back to /usr/local/cuda-${MAJOR} when torch reports 13.0
  but only cuda-13 (-> 13.1) is installed; rejects toolkit/torch
  major mismatches.
- Exports CPATH=$CUDA_HOME/include/cccl for CUDA 13, where CCCL
  headers (e.g. <cuda/std/tuple>) moved into the cccl/ subdir and
  torch's CUDAExtension doesn't add it on its own.
- Post-build --set-runpath /tmp/deepep_build/nvshmem/lib rewrites
  the DT_RUNPATH on deep_ep_cpp.so to match the cu12 convention the
  existing inference/RL templates already hook (they symlink the
  user's NVSHMEM at that path on each compute node).

install_deep_gemm.sh: post-build cu-suffix stamp.

scripts/wheel_add_cu_suffix.py (new): repacks a wheel with
+...cuXX appended to its local version, optionally stripping or
rewriting DT_RUNPATH on every .so. Keeps METADATA / dist-info /
RECORD / filename consistent.

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

* fix(templates): fall back to ep_kernels_workspace nvshmem in disagg launchers

inference.sbatch.j2 and multi_node_rl.sbatch.j2 still set up the
/tmp/deepep_build/nvshmem/lib symlink the deep_ep wheel needs at
runtime, but now also try $PROJECT_DIR/ep_kernels_workspace/nvshmem/lib
(where install_ep_kernels.sh actually places NVSHMEM) if
$OUTPUT_DIR/nvshmem isn't staged.

Also adds the same hook to multi_node_rl.sbatch.j2's disagg block
(was previously only in inference.sbatch.j2, despite multi_node_rl
running deep_ep in-process when disagg is enabled).

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

* style: drop unused shutil import, apply ruff format

Caught by the Style workflow — `shutil` was speculatively imported
when wheel_add_cu_suffix.py was first sketched but never used, and
ruff's formatter wanted a couple of cosmetic tweaks.

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

* fix(deps): exempt torchvision/torchaudio from exclude-newer cooldown

Both are sourced from the `pytorch-cu130` index alongside `torch` and
`flash_attn_3`. That index doesn't publish upload dates, so any package
pulled from it must be exempt from the 7-day `exclude-newer` cooldown
or `uv lock` may fail to resolve when a new release lands inside the
window.

Caught by bugbot.

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

* chore(deps): refresh uv.lock metadata under uv 0.11.9

Previous lockfile was generated with uv 0.11.7. After the bugbot
fix added `torchvision`/`torchaudio` to `exclude-newer-package`,
CI (which runs uv 0.11.9) detected a metadata drift and failed
`uv sync --locked`, even though the resolved packages were
identical.

Re-locking with uv 0.11.9 reorders the `exclude-newer-package`
section and normalizes the `exclude-newer` value; no resolution
changes.

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

* add cu12 cudart to venv dep

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Jackmin801 <ongjackm@gmail.com>
2026-05-05 20:20:19 -07:00
f7a27f69dd fix(sft): don't divide reported throughput by cp (#2424)
Release / Push CUDA image to Docker (push) Canceled after 0s
The bench reported `num_tokens = batch * seq // cp`, which under-reports
tps and MFU by ~cp× when CP > 1. CP is sequence-sharded data parallelism
(cp ranks split the seq dim of the same `batch × seq` tokens), so the
unique training tokens per step is `batch × seq` regardless of cp —
identical to the convention RL already uses (which excludes cp from the
`dp` mesh used for token counting).

Effect: cp=2 runs no longer look 2× slower than they really are in
SFT bench output; numbers become directly comparable across cp values.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 17:33:39 -07:00
minh hoangandGitHub 31591b7fe8 docker: drop deadsnakes in build stage (#2421)
Release / Push CUDA image to Docker (push) Canceled after 0s
deadsnakes has been pretty flakey during image builds on CI, and afaict
i think uv already installs python so don't think it's actually required
2026-05-05 09:24:40 -07:00
samsjaandGitHub 0deb4abaa9 fix(ring_attn): make FA3 causal/window_size kwargs version-agnostic (#2417)
Release / Push CUDA image to Docker (push) Canceled after 0s
66b277fb hardcoded is_causal + window_size_left/right assuming flash_attn_3
  3.0.0 API, but forward uses causal while backward uses is_causal in the
  installed package. Add _set_fa3_signature_params() that inspects the
  get_default_args() dict to set whichever key is actually present, covering
  both param name variants across FA3 versions.
2026-05-04 19:23:23 -07:00
halleriteandGitHub 4be61bbd68 chore(deps): host disagg wheels on prime-rl release instead of samsja personal repo (#2413)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-05 00:07:16 +02:00
rasdaniandGitHub 0660a9b3cb Pin Triton JIT cache to node-local /tmp per job (#2305)
Release / Push CUDA image to Docker (push) Canceled after 0s
Default TRITON_CACHE_DIR=~/.triton/cache lives on NFS in shared-home
clusters. Concurrent multi-node compiles race on that directory and
some ranks hit `ImportError: cannot stat shared object: Stale file
handle` when reading a .so that another node invalidated. One rank
dies, NCCL watchdog trips after 480s on all other ranks, job hangs.

Point TRITON_CACHE_DIR at /tmp/triton-cache-$USER-$SLURM_JOB_ID so
each node has its own local cache and no job shares state with any
other.
2026-05-03 23:37:04 +02:00
samsjaandGitHub 2ff21d97e7 chore(agents): forbid editing .venv/ (#2400)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(skills): add dotvenv skill warning against editing .venv/

* feat(agents): forbid editing .venv in AGENTS.md instead of skill

Replaces the dotvenv skill with a one-line rule under 'Running code'
in AGENTS.md, since AGENTS.md is always loaded and a 'never do X' rule
fits better there than as an on-demand skill.
2026-05-02 18:36:19 -07:00
5e6f7ebae8 feat(advantage): add num_turns option to efficiency shaping (#2384)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(advantage): add num_turns option to efficiency shaping

Replaces `length_shaping: bool` with `shaping_metric: Literal["length", "num_turns"] | None`
so the same correctness-gated efficiency shaping can score rollouts by trajectory
turn count instead of completion-token count. Generalizes the helper to operate
on a per-rollout cost tensor; both metrics are plumbed through `AdvantageInputs`.

* fix(advantage): remove extra blank line for ruff I001

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

* refactor(advantage): rename shaping_metric -> length_penalty

Per review feedback, use clearer name and shorter literal values:
shaping_metric: Literal["length", "num_turns"] -> length_penalty: Literal["tokens", "turns"]

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

* refactor(advantage): pass full rollouts through AdvantageInputs

AdvantageInputs now holds list[list[vf.RolloutOutput]] grouped by problem
instead of separate rewards/completion_lengths/num_turns tensors. Custom
advantage fns can read any rollout metadata; inputs.rewards is kept as a
convenience property for the common case.

Per @mikasenghaas review.

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

* refactor(advantage): drop AdvantageInputs.rewards convenience property

Per @samsja review: with rollouts as the single source of truth, the
rewards property was a partial holdover. Custom advantages now extract
rewards directly from rollouts, matching how all other metadata is read.

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

* test(advantage): regression test for per-problem advantage isolation

Two-problem case with very different reward scales — catches cross-group
leakage, slicing/transpose bugs, and out-of-order assignment in the
flat -> grouped -> flat round-trip through compute_advantages.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 16:06:31 -07:00
rasdaniandGitHub 7d7bd92333 Fix CP-local cu_seqlens from position ids (#2392)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-02 15:24:32 -07:00
d8d214cbab chore(agents): require keeping PR descriptions in sync with pushes (#2386)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 12:20:16 -07:00
halleriteandGitHub a50b4079de chore: add 7-day supply chain cooldown via exclude-newer (#2382)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-01 02:55:33 +02:00
minh hoangandGitHub 0403c097a2 flash-attn-cute -> flash-attn-4 (#2381)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-30 12:26:45 -07:00
halleriteandGitHub 0b8c35e9b3 feat: per-model client-side renderers for RL rollouts (+ /v1/generate) (#2278)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-30 20:12:22 +02:00
ca5e02c24c fix(monitor): retry wandb.init on transient CommError + bump wandb (#2374)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: update wandb to >=0.26.1

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

* fix(monitor): retry wandb.init on transient CommError

The W&B backend occasionally returns a 404 on upsertBucket during
wandb.init (server-side bug, see wandb/wandb#10497), which previously
killed the orchestrator since only non-primary shared-mode processes
retried. Now all callers retry CommError with a small backoff.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 22:39:59 -07:00
c37e2ca71b feat(orchestrator): bump verifiers to 3b77145, log per-turn timings (#2379)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): bump verifiers to 3b77145, log per-turn timings

Adopt the new RolloutTiming schema from verifiers#1182 (TimeSpan-based,
seconds). Replace the flat generation_ms/scoring_ms metrics with a
timing/{all,env_name}/{key}/{mean,max,min} section covering total,
setup, generation, model, env, scoring, overhead.

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

* refactor(orchestrator): extract per-rollout timings into timing_df

Mirror the metrics_df / filter_df pattern so the timing keys aren't
flattened into results_df. Cleaner aggregation loops and no special
"timing_" column-name prefix.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 22:39:29 -07:00
b1e9c7bdd2 feat(trainer): add single-point TPS/MFU API for RL (#2376)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): base MFU and TPS on forward+backward time only

PerfCounter previously used the wall-clock interval between successive
count_tokens() calls, which spanned optimizer step, grad clip, scheduler,
checkpointing, validation, etc. In rl/train.py the logged
time/forward_backward also covered optimizer.step() despite its name.

Drop the rolling window: compute throughput and MFU directly from each
step's token count and the measured forward+backward duration.

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

* fix(trainer): include opt step in forward_backward_time

Place forward_backward_time capture after scheduler.step() in both SFT
and RL trainers so MFU/TPS reflects real GPU compute (fwd + bwd + grad
clip + optimizer step + scheduler step) without data-loading or other
host-side wait time.

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

* feat(trainer): dual-mode PerfCounter — windowed for SFT, single-point for RL

PerfCounter now exposes both APIs on the same class:
- count_tokens / get_tokens_per_second / get_mfu — sliding-window smoothing
- get_step_tokens_per_second / get_step_mfu — single-step values

SFT uses the windowed API; RL uses the single-point API.

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

* revert(trainer): restore SFT sliding window over full step

SFT goes back to the original behavior: count_tokens(tokens) records its
own timestamp, smoothing happens over wall time between successive calls
(i.e. full step time, including opt step / validation / etc).

RL keeps the new single-point API on forward_backward_time.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 21:09:14 -07:00
af17a555fe fix(qwen3.5-moe): align _compute_attention with FA4 kwarg-based cu_seqlens (#2378)
Release / Push CUDA image to Docker (push) Canceled after 0s
Port the _compute_attention implementation from layers/attn.py so FA4
receives cu_seqlens via keyword args (its 4th positional is qv) and so
sliding_window is honored when set.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 14:13:20 -07:00
minh hoangandGitHub a87badd65f feat(inference): vllm engine liveness probe (#2375)
Release / Push CUDA image to Docker (push) Canceled after 0s
* vllm engine liveness probe

* codex yapping tests

* update liveness probe on helm template
2026-04-29 14:05:52 -07:00
Jackmin801andGitHub 5061b8d88e up fa4 version (#2369)
Release / Push CUDA image to Docker (push) Canceled after 0s
* up fa4 version

* update in the arm build script

* uv lock

* update in fix-flash-attn-cute
2026-04-28 19:53:57 -07:00
a8575d6f1c fix(orchestrator): bound monitor history and drop duplicate samples list (#2373)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): bound monitor history and drop duplicate samples list

The orchestrator process was retaining two unbounded structures for the full
lifetime of a run, both accumulating per orchestrator step:

- `WandbMonitor.history` / `PrimeMonitor.history`: full metrics dict per step,
  only ever read at end of run (orchestrator's --bench print, PrimeMonitor's
  `history[-1]` summary).
- `WandbMonitor.samples`: full prompt/completion text + stringified token ids
  per logged sample, only ever read once at end of run inside
  `log_final_samples()` to package a redundant `final-samples` wandb table.

For long prod runs with sample logging enabled this is the dominant memory
growth in the orchestrator and a plausible source of orchestrator-side OOMs.

Changes:
- Add `Monitor.prune_history()` that truncates `history` to its last entry
  (preserves `history[-1]` access for `save_final_summary`); `MultiMonitor`
  delegates to wrapped monitors.
- Call `monitor.prune_history()` from the orchestrator loop, gated on
  `not config.bench` so benchmark mode still gets the full history.
- Drop `WandbMonitor.samples` and the duplicate `final-samples` end-of-run
  table — per-step samples are already streamed via the incremental
  `samples` wandb table. Drops the now-unused `pandas` import.

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

* fix(monitor): drop unneeded try/except around MultiMonitor.prune_history

prune_history is a list slice — it can't fail in any meaningful way, so
matching the defensive pattern of the other delegators here was just noise.

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

* refactor(monitor): gate history accumulation; drop log_final_samples

Address review feedback:

- Replace `prune_history()` + per-step orchestrator call with a constructor
  `keep_full_history` flag on monitors. `Monitor.log()` either appends or
  replaces in-place based on the flag. The orchestrator passes
  `keep_full_history=config.bench` so non-bench runs never accumulate
  history at all (rather than accumulating-then-pruning). Trainer keeps
  the default `True`.
- Remove `log_final_samples` from the Monitor interface and all
  implementations; it was a no-op everywhere after the prior commit.
  Drops the corresponding orchestrator call site and the MultiMonitor
  delegator.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 15:31:51 -07:00
Matej SirovatkaandGitHub e75d8ca47f GlmMoeDsa - better CP implementation (#2372)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: new cp

* Fix: style

* Feat: cleanup
2026-04-28 15:28:49 -07:00
daedc1dbc6 fix(orchestrator): scope example_id by env_name to prevent cross-env collisions (#2366)
Release / Push CUDA image to Docker (push) Canceled after 0s
Auto-generated example_ids start at 0 for every dataset, so multi-env
runs silently merge rollouts from different envs in global metrics
(solve rates, reward averages, problem counts). Scope all global
groupby/set operations by (env_name, example_id) instead of example_id
alone.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-28 11:54:34 -07:00
3719abcfbb feat: rollout timeout config + verifiers 0.1.13.dev8 (#2371)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: rollout timeout config + verifiers 0.1.13.dev8

- Bump verifiers pin to v0.1.13.dev8 (rollout timeout, sandbox lifetime
  auto-derive, per-turn timing display).
- New EnvConfig.timeout_seconds: float | None field on the orchestrator
  config. When set, a model_validator auto-populates
  extra_env_kwargs["timeout_seconds"], which the env server forwards to
  the env constructor. MultiTurnEnv reads it as the per-rollout
  asyncio.wait_for cap. Mirrors the existing
  max_total_completion_tokens auto-populate pattern.

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

* refactor: rename env timeout_seconds to timeout (with alias)

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

* chore: pin verifiers to 980a9ea

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 11:53:46 -07:00
93cbc75b81 feat(orchestrator): make inference pool startup timeout configurable (#2355)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): make inference pool startup timeout configurable

Adds wait_for_ready_timeout to ClientConfig (default 1800s, matching
prior hardcoded value), threaded through StaticInferencePool and
ElasticInferencePool so it can be overridden via TOML per-client (e.g.
student vs teacher pools).

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

* chore: ruff format

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 05:09:34 +02:00
4e4390be87 feat: debug.force_balanced_routing for MoE smoke tests (#2368)
Release / Push CUDA image to Docker (push) Canceled after 0s
Fake-data MoE training produces severely skewed expert assignments,
which under EP causes per-rank memory blowup and OOM. This adds an
opt-in DebugModelConfig flag that overrides token-choice routing with
a round-robin assignment so every expert receives an equal share of
tokens. Gating scores are gathered from the override indices to keep
the forward pass self-consistent. Gradient flow through the router is
broken, so this is for benchmarking memory/timing only.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 20:04:24 -07:00
Jackmin801andGitHub 8457b601d6 [Fix] gpt oss (#2365)
Release / Push CUDA image to Docker (push) Canceled after 0s
* custom gpt oss impl

* gpt oss multilora impl

* gpt oss experts

* add gpt oss to custom model mapping

* add GPToss experts to apply lora

* update warning message
2026-04-27 15:49:51 -07:00
273524e2fc chore: remove async level from orch step log (#2361)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 15:23:51 -07:00
d2f36c9f65 feat: per-batch loss type override for hosted SFT hard distill (#2271)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: per-batch loss type override for hosted SFT hard distill

Add loss_type field to TrainingSample and MicroBatch transport types so
the orchestrator can stamp samples with a loss override (e.g. "sft")
that the trainer dispatches per-batch. This allows a shared multi-tenant
trainer to handle both RL and SFT distill runs on the same cluster.

When teacher_rollout_model is configured, the orchestrator sets
loss_type="sft" on each sample. The trainer's compute_loss checks the
field and swaps to sft_loss_fn for that batch, falling back to the
configured default when None (fully backward compatible).

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

* refactor: explicit loss_type field, sft_loss bool, no auto-derive

Address review feedback:
- Replace loss_type: str | None with sft_loss: bool on TrainingSample
  and MicroBatch (simpler, no string matching)
- Add explicit loss_type: Literal["rl", "sft"] on OrchestratorConfig
  instead of auto-deriving from teacher_rollout_model presence
- Orchestrator stamps sample.sft_loss based on config.loss_type, not
  teacher presence — user explicitly opts in
- Update validator: loss_type="sft" requires teacher_rollout_model
  (direction reversed from "teacher implies sft")
- Update example TOML with explicit loss_type = "sft"

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

* change to boolean

* conistency

* refactor: rename need_sft_loss to use_sft_loss and tighten hosted SFT invariants

- Rename `OrchestratorConfig.need_sft_loss` to `use_sft_loss` (clearer intent).
- Move the orchestrator-only SFT distill invariants (use_sft_loss paired
  with teacher_rollout_model, use_token_client coupling) from RLConfig onto
  OrchestratorConfig so the hosted `orchestrator` entrypoint enforces them
  too, not just the combined `rl` entrypoint.
- Shrink RLConfig.validate_external_rollout_inference to the one truly
  cross-config check (teacher_rollout_model vs self.inference).
- Drop redundant `[trainer.loss] type = "sft"` from the alphabet_sort
  example so `use_sft_loss` is the single obvious knob.
- Access micro_batch["sft_loss"] directly in train.py (required TypedDict
  field, no fallback needed).
- Document the override in skills/config/SKILL.md.

* test: cover hosted SFT loss override

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-27 15:12:58 -07:00
2566de0bd5 chore: bump prime to >=0.5.73 (#2367)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 15:02:51 -07:00
0fca0d15c5 fix(models): document cache_position to silence auto_docstring warnings (#2363)
Release / Push CUDA image to Docker (push) Canceled after 0s
The transformers @auto_docstring decorator prints a warning at import
time for any forward-method param missing from the docstring. The five
custom *ForCausalLM models accept cache_position only for HuggingFace
API compatibility — training asserts use_cache is None and never decodes
autoregressively, so the param is unused. Documenting that fact makes
the behavior explicit and clears the warnings.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 17:48:58 +02:00
Jackmin801andGitHub 24a2af0054 patch warnings and turn off 3d for qwen (#2356)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-26 13:08:46 -07:00
Benjamin WarnerandGitHub 8342ccd0c8 feat: add entity, group, and tags to wandb config (#2350)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-25 13:15:55 -07:00
halleriteandGitHub 20454ecd7b fix(ring_attn): adapt FA3 varlen wrappers to flash_attn_3 3.0.0 kwargs (#2352)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-24 22:25:11 +02:00
4a42aa039e fix(trainer): wait for NCCL_READY on all ranks before broadcast (#2337)
Release / Push CUDA image to Docker (push) Canceled after 0s
`broadcast_weights` used to guard both the orchestrator-notify and the
file-wait behind `if self.world.is_master`. The non-master ranks
skipped the wait and entered `nccl_broadcast_sender.broadcast_weights`
directly. Inside that path the preparation (DTensor resolution +
quantization / checkpoint preprocessing) enqueues NCCL collectives on
all ranks (FSDP all_gather in _resolve_dtensors). Those collectives
then sit in-flight with no counter-party until the inference engines
are paused and join — but the master has not yet waited for the
NCCL_READY marker because... only it was doing that.

Net effect: if the orchestrator took more than ~10 minutes to signal
NCCL_READY (e.g. eval + rollout-gen contention at the same time),
NCCL's watchdog would fire on a non-master rank and SIGABRT the
trainer. We've hit this repeatedly in large-cluster RL runs, always
with a non-master rank as the one to signal the timeout first.

Fix: split the existing `_notify_orchestrator` into a pure
`_compute_notified_runs` (safe on every rank) plus an impure
`_notify_orchestrator(notified_runs)` (master-only, does the
filesystem side-effects). Call the first unconditionally, call the
second only on master, then have every rank wait on the NCCL_READY
marker before proceeding. The file poll is filesystem-only with no
NCCL involvement, so a slow orchestrator now just blocks the whole
trainer safely instead of tripping NCCL's watchdog.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 16:33:56 -07:00
Jackmin801andGitHub b0a7cad8a8 [fix] patch gdn with varlen for qwen (#2346)
Release / Push CUDA image to Docker (push) Canceled after 0s
* patch gdn with varlen

* claude just casually reverted this what?
2026-04-22 23:38:47 -07:00
Jackmin801andGitHub f1bbdf924e missed patch for nemotron state dict (#2340)
Release / Push CUDA image to Docker (push) Canceled after 0s
* missed patch for nemotron state dict

* allow implementing state dict map hook

* address comment
2026-04-22 21:40:56 -07:00
Jackmin801andGitHub 9bbed30eba [Fix] nemotron fixes (#2338)
Release / Push CUDA image to Docker (push) Canceled after 0s
* non gated grouped experts multilora layer

* do bias leveling to avoid overflow

* varlen mamba

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
2026-04-21 20:23:42 -07:00
halleriteandGitHub a6a6441a3b fix(ci): bump nightly test container /dev/shm to 16g (#2339)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-22 02:12:13 +02:00
samsjaandGitHub e8abfa264b chore: add conservative testing guidelines to AGENTS.md (#2330)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-19 19:18:33 -07:00
c3a24c35e2 feat(slurm): cleanup stale node-local state before launch (#2331)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(slurm): cleanup stale node-local state before launch

Add a pre-workload srun step to the multi-node RL, multi-node SFT and
inference sbatch templates. It runs once per node and:

- kills orphan python/torchrun/vllm/prime_rl processes left over from a
  prior job that wedged after scancel (SLURM doesn't always reap cleanly
  when a job sits in CG for hours)
- removes stale vLLM and torch IPC state under /dev/shm/vllm-*,
  /tmp/vllm-*, /tmp/torch-*, /tmp/torchelastic_*

Without this, decode engines on previously-used nodes can hang at
"Waiting for READY message from DP Coordinator" because the new vLLM
process finds a stale /dev/shm segment or port holder from the dead run.
Symptom we hit: a fresh job timing out after 1800s because 4 decode
engines never became READY; a manual pdsh cleanup of the same nodes
fixed it immediately.

Each node prints one line (hostname, residual proc count, total GPU
memory in use) so the sbatch log shows the nodes came up clean.

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

* feat(slurm): explicitly cover vllm-router in cleanup

Address review feedback: add vllm-router to the pkill list and the
procs-count regex so the intent is explicit, even though the broader
"vllm" patterns already match it as a substring.

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

* feat(slurm): also kill prctl-named vllm::router workers

pkill -f only matches the command line, so the vllm router's worker
processes — which set their kernel process name (comm) to "vllm::router"
via prctl but keep a different cmdline — slip through. Add process-name
pkill for "vllm" and "vllm::.*" to catch them.

Also broaden the post-cleanup procs count to look at both comm and args
(ps -eo comm,args) so we see these if any survive.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 16:19:58 -07:00
d2718f5f65 chore: rename deprecated orchestrator config keys (#2327)
Release / Push CUDA image to Docker (push) Canceled after 0s
Rename '[orchestrator.sampling]' -> '[orchestrator.train.sampling]',
'[[orchestrator.env]]' -> '[[orchestrator.train.env]]', and
'max_tokens' -> 'max_completion_tokens' across all configs to remove
reliance on the deprecated auto-translation.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 13:08:35 -07:00
d49f3939e7 update dependency (#2317)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
2026-04-18 13:00:52 -07:00
9eeffdb6fb feat: drop filtered rollouts instead of masking (#2277)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: drop filtered rollouts from training batch instead of masking

Previously, enforced filters zeroed the completion_mask on detected
rollouts but still sent them through the entire training pipeline.
This wastes compute on samples that contribute nothing to the loss.

Now, `apply_filters` returns the subset of rollouts that should be
sent to the trainer. Enforced-detected rollouts are excluded before
pretokenization, VLM cache building, and sample construction.

The trainer handles the resulting empty batches ("phantom steps") by
skipping forward/backward and logging `data/is_empty_batch`.

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

* feat: retry empty filtered batches instead of passing them to trainer

Keep the invariant that the trainer only receives non-empty batches. If
all rollouts are filtered out, regenerate the batch (up to 3 retries)
and crash the orchestrator on sustained failure. Warn at <=10% trainable.

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

* chore: drop redundant num_rollouts guard

The retry loop only breaks when len(filtered_rollouts) > 0, which implies
num_rollouts > 0, so the guard is unreachable.

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

* chore: expand low-trainable-ratio warning with env review hint

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

* chore: drop empty-df guard and inline filtered metrics

filtered_rollouts is guaranteed non-empty after the retry loop, so the
empty-df branch is unreachable and the intermediate locals add no value.

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

* chore: hoist MAX_EMPTY_BATCH_RETRIES to module scope

Also rename the loop var and warning message to "retry N/MAX" so the
counter excludes the initial attempt and reads less ambiguously.

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

* chore: adjust log style in filter retry warnings

Drop trailing periods and replace ";" with " - " as clause separator.

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

* chore: clarify low-trainable-ratio warning hint

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

* refactor: compute metrics over all rollouts, drop only from trainer

Metric logging reverts to main's semantics: all rollouts contribute to
prefill_len, decode_len, samples_per_rollout, and results_df. Filtered
rollouts are still pretokenized and interleaved, but their samples are
simply not added to train_examples. Also inline the generate_batch
coroutine since it is awaited immediately.

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

* refactor: move filter flags to rollout["filter"] + is_filtered

Per-filter detection booleans now live under rollout["filter"], and a
top-level rollout["is_filtered"] captures whether any enforcing filter
triggered. The orchestrator uses is_filtered directly as the keep gate
(no more id() mapping). apply_filters no longer returns filtered_rollouts
- the in-place flags are the single source of truth. Also unbound-var
fix for retry-loop locals, and per-env filter/<env>/<flag>_rate logging
that mirrors the metrics logging pattern.

Both new fields are serialized to train_rollouts.jsonl via save_rollouts,
which already writes all top-level rollout keys.

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

* chore: cap to 3 total batch-generation attempts, not 3 retries

Rename MAX_EMPTY_BATCH_RETRIES to MAX_EMPTY_BATCH_ATTEMPTS and have the
loop run exactly that many times. Warning now reports the attempt that
just failed ("Attempt N/3 ... retrying").

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

* chore: log error line before raising on exhausted retries

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

* chore: align filter metric key names with per-env logging

Rename filter/total_detected_rate -> filter/detected_rate and
filter/total_enforced_rate -> filter/is_filtered_rate so the overall
keys mirror the per-env filter/<env>/is_filtered_rate naming.

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

* refactor: unify filter logging under filter/{all,<env>}/{<filter>,is_filtered}

Move is_filtered into results_df so it can be aggregated per-env like
is_truncated. filter_df now holds just per-filter detection booleans.
apply_filters no longer returns an aggregate metrics dict - the
orchestrator derives the rates uniformly across the "all" and per-env
scopes, with symmetric key naming and no _rate/_count suffixes.

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

* chore: rename rollout["filter"] to rollout["filters"] + log keys

Aligns with the plural configs list and the rollout-level "filters"
namespace. Log keys change from filter/{all,<env>}/... to
filters/{all,<env>}/....

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

* feat: self-evict orchestrator when batches carry no learning signal

Write control/evicted.txt before raising, so the multi-run manager
skips the run on rediscovery instead of treating it as a hard crash.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-18 09:22:28 -07:00
03689b8ac0 chore: remove prefix-cache-salt and reset-prefix-cache config flags (#2314)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove prefix-cache-salt and reset-prefix-cache config flags

Hardcode the defaults: always set cache_salt on inference requests
(keyed by ckpt_step) and never reset the prefix cache after weight or
LoRA updates. The salt alone is sufficient to invalidate stale KV
states across policy updates, so the reset path is redundant.

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

* chore: keep empty experimental sub-configs as extension points

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:03:37 -07:00
f29e947585 Fix Prime monitor public API flow (#2205)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Use bearer auth for Prime monitor uploads

* Fix Prime monitor presign and finalize flow

* Sanitize non-finite Prime monitor payloads

* Simplify Prime monitor payload normalization

* Simplify Prime monitor public API contract

* Simplify public presign response parsing

* Simplify non-finite payload sanitization

* Inline public presign response parsing

* Inline non-finite payload sanitization logic

* Refine Prime monitor JSON sanitization

* Address review: inline auth headers and simplify sanitize

- Remove _api_headers() helper; store self._headers once in __init__
- Always sanitize payloads; drop silent try/except and log only when values are dropped
- Remove prime_cli sys.modules mocking from tests (real dep is installed)

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

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:01:27 -07:00
JupiterandGitHub bb7449c829 Add FA4 (flash_attn.cute) support to ring attention, enabling context (#2307)
Release / Push CUDA image to Docker (push) Canceled after 0s
parallel training with FA4 kernels. Mirrors the FA3 ring attention
pattern (all-gather K/V, compute per GQA stride, reduce-scatter grads)
using FA4 low-level _flash_attn_fwd/_flash_attn_bwd.

Changes:
- ring_attn.py: FA4 forward/backward wrappers, _RingFA4Varlen autograd
  Function, ring_fa4_varlen_func public API
- attn.py: route FA4 to ring_fa4_varlen_func in substitute_ring_attn
- trainer.py: allow CP with fa4 (requires model.impl='custom')
2026-04-17 20:00:52 -07:00
82fa41f4f2 fix: serialize env server spawn to avoid port race (#2310)
Release / Push CUDA image to Docker (push) Canceled after 0s
get_free_port() only holds the port until it returns, so parallel
env spawns under asyncio.gather could hand the same port to two
children — the loser died with EADDRINUSE. Serializing start()
and awaiting wait_for_server_startup() between envs ensures each
port is bound before the next one is picked.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 15:55:37 -07:00
1ade129004 fix: check rollout error before empty trajectory in scheduler (#2308)
Release / Push CUDA image to Docker (push) Canceled after 0s
When `verifiers` CliAgentEnv catches an agent crash pre-LLM-call, it
sets `state["error"]` but the trajectory stays `[]` because the agent
never produced any messages. The previous branch order fired the
"Empty trajectory" warning first and dropped the detailed AgentError
diagnostic. Swap the branches so error-bearing rollouts surface
"Rollout error ...: {error_chain_repr}" instead.

Related: PrimeIntellect-ai/verifiers#1127, #1130

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:23:13 +02:00
26ea8df85e chore: bump vllm-router to v0.1.22 (#2292)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 10:52:49 -07:00
Mika SenghaasandGitHub d4bddbaed7 fix: clean stale rollouts and broadcasts on fresh runs (#2304)
Release / Push CUDA image to Docker (push) Canceled after 0s
Previously `clean_future_steps` only ran when resuming from a checkpoint,
so a fresh run started in an output_dir containing stale rollouts or
broadcasts from a previous run would consume them: the trainer would
train on stale data and the orchestrator would compute a negative async
level because it sees a trainer that is seemingly ahead of it.

Run the same cleanup from step 0 when training from scratch so these
artifacts are removed before training begins.
2026-04-17 09:26:34 -07:00
samsjaandGitHub 6bf14b80f8 vf bump (#2302)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 08:11:50 -07:00
halleriteandGitHub 586e0f8e5d fix: work around transformers lazy_load_kernel offline regression (#2276)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 15:16:27 +02:00
JannikStandGitHub 18e895651e accept fully-qualified expert names in lora check (#2301)
Release / Push CUDA image to Docker (push) Canceled after 0s
* accept fully-qualified expert names in lora check

* ruff format
2026-04-17 14:56:58 +02:00
Matej SirovatkaandGitHub 2c54d5c834 Feat: fix cpu offloading patch to match upstream and remove a segfault (#2300)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 11:21:32 +02:00
3a6b46189a fix: always ensure X-Session-ID and propagate extra_headers_from_state in elastic pool (#2283)
Release / Push CUDA image to Docker (push) Canceled after 0s
Two fixes:
- Use setdefault so X-Session-ID: example_id is always present for
  sticky DP-aware routing, even if user provides other
  extra_headers_from_state entries
- Propagate extra_headers_from_state when rebuilding clients in the
  elastic pool, so session headers survive pool refreshes

Keeps dp_rank_count as-is for direct DP rank routing.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:11:58 -07:00
JannikStandGitHub ba86b9ba88 Support runtime verifiers version override (#2274)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Support runtime verifiers version override via VERIFIERS_VERSION env var

When set, the entrypoint reinstalls verifiers from the specified git ref
(tag, branch, or commit) before starting the main process.

* Drop --no-deps so transitive deps are updated with verifiers override

* Use --reinstall-package to only reinstall verifiers, not the entire dep tree
2026-04-16 09:38:18 -07:00
halleriteandGitHub 2d659eecc7 feat: context parallelism for NemotronH Mamba layers (#2231)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-16 09:12:49 +02:00
56cdd2c579 feat: pre-download model weights in launcher (#2282)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: pre-download model weights in launcher instead of using HF_HUB_OFFLINE

Remove hardcoded `HF_HUB_OFFLINE=1` from multi-node SLURM templates and
instead pre-download model weights via `snapshot_download` in the rl/sft
launchers before dispatching to local or SLURM execution. This ensures
weights are cached on the shared filesystem before training starts,
removing the need to manually pre-download models.

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

* feat: pre-download model weights in launcher instead of using HF_HUB_OFFLINE

Remove hardcoded `HF_HUB_OFFLINE=1` from multi-node SLURM templates and
instead pre-download model weights via `snapshot_download` in the rl/sft
launchers before dispatching to local or SLURM execution. This ensures
weights are cached on the shared filesystem before training starts,
removing the need to manually pre-download models.

Also replace `format_time` with the verifiers-style two-unit display
(e.g. "1h 30m" instead of "1.50h").

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

* refactor: move pre_download_model to trainer.model

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

* feat: log cache path when model is already downloaded

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

* chore: remove redundant cache log from pre_download_model

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

* chore: move pre_download_model import to module top

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

* feat: skip download and log cache path when model already cached

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

* Revert "feat: skip download and log cache path when model already cached"

This reverts commit 5b2bac9f2bb9e22ae898fe54f66f48357931dc40.

* chore: keep HF_HUB_OFFLINE=1 in SLURM templates

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 19:51:04 -07:00
4dcf86f0ea feat: set tool_call_parser default to 'auto' (#2285)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: set tool_call_parser default to 'auto'

Changed the default value of tool_call_parser from None to 'auto' to enable automatic tool call parser detection from model name by default. This provides better out-of-the-box experience for users working with tool-calling models.

* test: add unit tests for inference metrics collector

Tests parsing, aggregation (sum/max/mean), counter rates, histogram
latency, counter reset handling, server failures, and wandb logging.

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

* Revert "test: add unit tests for inference metrics collector"

This reverts commit 48eb049144b51ec9a2562358b398c2be46bc8eca.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 18:16:10 -07:00
samsjaandGitHub ad3134ac03 fix 32-> 30 (#2287)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-15 16:34:23 -07:00
samsjaandGitHub 8c5aa67aa5 fix 2.5 -> qwen (#2286)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-15 16:22:56 -07:00
rasdaniandGitHub fde3006470 Add env_install_prerelease config option (#2279)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-15 02:26:25 -07:00
201 changed files with 12846 additions and 3608 deletions
+61 -1
View File
@@ -14,7 +14,11 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
@@ -38,3 +42,59 @@ jobs:
run: PYTEST_OUTPUT_DIR=/tmp/outputs uv run pytest tests/unit -m "not gpu"
- name: Cleanup output_dir
run: rm -rf /tmp/outputs
slim-configs-install:
name: Slim install (prime-rl-configs only)
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Build the slim wheel
run: uv build --wheel ./packages/prime-rl-configs --out-dir /tmp/slim-wheel
- name: Install slim wheel from a directory with no workspace context
# Build the wheel and install it from /tmp so uv can't discover the
# repo's root pyproject.toml [tool.uv.sources] and silently apply
# them. This mirrors what an external pip-only user gets.
run: |
uv venv --python 3.12 /tmp/slim
cd /tmp && uv pip install --python /tmp/slim/bin/python /tmp/slim-wheel/*.whl
- name: Verify configs import without heavy deps
run: |
/tmp/slim/bin/python - <<'PY'
import sys
from prime_rl.configs.rl import RLConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import validate_shared_ckpt_config
forbidden = ["torch", "transformers", "vllm", "wandb", "ring_flash_attn",
"verifiers", "prime", "datasets", "liger_kernel", "loguru"]
leaked = [m for m in forbidden if m in sys.modules]
if leaked:
raise SystemExit(f"slim install leaked heavy deps into sys.modules: {leaked}")
# Slim wheel does not ship the templates/ data dir; resolver returns None.
assert find_package_resource("templates") is None, "templates should not be in slim wheel"
print("slim install OK — configs import with no heavy deps loaded")
PY
- name: Verify a real config (with [slurm]) parses on slim install
run: |
/tmp/slim/bin/python - <<'PY'
from pydantic_config import cli
from prime_rl.configs.rl import RLConfig
rl = cli(RLConfig, args=["@", "examples/Intellect-3.1/rl.toml"])
assert rl.slurm is not None, "expected [slurm] in example config"
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
assert rl.slurm.template_path is None, f"unexpected template_path on slim: {rl.slurm.template_path}"
print("slim parse OK")
PY
+30 -27
View File
@@ -28,23 +28,20 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
- name: Run unit tests
env:
USERNAME_CI: CI_RUNNER
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
# This is to allow running tests on forks without WANDB_API_KEY
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
@@ -63,21 +60,30 @@ jobs:
fail-fast: false
matrix:
include:
- test: base
- test: reverse_text_sft
runner: vm
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
- test: rl_lora
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: vm
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: vm
pytest_args: "tests/integration/test_reverse_text.py"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
- test: rl_multi_run
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py -m gpu"
pytest_args: "tests/integration/test_benchmark_regression.py"
steps:
- name: Install Git
run: |
@@ -87,23 +93,20 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
- name: Run integration tests
env:
USERNAME_CI: CI_RUNNER
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
# This is to allow running tests on forks without WANDB_API_KEY
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
@@ -111,4 +114,4 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest ${{ matrix.pytest_args }}
run: uv run pytest -vvs ${{ matrix.pytest_args }}
+10 -3
View File
@@ -25,7 +25,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Build matrix from nightly test files
id: build-matrix
@@ -57,7 +57,10 @@ jobs:
runs-on: research-cluster
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
# --shm-size: vLLM V1's DP engine/API-server IPC uses POSIX shm-backed
# MessageQueue (~160MB per queue); Docker's default 64MB /dev/shm triggers
# SIGBUS in DP engine cores on VLM runs (mm data overflows tmpfs).
options: --gpus all --shm-size=16g
timeout-minutes: 1440 # 24 hours
strategy:
fail-fast: false
@@ -72,7 +75,11 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+6
View File
@@ -24,6 +24,12 @@ jobs:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Docker meta
id: meta
uses: crazy-max/ghaction-docker-meta@v2
+2 -1
View File
@@ -16,8 +16,9 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
with:
submodules: true
submodules: false
- name: Run ruff
uses: astral-sh/ruff-action@v3
with:
+3
View File
@@ -1,4 +1,5 @@
.vscode/*
.claude/scheduled_tasks.lock
*.ipynb
*.jsonl
configs/endpoints.py
@@ -199,3 +200,5 @@ debug_I2_zero_band
.idea
outputs/
third_party/
+12
View File
@@ -0,0 +1,12 @@
[submodule "verifiers"]
path = deps/verifiers
url = git@github.com:PrimeIntellect-ai/verifiers.git
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "configs/private"]
path = configs/private
url = git@github.com:PrimeIntellect-ai/research-configs.git
+6
View File
@@ -3,6 +3,7 @@
## Writing code
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Zen of Python**: remember the Zen of Python when writing code.
```
@@ -32,6 +33,7 @@ Namespaces are one honking great idea -- let's do more of those!
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
## Skills
@@ -43,6 +45,9 @@ You are responsible for maintaining the skills folder. When a workflow fails and
Write tests as plain functions with pytest fixtures. Don't use class-based tests.
- **Conservative test additions**: don't add new tests unless the user explicitly asks for them or it's clearly necessary. Editing existing tests is fine, but adding new test files or test functions should be the exception, not the default.
- **Test what matters**: only test code with clear, isolated logic — pure functions, abstract base classes, data transformations, well-defined algorithms. Don't test runtime-level code, framework glue, or anything that requires extensive mocking/patching just to get a test to pass. If you need to patch everything out to make it testable, it's probably not worth testing.
## Git
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
@@ -51,4 +56,5 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
+4
View File
@@ -2,6 +2,10 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
+3 -7
View File
@@ -12,7 +12,7 @@ RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
ENV CUDA_HOME=/usr/local/cuda
ENV PATH=$PATH:/usr/local/cuda/bin
# Install packages (including Python 3.12 and ninja for fast CUDA kernel compilation)
# Install build tooling.
ARG DEBIAN_FRONTEND=noninteractive
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
@@ -22,12 +22,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
sudo \
git \
ninja-build \
software-properties-common \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y --no-install-recommends python3.12 python3.12-dev python3.12-venv \
&& ln -sf /usr/bin/python3.12 /usr/bin/python3 \
&& ln -sf /usr/bin/python3.12 /usr/bin/python \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Download the latest installer
@@ -48,6 +42,8 @@ COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
COPY src/ /app/src/
COPY packages/ /app/packages/
COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
+9 -2
View File
@@ -53,6 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | [multimodal.md](docs/multimodal.md) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
@@ -90,14 +91,20 @@ git clone https://github.com/PrimeIntellect-ai/prime-rl.git
cd prime-rl
```
2. Install [uv](https://docs.astral.sh/uv/)
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
```
3. Install [uv](https://docs.astral.sh/uv/)
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env
```
3. Install dependencies from the lock file
4. Install dependencies from the lock file
```bash
uv sync --all-extras
+3 -3
View File
@@ -19,11 +19,11 @@ name = "stage1"
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 8192
max_completion_tokens = 8192
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -20,11 +20,11 @@ name = "stage2"
batch_size = 2048
rollouts_per_example = 16
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 16384
max_completion_tokens = 16384
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -13,10 +13,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2 }
@@ -1,4 +1,4 @@
max_steps = 10
max_steps = 5
seq_len = 2048
[ckpt]
@@ -13,10 +13,10 @@ lr = 1e-5
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 384
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
@@ -1,29 +0,0 @@
max_steps = 10
seq_len = 2048
[deployment]
type = "single_node"
num_infer_gpus = 1
num_train_gpus = 1
[ckpt]
[model]
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 1024
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
@@ -2,6 +2,7 @@ max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -13,10 +14,10 @@ lr = 3e-6
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
@@ -1,8 +1,7 @@
max_steps = 25
max_steps = 15
seq_len = 2048
[ckpt]
resume_step = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -14,10 +13,10 @@ lr = 3e-6
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
@@ -2,6 +2,7 @@ max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -22,10 +23,10 @@ rollouts_per_example = 16
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
@@ -1,8 +1,7 @@
max_steps = 25
max_steps = 15
seq_len = 2048
[ckpt]
resume_step = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -23,10 +22,10 @@ rollouts_per_example = 16
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
@@ -9,14 +9,17 @@ name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[trainer.model]
impl = "custom"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
@@ -11,10 +11,10 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-5
[sampling]
max_tokens = 128
[train.sampling]
max_completion_tokens = 128
[[env]]
[[train.env]]
id = "reverse-text"
[ckpt]
@@ -1,6 +1,7 @@
max_steps = 10
[ckpt]
resume_step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -1,7 +1,6 @@
max_steps = 20
max_steps = 5
[ckpt]
resume_step = 10
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -1,7 +1,7 @@
max_steps = 20
max_steps = 10
[ckpt]
resume_step = 10
resume_step = 5
[ckpt.weights]
save_adapter_separately = true
@@ -1,4 +1,4 @@
max_steps = 10
max_steps = 5
[ckpt]
+3 -3
View File
@@ -17,11 +17,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 8192
max_completion_tokens = 8192
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -17,10 +17,10 @@ language_model_attr = "model.language_model"
batch_size = 256
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 64
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
+2 -2
View File
@@ -2,6 +2,6 @@ max_steps = 5
max_async_level = 5
batch_size = 16
[sampling]
max_tokens = 16
[train.sampling]
max_completion_tokens = 16
+3 -3
View File
@@ -19,11 +19,11 @@ interval = 100
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 8192
max_completion_tokens = 8192
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -20,11 +20,11 @@ resume_step = 500
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 16384
max_completion_tokens = 16384
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -20,11 +20,11 @@ resume_step = 1000
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 24576
max_completion_tokens = 24576
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -32,15 +32,15 @@ lr = 1e-5
batch_size = 512
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 768
[orchestrator.train.sampling]
max_completion_tokens = 768
[orchestrator.client.elastic]
hostname = "localhost"
port = 8000
sync_interval = 5.0
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+5 -5
View File
@@ -16,27 +16,27 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math"
args = { min_avg_reward = 0.1, rubric_max_workers = 128 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "code-env"
name = "code"
args = { min_avg_reward = 0.1 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "science-env"
name = "science"
args = { min_avg_reward = 0.1, pool_size = 128, rubric_max_workers = 128 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "logic-env"
name = "logic"
args = { min_avg_reward = 0.1 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math-python"
args = { min_avg_reward = 0.1, sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy", python_tool = true, rubric_max_workers = 128 }
+3 -3
View File
@@ -12,10 +12,10 @@ name = "PrimeIntellect/Qwen3-0.6B"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
+4 -4
View File
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -28,7 +28,7 @@ hard_threshold = 0.0
interval = 10
[orchestrator.eval.sampling]
max_tokens = 2048
max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
+1 -1
View File
@@ -12,7 +12,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
batch_size = 512
rollouts_per_example = 8
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
+2 -2
View File
@@ -11,13 +11,13 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 256
rollouts_per_example = 8
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
ratio = 0.5
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
+3 -3
View File
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-python"
args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy" }
+3 -3
View File
@@ -13,10 +13,10 @@ batch_size = 256
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 64
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
@@ -13,10 +13,10 @@ language_model_attr = "model.language_model"
batch_size = 16
rollouts_per_example = 2
[orchestrator.sampling]
max_tokens = 32
[orchestrator.train.sampling]
max_completion_tokens = 32
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
+4 -4
View File
@@ -48,10 +48,10 @@ max_inflight_activations = 5
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -64,7 +64,7 @@ hard_threshold = 0.0
interval = 10
[orchestrator.eval.sampling]
max_tokens = 2048
max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
+4 -4
View File
@@ -47,10 +47,10 @@ freq = 1
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 4096
[orchestrator.train.sampling]
max_completion_tokens = 4096
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -63,7 +63,7 @@ hard_threshold = 0.0
interval = 10
[orchestrator.eval.sampling]
max_tokens = 4096
max_completion_tokens = 4096
[[orchestrator.eval.env]]
id = "math500"
+1
Submodule configs/private added at 74c1330008
+3 -3
View File
@@ -30,13 +30,13 @@ batch_size = 512
rollouts_per_example = 16
oversampling_factor = 2.0
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[orchestrator.buffer]
online_difficulty_filtering = true
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "wiki-search"
[inference.model]
Vendored Submodule
+1
Submodule deps/renderers added at 17d0584f87
Vendored Submodule
+1
Vendored Submodule
+1
Submodule deps/verifiers added at 711a7c705e
+8 -5
View File
@@ -86,10 +86,12 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
```python
@dataclass
class AdvantageInputs:
rewards: Float[Tensor, "num_examples rollouts_per_example"]
completion_lengths: Int[Tensor, "num_examples rollouts_per_example"]
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
rollouts: list[list[vf.RolloutOutput]]
```
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
#### AdvantageOutputs
```python
@@ -106,9 +108,10 @@ from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
"""Normalize advantages to zero mean and unit variance per example."""
mean = inputs.rewards.mean(dim=1, keepdim=True)
std = inputs.rewards.std(dim=1, keepdim=True)
advantages = (inputs.rewards - mean) / (std + eps)
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
mean = rewards.mean(dim=1, keepdim=True)
std = rewards.std(dim=1, keepdim=True)
advantages = (rewards - mean) / (std + eps)
return AdvantageOutputs(advantages=advantages)
```
+1
View File
@@ -110,6 +110,7 @@ The eviction takes effect through two mechanisms:
- The orchestrator checks for `evicted.txt` at the start of each iteration in its main loop
- If found, it raises a `RuntimeError` with the eviction reason, causing the orchestrator to exit
- This surfaces the eviction reason to the user
- The orchestrator also self-evicts by writing `evicted.txt` if a training batch has no learning signal (all rollouts filtered out) on `MAX_EMPTY_BATCH_ATTEMPTS` (3) consecutive attempts
## LoRA Module Registration
+5 -5
View File
@@ -47,31 +47,31 @@ weight_decay = 0.01
batch_size = 2048
oversampling_factor = 2
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
ratio = 0.3
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "deepdive"
name = "deepdive"
ratio = 0.2
args = { finish_with_tool = true, open_max_workers = 128, cache_dir = "/tmp/i3_deepdive_cache_train" }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math"
ratio = 0.3
args = { min_avg_reward = 0.0, max_avg_reward = 0.874}
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "logic-env"
name = "logic"
ratio = 0.2
args = { min_avg_reward = 0.0, max_avg_reward = 0.874 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "code-env"
name = "code"
ratio = 0.2
+3 -3
View File
@@ -28,10 +28,10 @@ lr = 1e-5
batch_size = 512
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 768
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+4 -6
View File
@@ -19,9 +19,6 @@ name = "qwen3-4b-hard-distill"
[trainer.optim]
lr = 1e-5
[trainer.loss]
type = "sft"
[trainer.model.lora]
rank = 16
alpha = 32
@@ -33,9 +30,10 @@ save_adapter_separately = true
batch_size = 256
rollouts_per_example = 4
use_token_client = false
use_sft_loss = true
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
temperature = 0.7
[orchestrator.teacher_rollout_model.client]
@@ -45,7 +43,7 @@ api_key_var = "PRIME_API_KEY"
[orchestrator.teacher_rollout_model.model]
name = "qwen/qwen3-235b-a22b-instruct-2507"
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
+1 -1
View File
@@ -16,7 +16,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
batch_size = 512
rollouts_per_example = 8
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env" # included in lock file
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
+1 -1
View File
@@ -49,7 +49,7 @@ oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
+3 -3
View File
@@ -38,10 +38,10 @@ freq = 1
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
+2 -2
View File
@@ -1,6 +1,6 @@
# Qwen 2.5 32B Math
# Qwen 3 30B - A3B Math
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on math tasks.
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on math tasks.
## Requirements
+3 -3
View File
@@ -45,10 +45,10 @@ batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 8
[orchestrator.sampling]
max_tokens = 32768
[orchestrator.train.sampling]
max_completion_tokens = 32768
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math"
+2 -2
View File
@@ -1,6 +1,6 @@
# Qwen 2.5 32B SWE
# Qwen 3 30B - A3B SWE
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on agentic SWE tasks.
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on agentic SWE tasks.
## Requirements
+1 -1
View File
@@ -46,7 +46,7 @@ batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
+3 -3
View File
@@ -12,10 +12,10 @@ name = "reverse-text"
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[trainer.optim]
+3 -3
View File
@@ -37,13 +37,13 @@ oversampling_factor = 2.0
[orchestrator.model.lora]
name = "qwen3-4b-wiki-search"
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[orchestrator.buffer]
online_difficulty_filtering = true
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/wiki-search"
[ckpt] # Checkpoint at the end of training
+3 -3
View File
@@ -18,12 +18,12 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 1024
rollouts_per_example = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/wordle"
name = "wordle"
[orchestrator.sampling]
max_tokens = 1024
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
+1 -1
View File
@@ -207,7 +207,7 @@ spec:
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
livenessProbe:
httpGet:
path: /health
path: /liveness
port: {{ .Values.inference.service.port }}
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
+2 -2
View File
@@ -75,7 +75,7 @@ inference:
runtimeClassName: nvidia
# Health probes for inference server (requires /health endpoint)
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
probes:
enabled: false
# Startup probe: allows long model loading time (up to 45 min by default)
@@ -86,7 +86,7 @@ inference:
liveness:
periodSeconds: 10
failureThreshold: 3
timeoutSeconds: 60
timeoutSeconds: 10
readiness:
periodSeconds: 5
failureThreshold: 2
+26
View File
@@ -0,0 +1,26 @@
# prime-rl-configs
Slim config schema for [`prime-rl`](https://github.com/PrimeIntellect-ai/prime-rl), with no GPU or ML deps.
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-server schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
## Install
```sh
pip install git+https://github.com/PrimeIntellect-ai/prime-rl.git#subdirectory=packages/prime-rl-configs
```
## Usage
The pip *distribution name* (`prime-rl-configs`) and the *import path* (`prime_rl.configs.*`) are different on purpose: this package contributes submodules to the shared `prime_rl` namespace.
```python
from pydantic_config import cli
from prime_rl.configs.rl import RLConfig
config = cli(RLConfig, args=["@", "path/to/rl.toml"])
```
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_server`).
`import prime_rl` on its own succeeds but is empty — it's a [PEP 420](https://peps.python.org/pep-0420/) namespace package with no top-level attributes. Always import a submodule.
+25
View File
@@ -0,0 +1,25 @@
[project]
name = "prime-rl-configs"
version = "0.4.0"
description = "Slim config schema for prime-rl (no GPU/ML deps)."
readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
# The PyPI package named `pydantic-config` is a different project that
# doesn't expose `BaseConfig` / `cli`. Pin to samsja's fork so plain
# `pip install prime-rl-configs` (no uv workspace context) resolves it.
"pydantic-config @ git+https://github.com/samsja/pydantic_config.git",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/prime_rl"]
[tool.hatch.metadata]
allow-direct-references = true
@@ -13,6 +13,7 @@ class EnvServerConfig(BaseConfig):
env: EnvConfig = EnvConfig()
log: LogConfig = LogConfig()
env_install_prerelease: bool = False
output_dir: Annotated[
Path,
@@ -6,7 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
from prime_rl.utils.utils import rgetattr, rsetattr
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
# TODO: Set thinking/ solution budget
@@ -16,6 +16,16 @@ class ServerConfig(BaseConfig):
host: Annotated[str | None, Field(description="The host to bind to.")] = None
port: Annotated[int, Field(description="The port to bind to.")] = 8000
liveness_timeout_seconds: Annotated[
float,
Field(
gt=0,
description=(
"Timeout in seconds for the /liveness endpoint's internal vLLM worker RPC. "
"If Kubernetes liveness probes are enabled, keep the probe timeoutSeconds at least this high."
),
),
] = 30.0
class ParallelConfig(BaseConfig):
@@ -85,7 +95,7 @@ class ModelConfig(BaseModelConfig):
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
'Set to "auto" to infer from the model name.',
),
] = None
] = "auto"
reasoning_parser: Annotated[
str | None,
@@ -110,6 +120,16 @@ class WeightBroadcastConfig(BaseConfig):
)
class KVCacheOffloadConfig(BaseModel):
"""CPU KV cache offloading for vLLM inference workers."""
model_config = ConfigDict(extra="forbid")
cpu_bytes: Annotated[int, Field(gt=0, description="CPU bytes available for KV cache offloading per worker.")] = (
1_000_000_000
)
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
@@ -152,20 +172,6 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
] = "consistent_hash"
class KVCacheOffloadConfig(BaseModel):
"""CPU KV cache offloading for disaggregated serving.
When configured, both prefill and decode nodes use
MultiConnector (NixlConnector + OffloadingConnector).
"""
model_config = ConfigDict(extra="forbid")
cpu_bytes: Annotated[int, Field(ge=0, description="CPU bytes available for KV cache offloading per worker.")] = (
1_000_000_000
)
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
"""Configures a disaggregated prefill/decode inference deployment.
@@ -214,11 +220,6 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
Field(description="Extra environment variables exported only on decode nodes."),
] = {}
kv_cache_offload: Annotated[
KVCacheOffloadConfig | None,
Field(description="CPU KV cache offload config for prefill nodes. None = disabled (NixlConnector only)."),
] = None
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@@ -247,15 +248,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceExperimentalConfig(BaseConfig):
"""Experimental features for inference."""
reset_prefix_cache_after_update: Annotated[
bool,
Field(
description="Whether to reset the prefix cache after weight updates (update_weights, load_lora_adapter). "
"Ensures all KV states are recomputed with the new weights at the cost of extra prefill. "
"When False, prefer using orchestrator.experimental.use_prefix_cache_salt to invalidate stale caches via salt instead.",
),
] = False
class InferenceConfig(BaseConfig):
"""Configures inference."""
@@ -392,6 +384,17 @@ class InferenceConfig(BaseConfig):
WeightBroadcastConfig()
)
kv_cache_offload: Annotated[
KVCacheOffloadConfig | None,
Field(
description=(
"CPU KV cache offload config for inference workers. Standard inference uses vLLM's "
"OffloadingConnector. Disaggregated P/D deployments combine it with NIXL through "
"MultiConnector in the SLURM launcher."
),
),
] = None
enable_return_routed_experts: Annotated[
bool,
Field(
@@ -399,6 +402,13 @@ class InferenceConfig(BaseConfig):
),
] = False
enable_fp32_lm_head: Annotated[
bool,
Field(
description="Run the lm_head projection in fp32 via a native bf16xbf16 -> fp32 GEMM (`torch.mm` with `out_dtype=torch.float32`). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's `--enable-fp32-lm-head`. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting `additional_config[\"fp32_lm_head\"] = True` on the vLLM config.",
),
] = False
vllm_extra: Annotated[
dict[str, Any],
Field(
@@ -437,6 +447,16 @@ class InferenceConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
if self.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.model_fields_set:
self.enable_prefix_caching = True
return self
@model_validator(mode="after")
def auto_setup_disaggregated(self):
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
@@ -459,10 +479,9 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
templates_dir = find_package_resource("templates")
if templates_dir is not None:
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
return self
@model_validator(mode="after")
@@ -509,6 +528,7 @@ class InferenceConfig(BaseConfig):
to_vllm = {
"server.host": "host",
"server.port": "port",
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
"model.name": "model",
"model.dtype": "dtype",
"model.max_model_len": "max_model_len",
@@ -545,6 +565,26 @@ class InferenceConfig(BaseConfig):
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
if self.kv_cache_offload is not None:
rsetattr(
namespace,
"kv_transfer_config",
{
"kv_connector": "OffloadingConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": {
"cpu_bytes_to_use": int(self.kv_cache_offload.cpu_bytes),
},
},
)
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
if self.enable_fp32_lm_head:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_lm_head"] = True
rsetattr(namespace, "additional_config", existing)
# Remove chat_template if not set (vLLM doesn't accept None)
if namespace.chat_template is None:
delattr(namespace, "chat_template")
@@ -1,4 +1,5 @@
import math
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
@@ -11,12 +12,12 @@ from prime_rl.configs.shared import (
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
RendererConfig,
TransportConfig,
WandbWithExtrasConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
class OptimizerConfig(BaseConfig):
@@ -148,9 +149,11 @@ class TrainSamplingConfig(BaseConfig):
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
get_logger().warning(
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release."
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
@@ -247,9 +250,11 @@ class EvalSamplingConfig(BaseConfig):
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
get_logger().warning(
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release."
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
@@ -324,6 +329,14 @@ class EnvConfig(BaseConfig):
),
] = -1
timeout: Annotated[
float | None,
Field(
validation_alias=AliasChoices("timeout", "timeout_seconds"),
description="Per-rollout wall-clock timeout in seconds. Set to None (default) to disable.",
),
] = None
@property
def stripped_id(self) -> str:
"""Environment ID without the @version suffix."""
@@ -346,6 +359,12 @@ class EnvConfig(BaseConfig):
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
return self
@model_validator(mode="after")
def resolve_timeout(self):
if self.timeout is not None:
self.extra_env_kwargs["timeout_seconds"] = self.timeout
return self
class TrainEnvConfig(EnvConfig):
"""Configures a training environment."""
@@ -670,22 +689,70 @@ class BufferConfig(BaseConfig):
return self
class TokensLengthPenaltyConfig(BaseModel):
"""Length penalty by weighted token cost.
Effective cost = completion_weight * model_completion_tokens
+ tool_response_weight * tool_response_tokens.
Tool-response tokens are read from the rollout's harness metric
`*_total_tool_response_tokens` (e.g. `rlm_total_tool_response_tokens`); 0 if absent —
so for envs without tool accounting, only the completion term contributes regardless of weight.
"""
model_config = ConfigDict(extra="forbid")
type: Literal["tokens"] = "tokens"
completion_weight: Annotated[
float,
Field(
ge=0,
allow_inf_nan=False,
description="Weight on model completion tokens. Finite and non-negative.",
),
] = 1.0
tool_response_weight: Annotated[
float,
Field(
ge=0,
allow_inf_nan=False,
description="Weight on tool-response tokens. Finite and non-negative.",
),
] = 1.0
class TurnsLengthPenaltyConfig(BaseModel):
"""Length penalty by trajectory turn count."""
model_config = ConfigDict(extra="forbid")
type: Literal["turns"] = "turns"
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
class DefaultAdvantageConfig(BaseModel):
"""Config for the default advantage."""
model_config = ConfigDict(extra="forbid")
type: Literal["default"] = "default"
length_shaping: Annotated[
bool,
length_penalty: Annotated[
LengthPenaltyConfig | None,
Field(
description=(
"Enable correctness-gated length shaping. In mixed groups, shorter correct rollouts get "
"amplified advantage (up to 2x), longer correct rollouts are unchanged, incorrect untouched. "
"In all-correct groups, below-average-length rollouts get advantage in [0, 1], others get 0."
"Correctness-gated length penalty. `tokens` shapes by weighted token cost, "
"`turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
"groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct "
"rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost "
"rollouts get advantage in [0, 1], others get 0."
)
),
] = False
] = None
class CustomAdvantageConfig(BaseModel):
@@ -715,7 +782,7 @@ class GibberishFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = False
token_id_threshold: Annotated[
@@ -739,7 +806,7 @@ class RepetitionFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = False
window: Annotated[
@@ -765,7 +832,7 @@ class ZeroAdvantageFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = True
@@ -812,15 +879,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
class OrchestratorExperimentalConfig(BaseConfig):
"""Experimental features for the orchestrator."""
use_prefix_cache_salt: Annotated[
bool,
Field(
description="Whether to set a cache_salt on inference requests that changes with each weight update. "
"This invalidates prefix-cached KV states from previous policies without resetting the entire cache, "
"while preserving cache hits for in-flight off-policy rollouts.",
),
] = True
class TeacherModelConfig(BaseConfig):
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
@@ -865,6 +923,9 @@ class OrchestratorConfig(BaseConfig):
# The tokenizer configuration
tokenizer: TokenizerConfig = TokenizerConfig()
# The renderer configuration (only used when use_renderer=True)
renderer: RendererConfig = RendererConfig()
# The optimizer configuration (per-run LR for multi-run training)
optim: OptimizerConfig = OptimizerConfig()
@@ -889,6 +950,17 @@ class OrchestratorConfig(BaseConfig):
),
] = None
# When True, trainer uses SFT loss instead of RL loss (per-run override for hosted multi-tenant training)
use_sft_loss: Annotated[
bool,
Field(
description=(
"When True, use SFT masked NLL loss instead of the trainer's configured RL loss. "
"Requires a teacher_rollout_model to be configured."
),
),
] = False
# The evaluation configuration
eval: EvalConfig | None = None
@@ -1010,6 +1082,14 @@ class OrchestratorConfig(BaseConfig):
),
] = 8
max_error_reschedule_attempts: Annotated[
int | None,
Field(
ge=1,
description="The group is dropped from the current step's batch once this many of its dispatch rounds have returned errored or empty rollouts (the trainer proceeds with the rollouts from other groups). Counts rounds, not individual rollouts: a non-group-scoring env that dispatches `rollouts_per_example` rollouts at once still only counts one round per failed batch. `None` means retry indefinitely (legacy behavior). Useful for unblocking single-example hangs in agent envs.",
),
] = None
max_async_level: Annotated[
int,
Field(
@@ -1041,10 +1121,31 @@ class OrchestratorConfig(BaseConfig):
use_token_client: Annotated[
bool,
Field(
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
description="Whether to use the token-in-token-out (TITO) client for training across all environments. "
"WARNING: Only use this if your environment has a linear history and the chat template has the extension "
"property (i.e. no tokens are ever removed or inserted by the chat template). Mutually exclusive with "
"``use_renderer``."
),
] = True
use_renderer: Annotated[
bool,
Field(
description="Whether to use the renderer client (client-side tokenization via the ``renderers`` package, "
"served by ``/v1/generate``). Mutually exclusive with ``use_token_client``. When True, the "
"``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) "
"applies; when False those fields must be left at their defaults. Not supported for VLMs — "
"VLMs must use the token client (TITO) so image preprocessing and chat templating stay server-side."
),
] = False
env_install_prerelease: Annotated[
bool,
Field(
description="Allow pre-release versions when installing environments (e.g. verifiers>=0.1.12.dev5). Passes --prerelease to prime env install."
),
] = False
experimental: Annotated[
OrchestratorExperimentalConfig,
Field(description="Experimental features for the orchestrator."),
@@ -1060,15 +1161,19 @@ class OrchestratorConfig(BaseConfig):
train = data.setdefault("train", {})
if isinstance(train, dict):
if "env" in data:
get_logger().warning(
warnings.warn(
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
"Auto-translating for now, but this will be removed in a future release."
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("env", data.pop("env"))
if "sampling" in data:
get_logger().warning(
warnings.warn(
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
"Auto-translating for now, but this will be removed in a future release."
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("sampling", data.pop("sampling"))
return data
@@ -1088,6 +1193,90 @@ class OrchestratorConfig(BaseConfig):
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
return self
@model_validator(mode="after")
def validate_sft_distill_mode(self):
"""Enforce the SFT hard distill invariants that involve only orchestrator fields.
Runs at ``OrchestratorConfig`` level so hosted deployments (which load this
config standalone via the ``orchestrator`` entrypoint) get the same guarantees
as the combined ``rl`` entrypoint.
"""
has_teacher = self.teacher_rollout_model is not None
if self.use_sft_loss and not has_teacher:
raise ValueError(
"orchestrator.use_sft_loss = true requires orchestrator.teacher_rollout_model to be configured."
)
if has_teacher and not self.use_sft_loss:
raise ValueError("orchestrator.teacher_rollout_model requires orchestrator.use_sft_loss = true.")
if has_teacher and self.use_token_client:
raise ValueError(
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
)
if has_teacher and self.use_renderer:
raise ValueError(
"orchestrator.use_renderer must be false when orchestrator.teacher_rollout_model is configured "
"(external rollout uses MITO)."
)
return self
@model_validator(mode="after")
def validate_client_mode(self):
"""The two client toggles select among three exclusive modes:
- ``use_token_client=True`` + ``use_renderer=False`` → TITO (default)
- ``use_token_client=False`` + ``use_renderer=True`` → renderer
- ``use_token_client=False`` + ``use_renderer=False`` → MITO
Both True is invalid: TITO and renderer are different wire protocols
(server-side templating vs client-side tokenization).
"""
if self.use_token_client and self.use_renderer:
raise ValueError(
"orchestrator.use_token_client and orchestrator.use_renderer are mutually exclusive. "
"Pick one: token client (TITO, server-side templating) or renderer client (client-side "
"tokenization)."
)
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
"""The renderer client takes plain message dicts and tokenizes
them client-side. VLMs need server-side image preprocessing and
chat templating, so they must use the token client (TITO) — fail
loudly when both are set."""
if self.use_renderer and self.model.vlm is not None:
raise ValueError(
"orchestrator.use_renderer is not supported for VLMs. Use the token client "
"(``use_token_client=true``, the default) so image preprocessing and chat "
"templating stay on the inference server."
)
return self
@model_validator(mode="after")
def validate_renderer_args(self):
"""``[orchestrator.renderer]`` knobs are only meaningful when
``use_renderer=True``. Reject otherwise so callers don't silently
pass them and wonder why they're ignored."""
if self.use_renderer:
return self
renderer_args_set = []
if self.renderer.name != "auto":
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
if self.renderer.tool_parser is not None:
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
if self.renderer.reasoning_parser is not None:
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
if self.renderer.pool_size is not None:
renderer_args_set.append(f"renderer.pool_size={self.renderer.pool_size!r}")
if renderer_args_set:
raise ValueError(
"Renderer-specific args set without orchestrator.use_renderer=True: "
f"{', '.join(renderer_args_set)}. Either enable the renderer client or remove these knobs."
)
return self
@model_validator(mode="after")
def nccl_max_async_level(self):
if self.weight_broadcast.type == "nccl":
@@ -1,3 +1,4 @@
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
@@ -38,8 +39,7 @@ from prime_rl.configs.trainer import (
from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_async_level,
@@ -77,8 +77,14 @@ class SharedWandbConfig(BaseConfig):
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
entity: Annotated[str | None, Field(description="The W&B entity to use.")] = None
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
group: Annotated[str | None, Field(description="The W&B group to use.")] = None
tags: Annotated[list[str] | None, Field(description="The W&B tags to attach to the run.")] = None
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
shared: Annotated[
@@ -428,24 +434,18 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_external_rollout_mode(self):
if self.orchestrator.teacher_rollout_model is None:
return self
def validate_external_rollout_inference(self):
"""Forbid configuring a local inference server when rollouts come from an external teacher.
if self.trainer.loss.type != "sft":
raise ValueError('orchestrator.teacher_rollout_model is only supported when trainer.loss.type = "sft".')
if self.inference is not None:
Orchestrator-only invariants (``use_sft_loss`` paired with ``teacher_rollout_model``,
and ``use_token_client`` coupling) live on ``OrchestratorConfig`` so the hosted
orchestrator entrypoint also enforces them.
"""
if self.orchestrator.teacher_rollout_model is not None and self.inference is not None:
raise ValueError(
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
"External rollout mode does not use the local inference server."
)
if self.orchestrator.use_token_client:
raise ValueError(
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
)
return self
### Auto-setup and validate shared configs
@@ -522,6 +522,10 @@ class RLConfig(BaseConfig):
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
if self.wandb.entity:
self.trainer.wandb.entity = self.wandb.entity
self.orchestrator.wandb.entity = self.wandb.entity
if self.wandb.shared:
if self.wandb.name:
self.trainer.wandb.name = self.wandb.name
@@ -531,6 +535,14 @@ class RLConfig(BaseConfig):
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
if self.wandb.group:
self.trainer.wandb.group = self.wandb.group
self.orchestrator.wandb.group = self.wandb.group
if self.wandb.tags:
self.trainer.wandb.tags = self.wandb.tags.copy()
self.orchestrator.wandb.tags = self.wandb.tags.copy()
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
@@ -669,6 +681,21 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.enable_eplb:
return self
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
trainer_weight_broadcast = self.trainer.weight_broadcast
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
raise ValueError(
"inference.enable_eplb requires weight_broadcast.type = 'nccl' and "
"weight_broadcast.quantize_in_weight_transfer = true."
)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
@@ -733,18 +760,18 @@ class RLConfig(BaseConfig):
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
get_logger().warning(
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank."
"make sure to set --enable_lora and --max-lora-rank.",
stacklevel=2,
)
return self
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
return self
@model_validator(mode="after")
@@ -752,13 +779,15 @@ class RLConfig(BaseConfig):
if self.trainer.enable_router_replay:
if self.inference is not None:
if self.inference.enable_return_routed_experts is False:
get_logger().warning(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True."
warnings.warn(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True.",
stacklevel=2,
)
self.inference.enable_return_routed_experts = True
else:
get_logger().warning(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server."
warnings.warn(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server.",
stacklevel=2,
)
return self
@@ -946,13 +975,12 @@ class RLConfig(BaseConfig):
def auto_setup_slurm_template(self):
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
templates_dir = find_package_resource("templates")
if templates_dir is not None:
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
return self
### Warnings
@@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.configs.shared import (
HeartbeatConfig,
RendererConfig,
SlurmConfig,
TrainerLogConfig,
WandbConfig,
@@ -21,7 +22,7 @@ from prime_rl.configs.trainer import (
SchedulerConfig,
TokenizerConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, find_package_resource
class BaseDataConfig(BaseModel):
@@ -172,6 +173,21 @@ class SFTConfig(BaseConfig):
# The tokenizer configuration
tokenizer: TokenizerConfig = TokenizerConfig()
# The renderer configuration (only used when use_renderer=True)
renderer: RendererConfig = RendererConfig()
use_renderer: Annotated[
bool,
Field(
description=(
"If True, tokenize SFT samples through the `renderers` library "
"(single render() + message_indices mask) instead of the default "
"`build_incremental_token_mask` path. Required for chat templates "
"that render position-dependently (e.g. Qwen3, Qwen3.5)."
),
),
] = False
# The data configuration
data: DataConfig = SFTDataConfig()
@@ -357,6 +373,55 @@ class SFTConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
if self.use_renderer and self.model.vlm is not None:
raise ValueError(
"use_renderer is not supported for VLMs. The renderer tokenizes "
"text-only message dicts client-side and cannot handle image inputs."
)
return self
@model_validator(mode="after")
def validate_renderer_args(self):
# pool_size is orchestrator-only. An in-process renderer pool exists
# to amortize tokenization across concurrent rollouts in the
# orchestrator (many async requests render at once, HF fast
# tokenizers release the GIL during Rust encoding, so a pool of N
# tokenizer copies parallelizes well). SFT has no such concurrency:
# the StatefulDataLoader is constructed with num_workers=0, so the
# main process tokenizes one example at a time, between training
# steps. Across DP, each rank already owns its own renderer — an
# implicit pool of size world_size. Pooling within a rank gives
# nothing on top of that. Reject so callers don't silently set a
# knob that does nothing; if SFT tokenization ever becomes a
# bottleneck the fix is num_workers on the dataloader, not a pool.
if self.renderer.pool_size is not None:
raise ValueError(
f"renderer.pool_size={self.renderer.pool_size!r} is only used by the orchestrator. "
"SFT tokenizes synchronously (num_workers=0) and already gets one renderer per DP "
"rank — an in-process pool adds nothing. If tokenization is a bottleneck, raise "
"num_workers on the dataloader instead."
)
if self.use_renderer:
return self
renderer_args_set = []
if self.renderer.name != "auto":
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
if self.renderer.tool_parser is not None:
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
if self.renderer.reasoning_parser is not None:
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
if renderer_args_set:
raise ValueError(
"Renderer-specific args set without use_renderer=True: "
f"{', '.join(renderer_args_set)}. Either enable the renderer or remove these knobs."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
@@ -425,11 +490,10 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
templates_dir = find_package_resource("templates")
if templates_dir is not None:
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
return self
@@ -132,6 +132,61 @@ class BaseModelConfig(BaseConfig):
] = None
class RendererConfig(BaseConfig):
"""Configures the client-side renderer (chat-template + response parsing).
Only consumed when ``orchestrator.use_renderer = true``. The renderer
owns both directions: render messages → token ids on the client, and
parse model output tokens → structured ``content`` / ``reasoning_content``
/ ``tool_calls``.
"""
name: Annotated[
str,
Field(
description=(
"Renderer to use for chat template tokenization. "
"Options: 'auto' (detect from tokenizer), 'qwen3', 'qwen3_vl', "
"'qwen3.5', 'glm5', 'glm4.5', 'minimax-m2', 'deepseek_v3', "
"'kimi_k2', 'kimi_k25', 'nemotron3', 'gpt_oss', 'default'."
),
),
] = "auto"
tool_parser: Annotated[
str | None,
Field(
description=(
"Name of a tool parser in renderers.parsers. Only consumed by "
"DefaultRenderer (model-specific renderers bake their own parsing "
"in). Options today: 'qwen3', 'qwen3.5', 'glm', 'deepseek_v3'."
),
),
] = None
reasoning_parser: Annotated[
str | None,
Field(
description=(
"Name of a reasoning parser in renderers.parsers. Only consumed "
"by DefaultRenderer. Options today: 'think'."
),
),
] = None
pool_size: Annotated[
int | None,
Field(
ge=1,
description=(
"Number of renderer slots shared across concurrent rollouts. "
"None keeps the verifiers default (1). Bump for long multi-turn "
"prompts where client-side jinja tokenization serializes."
),
),
] = None
class ElasticConfig(BaseConfig):
"""Configures elastic inference pool with DNS-based service discovery.
@@ -184,6 +239,14 @@ class ClientConfig(BaseConfig):
),
] = 30.0
wait_for_ready_timeout: Annotated[
int,
Field(
description="Timeout in seconds for waiting for the inference pool to become ready at startup. "
"Applies to both the static health check and elastic DNS-based discovery. Defaults to 1800 seconds.",
),
] = 1800
base_url: Annotated[
list[str],
Field(
@@ -354,6 +417,13 @@ class WandbConfig(BaseConfig):
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
entity: Annotated[
str | None,
Field(
description="The W&B entity to log to.",
),
] = None
name: Annotated[
str | None,
Field(
@@ -361,6 +431,20 @@ class WandbConfig(BaseConfig):
),
] = None
group: Annotated[
str | None,
Field(
description="The W&B group to use for logging.",
),
] = None
tags: Annotated[
list[str] | None,
Field(
description="The W&B tags to attach to the run.",
),
] = None
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
@@ -139,7 +139,13 @@ class LoRAConfig(BaseConfig):
target_modules: Annotated[
list[str],
Field(
description="Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') match any component in the module path. Regex patterns match anywhere in the name.",
description=(
"Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') "
"match any component in the module path. Regex patterns match anywhere in the name. "
"Names unknown to the current model are silently ignored, so defaults cover multiple architectures. "
"NemotronH note: 'experts' matches NonGatedGroupedExperts inside LatentMoE; 'fc1_latent_proj' and "
"'fc2_latent_proj' adapt the latent up/down projections. Add 'in_proj'/'out_proj' to also LoRA Mamba."
),
),
] = [
"q_proj",
@@ -150,6 +156,8 @@ class LoRAConfig(BaseConfig):
"up_proj",
"down_proj",
"experts",
"fc1_latent_proj",
"fc2_latent_proj",
]
modules_to_save: Annotated[
@@ -175,6 +183,13 @@ class DebugModelConfig(BaseConfig):
),
] = False
force_balanced_routing: Annotated[
bool,
Field(
description="If True, override MoE token-choice routing with a round-robin assignment so every expert receives an equal share of tokens. Intended for fake-data smoke tests where untrained routing would otherwise produce severe expert imbalance and OOM. Gating scores are still gathered from the override indices so the forward pass stays consistent.",
),
] = False
class ModelConfig(BaseModelConfig):
"""Configures the model for training."""
@@ -184,7 +199,7 @@ class ModelConfig(BaseModelConfig):
attn: Annotated[
AttnImplementation,
Field(
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3).",
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3, FA4 for fa4).",
),
] = "flash_attention_2"
@@ -284,6 +299,21 @@ class ModelConfig(BaseModelConfig):
),
] = 1
cp_style: Annotated[
Literal["ring", "ulysses"],
Field(
description=(
"Context parallelism communication style. "
"'ring' uses ring-attention all-gather/reduce-scatter (current default, "
"requires custom kernels per attention type). "
"'ulysses' uses all-to-all to redistribute Q/K/V from sequence-sharded "
"to head-sharded, runs vanilla attention locally on the full sequence, "
"then all-to-all back. Works out-of-the-box with any attention kernel "
"(softmax FA, linear attention, mamba, etc.)."
),
),
] = "ring"
impl: Annotated[
Literal["hf", "custom", "auto"],
Field(
@@ -315,6 +345,14 @@ class ModelConfig(BaseModelConfig):
),
] = True
fp8: Annotated[
bool,
Field(
description="Whether to use FP8 training via DeepGEMM. Replaces nn.Linear layers with FP8 blockwise linear "
"and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and model.impl='custom'.",
),
] = False
freeze_moe_router: Annotated[
bool,
Field(
@@ -368,12 +406,16 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3"]:
raise ValueError("CP is only supported with flash attention 2 or flash attention 3")
if self.cp > 1 and self.attn == "flash_attention_3" and self.impl != "custom":
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
# `_flash_attention_forward` which only wraps FA2.
raise ValueError(
"CP with flash_attention_3 requires model.impl='custom' "
"(the FA3 ring-attention kernel is only implemented for the custom model path)"
f"CP with {self.attn} requires model.impl='custom' "
"(FA3/FA4 paths are only implemented for the custom model attention class)"
)
return self
@@ -402,6 +444,12 @@ class ModelConfig(BaseModelConfig):
raise ValueError("Flash attention 4 is only supported with the custom implementation")
return self
@model_validator(mode="after")
def fp8_only_with_custom_impl(self):
if self.fp8 and self.impl not in ("custom", "auto"):
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
return self
@model_validator(mode="after")
def validate_ep_comm_backend(self):
if self.ep_comm_backend == "torch":
@@ -0,0 +1,56 @@
from pathlib import Path
from typing import Any
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
def find_package_resource(subdir: str) -> Path | None:
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
Returns None if `subdir` is not present in any wheel — e.g. on a slim
`prime-rl-configs`-only install where `prime-rl`'s shipped resources
(templates, etc.) are absent.
"""
import prime_rl
for p in prime_rl.__path__:
candidate = Path(p) / subdir
if candidate.is_dir():
return candidate
return None
def rgetattr(obj: Any, attr_path: str) -> Any:
"""Recursive getattr for dotted paths: rgetattr(cfg, "trainer.model.name")."""
current = obj
for attr in attr_path.split("."):
if not hasattr(current, attr):
raise AttributeError(f"'{type(current).__name__}' object has no attribute '{attr}'")
current = getattr(current, attr)
return current
def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
"""Recursive setattr for dotted paths: rsetattr(cfg, "trainer.model.name", "foo")."""
if "." not in attr_path:
return setattr(obj, attr_path, value)
parent_path, attr = attr_path.rsplit(".", 1)
setattr(rgetattr(obj, parent_path), attr, value)
def get_all_fields(model: BaseModel | type) -> list[str]:
if isinstance(model, BaseModel):
model_cls = model.__class__
else:
model_cls = model
fields = []
for name, field in model_cls.model_fields.items():
field_type = field.annotation
fields.append(name)
if field_type is not None and hasattr(field_type, "model_fields"):
sub_fields = get_all_fields(field_type)
fields.extend(f"{name}.{sub}" for sub in sub_fields)
return fields
+140 -46
View File
@@ -5,24 +5,23 @@ description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"prime-rl-configs",
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
"liger-kernel>=0.5.10",
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"pydantic>=1.10.13",
"pydantic-config",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"numpy>=2.2.6",
"torch>=2.9.0",
"torchvision",
"torchaudio",
"torchdata>=0.11.0",
"transformers",
"vllm>=0.19.0",
"wandb>=0.24.2",
"vllm>=0.20.2",
"wandb>=0.26.1",
"ring-flash-attn>=0.1.8",
"prime>=0.5.37",
"prime>=0.6.4",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
@@ -32,6 +31,7 @@ dependencies = [
"uvloop>=0.21.0",
"torchtitan",
"verifiers",
"renderers",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
@@ -51,7 +51,7 @@ prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
[project.optional-dependencies]
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-3 = ["flash_attn_3"]
@@ -59,20 +59,33 @@ flash-attn-cute = [
"flash-attn-4",
]
envs = [
"reverse-text",
"alphabet-sort",
"wiki-search",
"math-python",
"math-env",
"code-env",
"science-env",
"logic-env",
"color-codeword",
"math500",
"aime2024",
"aime2025",
"mini_swe_agent_plus",
"deepdive"
"alphabet-sort",
"code-env",
"color-codeword",
"deepdive",
"gpqa",
"hle",
"ifeval",
"livecodebench",
"logic-env",
"math-env",
"math-python",
"math500",
"mini-swe-agent-plus",
"mini-swe-agent-plus-rlm",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
"opencode-math",
"opencode-science",
"opencode-swe",
"reverse-text",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -91,6 +104,8 @@ all = [
"prime-rl[flash-attn]",
"prime-rl[disagg]",
"prime-rl[quack]",
"prime-rl[flash-attn-3]",
"prime-rl[flash-attn-cute]",
]
[dependency-groups]
@@ -106,7 +121,42 @@ dev = [
]
[tool.uv.workspace]
members = [
"packages/prime-rl-configs",
"deps/verifiers",
"deps/renderers",
"deps/verifiers/environments/alphabet_sort",
"deps/verifiers/environments/math_python",
"deps/verifiers/environments/reverse_text",
"deps/verifiers/environments/wiki_search",
"deps/research-environments/environments/aime2024",
"deps/research-environments/environments/aime2025",
"deps/research-environments/environments/code_env",
"deps/research-environments/environments/color_codeword",
"deps/research-environments/environments/deepdive",
"deps/research-environments/environments/gpqa",
"deps/research-environments/environments/hle",
"deps/research-environments/environments/ifeval",
"deps/research-environments/environments/livecodebench",
"deps/research-environments/environments/logic_env",
"deps/research-environments/environments/math500",
"deps/research-environments/environments/math_env",
"deps/research-environments/environments/mini_swe_agent_plus",
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
"deps/research-environments/environments/mmlu_pro",
"deps/research-environments/environments/opencode_cp",
"deps/research-environments/environments/opencode_deepdive",
"deps/research-environments/environments/opencode_math",
"deps/research-environments/environments/opencode_science",
"deps/research-environments/environments/opencode_swe",
"deps/research-environments/environments/science_env",
"deps/research-environments/environments/simpleqa_verified",
"deps/research-environments/environments/tau2_bench",
]
[tool.uv]
exclude-newer = "7 days"
preview = true
no-build-isolation-package = ["flash-attn"]
environments = [
@@ -119,34 +169,74 @@ override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"transformers>=5.1.0.dev0",
"torch>=2.9.0",
"openenv-core",
]
[tool.uv.exclude-newer-package]
# we want latest vllm, remove next patch
vllm = false
flash_attn_3 = false
# PrimeIntellect-published on PyPI (trusted publisher)
prime = false
prime-sandboxes = false
prime-tunnel = false
prime-evals = false
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
vllm-router = false
dion = false
pydantic-config = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
[tool.uv.sources]
prime-rl-configs = { workspace = true }
verifiers = { workspace = true }
renderers = { workspace = true }
aime2024 = { workspace = true }
aime2025 = { workspace = true }
alphabet-sort = { workspace = true }
code-env = { workspace = true }
color-codeword = { workspace = true }
deepdive = { workspace = true }
gpqa = { workspace = true }
hle = { workspace = true }
ifeval = { workspace = true }
livecodebench = { workspace = true }
logic-env = { workspace = true }
math-env = { workspace = true }
math-python = { workspace = true }
math500 = { workspace = true }
mini-swe-agent-plus = { workspace = true }
mini-swe-agent-plus-rlm = { workspace = true }
mmlu-pro = { workspace = true }
opencode-cp = { workspace = true }
opencode-deepdive = { workspace = true }
opencode-math = { workspace = true }
opencode-science = { workspace = true }
opencode-swe = { workspace = true }
reverse-text = { workspace = true }
science-env = { workspace = true }
simpleqa-verified = { workspace = true }
tau2-bench = { workspace = true }
wiki-search = { workspace = true }
torch = { index = "pytorch-cu128" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "0760204" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "abd9943b" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.20/vllm_router-0.1.20-cp38-abi3-manylinux_2_28_x86_64.whl" }
reverse-text = { index = "primeintellect" }
alphabet-sort = { index = "primeintellect" }
wiki-search = { index = "primeintellect" }
math-python = { index = "primeintellect" }
math-env = { index = "primeintellect" }
code-env = { index = "primeintellect" }
science-env = { index = "primeintellect" }
logic-env = { index = "primeintellect" }
color-codeword = { index = "primeintellect" }
math500 = { index = "primeintellect" }
aime2024 = { index = "primeintellect" }
aime2025 = { index = "primeintellect" }
deepdive = { index = "primeintellect" }
mini_swe_agent_plus = { index = "primeintellect" }
deep-ep = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
nixl-cu12 = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
flash_attn_3 = { index = "pytorch-cu128-test" }
@@ -158,17 +248,11 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
[[tool.uv.index]]
name = "primeintellect"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128-test"
url = "https://download.pytorch.org/whl/test/cu128"
@@ -178,8 +262,15 @@ explicit = true
select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
[tool.ruff.lint.isort]
# `prime_rl` is split across two workspace wheels (prime-rl + prime-rl-configs).
# Without this, ruff classifies prime_rl.configs.* as third-party because it
# doesn't live under src/.
known-first-party = ["prime_rl"]
[tool.ruff]
line-length = 120
extend-exclude = ["deps"]
[tool.pytest.ini_options]
addopts = "--strict-markers"
@@ -192,5 +283,8 @@ markers = [
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/prime_rl"]
[tool.hatch.metadata]
allow-direct-references = true
+1 -7
View File
@@ -14,10 +14,4 @@ export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --reinstall --no-deps \
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
SITE_PACKAGES=".venv/lib/python3.12/site-packages"
cp "$SITE_PACKAGES/flashinfer/data/cutlass/python/CuTeDSL/cutlass/utils/ampere_helpers.py" \
"$SITE_PACKAGES/nvidia_cutlass_dsl/python_packages/cutlass/utils/ampere_helpers.py"
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
+8
View File
@@ -4,5 +4,13 @@ set -e
# Set higher ulimit for file descriptors to prevent API timeout issues
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
"verifiers @ git+https://github.com/PrimeIntellect-ai/verifiers.git@${VERIFIERS_VERSION}"
fi
# Execute the main command
exec "$@"
+1 -1
View File
@@ -11,7 +11,7 @@
set -e
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
uv pip install --reinstall --no-deps "flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
# Verify installation
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
+115 -53
View File
@@ -4,86 +4,148 @@ set -euo pipefail
# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
REPO_ID="prime-rl"
# Flag defaults (can be overridden via env)
SKIP_CLONE=${SKIP_CLONE:-0}
assert_supported_platform() {
local os arch
os="$(uname -s)"
arch="$(uname -m)"
if [ "$os" != "Linux" ]; then
log_error "Unsupported platform: ${os}/${arch}."
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
exit 1
fi
case "$arch" in
x86_64 | aarch64) ;;
*)
log_error "Unsupported architecture: ${arch}."
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
exit 1
;;
esac
if ! command -v apt &>/dev/null; then
log_error "Unsupported Linux distribution: apt is required by this installer."
log_error "Use a Debian/Ubuntu-based Linux machine on x86_64 or aarch64, or install manually."
exit 1
fi
}
has_ssh_access() {
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
# We try a quick ls-remote to avoid cloning on failure.
# Disable -e for the probe so the script doesn't exit on a failed test.
set +e
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
rc=$?
set -e
return $rc
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
# We try a quick ls-remote to avoid cloning on failure.
# Disable -e for the probe so the script doesn't exit on a failed test.
set +e
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
rc=$?
set -e
return $rc
}
ensure_known_hosts() {
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
mkdir -p "${HOME}/.ssh"
chmod 700 "${HOME}/.ssh"
# Use -H to hash hostnames; merge uniquely to avoid dupes.
if command -v ssh-keyscan >/dev/null 2>&1; then
ssh-keyscan -H github.com 2>/dev/null | sort -u \
| tee -a "${HOME}/.ssh/known_hosts" >/dev/null
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
mkdir -p "${HOME}/.ssh"
chmod 700 "${HOME}/.ssh"
# Use -H to hash hostnames; merge uniquely to avoid dupes.
if command -v ssh-keyscan >/dev/null 2>&1; then
ssh-keyscan -H github.com 2>/dev/null | sort -u |
tee -a "${HOME}/.ssh/known_hosts" >/dev/null
chmod 600 "${HOME}/.ssh/known_hosts"
fi
}
# Initialize each submodule independently so that a missing private repo
# (e.g. configs/private when the user lacks access) does not abort the install.
init_submodules() {
if [ ! -f .gitmodules ]; then
return 0
fi
local paths failures
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
failures=()
for path in $paths; do
log_info "Initializing submodule: ${path}"
if git submodule update --init --recursive -- "$path"; then
:
else
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
failures+=("$path")
fi
done
if [ "${#failures[@]}" -gt 0 ]; then
log_warn "Skipped submodules: ${failures[*]}"
fi
}
main() {
# Ensure sudo exists
if ! command -v sudo &>/dev/null; then
apt update
apt install -y sudo
fi
assert_supported_platform
log_info "Installing base packages..."
sudo apt update && sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
# Ensure sudo exists
if ! command -v sudo &>/dev/null; then
apt update
apt install -y sudo
fi
log_info "Configuring SSH known_hosts for GitHub..."
ensure_known_hosts
log_info "Installing base packages..."
sudo apt update
sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
if [ "$SKIP_CLONE" -eq 1 ]; then
log_info "Skipping clone; assuming we are already inside the repo."
log_info "Configuring SSH known_hosts for GitHub..."
ensure_known_hosts
if [ "$SKIP_CLONE" -eq 1 ]; then
log_info "Skipping clone; assuming we are already inside the repo."
else
log_info "Determining best way to clone (SSH vs HTTPS)..."
if has_ssh_access; then
log_info "SSH access to GitHub works. Cloning via SSH."
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
else
log_info "Determining best way to clone (SSH vs HTTPS)..."
if has_ssh_access; then
log_info "SSH access to GitHub works. Cloning via SSH."
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
else
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
fi
log_info "Entering project directory..."
cd ${REPO_ID}
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
fi
log_info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
log_info "Entering project directory..."
cd ${REPO_ID}
fi
log_info "Sourcing uv environment..."
if ! command -v uv &> /dev/null; then
source $HOME/.local/bin/env
fi
if ! has_ssh_access; then
git config url."https://github.com/".insteadOf "git@github.com:"
fi
log_info "Installing prime..."
uv tool install prime
log_info "Initializing submodules..."
init_submodules
log_info "Syncing virtual environment..."
uv sync --all-extras
log_info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
log_info "Installing pre-commit hooks..."
uv run pre-commit install
log_info "Sourcing uv environment..."
if ! command -v uv &>/dev/null; then
source $HOME/.local/bin/env
fi
log_info "Installation completed!"
log_info "Installing prime..."
uv tool install prime
log_info "Syncing virtual environment..."
uv sync --all-extras
log_info "Installing pre-commit hooks..."
uv run pre-commit install
log_info "Installation completed!"
}
main
main
+11 -5
View File
@@ -1,14 +1,20 @@
#!/usr/bin/env bash
# Build and install DeepGEMM from source for FP8 MoE inference.
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
#
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
# and is what `pyproject.toml` consumes by default; this script is for
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
#
# Uses the commit recommended by vLLM for compatibility with vLLM 0.17+.
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
#
# Usage:
# bash scripts/install_deep_gemm.sh
# bash scripts/install_deep_gemm.sh # build + install in-place
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
#
# Options:
# --ref REF DeepGEMM commit hash (default: 477618c)
# --ref REF DeepGEMM commit hash (default: d30fc36)
# --wheel-dir DIR Output wheel to DIR instead of installing
set -euo pipefail
@@ -17,7 +23,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
DEEPGEMM_GIT_REF="477618cd51baffca09c4b0b87e97c03fe827ef03"
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
WHEEL_DIR=""
while [[ $# -gt 0 ]]; do
+55
View File
@@ -23,6 +23,8 @@ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.laguna import LagunaConfig
from prime_rl.trainer.models.laguna import LagunaForCausalLM as PrimeRLLagunaForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
@@ -130,6 +132,59 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
"laguna": {
"config_class": LagunaConfig,
"config_kwargs": dict(
vocab_size=100352,
hidden_size=512,
intermediate_size=2048,
num_hidden_layers=12,
num_attention_heads=8,
num_attention_heads_per_layer=[8] * 12,
num_key_value_heads=4,
head_dim=64,
hidden_act="silu",
max_position_embeddings=4096,
rms_norm_eps=1e-6,
rope_parameters={
"full_attention": {
"rope_type": "yarn",
"rope_theta": 500000.0,
"factor": 4.0,
"original_max_position_embeddings": 1024,
"beta_slow": 1.0,
"beta_fast": 64.0,
"attention_factor": 1.0,
"partial_rotary_factor": 0.5,
},
"sliding_attention": {
"rope_type": "default",
"rope_theta": 10000.0,
"partial_rotary_factor": 1.0,
},
},
layer_types=["full_attention", "sliding_attention", "sliding_attention", "sliding_attention"] * 3,
sliding_window=512,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=8,
num_experts_per_tok=4,
mlp_layer_types=["dense"] + ["sparse"] * 11,
moe_routed_scaling_factor=2.5,
use_grouped_mm=False,
pad_token_id=9,
bos_token_id=2,
eos_token_id=[2, 24],
auto_map={
"AutoConfig": "poolside/Laguna-XS.2--configuration_laguna.LagunaConfig",
"AutoModel": "poolside/Laguna-XS.2--modeling_laguna.LagunaModel",
"AutoModelForCausalLM": "poolside/Laguna-XS.2--modeling_laguna.LagunaForCausalLM",
},
),
"hf_model_class": None, # uses Poolside remote modeling code
"prime_model_class": PrimeRLLagunaForCausalLM,
"tokenizer_source": "poolside/Laguna-XS.2",
},
"qwen3_5_moe_vlm": {
"config_fn": _qwen3_5_moe_vlm_config,
"hf_model_class": HFQwen3_5MoeVLM,
+5
View File
@@ -153,6 +153,10 @@ uv run sft --data.type fake --data.batch-size 4
If you wish to configure values of the default variant, you don't need to set the `type` field.
### SFT hard distill override
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
### Model fields
For `BaseModel | None` fields (like `[ckpt]`, `[wandb]`, `[compile]`), a bare flag enables them with defaults:
@@ -173,4 +177,5 @@ In TOML, an empty section header does the same:
- `src/prime_rl/utils/config.py` — re-exports `BaseConfig` and `cli` from pydantic_config
- `src/prime_rl/configs/` — all domain-specific config classes
- `configs/debug/` — minimal debug configs for testing
- `configs/private/` — private configs via git submodule (internal only)
- `examples/` — full example configs for various tasks
+1
View File
@@ -88,4 +88,5 @@ curl http://localhost:8000/v1/chat/completions \
- `src/prime_rl/entrypoints/` — top-level entrypoints (`rl`, `sft`, `inference`)
- `src/prime_rl/configs/` — all config classes
- `configs/debug/` — minimal configs for quick testing
- `configs/private/` — private configs submodule (if access granted)
- `examples/` — full example configs for various tasks
+25 -1
View File
@@ -5,13 +5,37 @@ description: How to install prime-rl and its optional dependencies. Use when set
# Installation
## Cloning
prime-rl is a monorepo with submodules. Clone the repo first, then initialize submodules explicitly:
```bash
git clone git@github.com:PrimeIntellect-ai/prime-rl.git
cd prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
```
For an existing clone, initialize the public submodules by passing explicit paths:
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
```
Do **not** use `git submodule update --init --recursive` without explicit paths — it will also attempt to clone `configs/private` (a private submodule) and fail with "Repository not found" for users without access. Git will retry the clone once internally before aborting, which is expected behavior.
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, and `deps/research-environments/`. Each is also a uv workspace member, so source edits inside them apply to the prime-rl venv without re-sync.
The install script (`scripts/install.sh`) handles the private submodule gracefully — it iterates each submodule individually so a failed `configs/private` init does not abort the rest.
## Basic
```bash
uv sync # core dependencies only
uv sync --group dev # dev tools: pytest, ruff, pre-commit
uv sync --all-extras # recommended: includes flash-attn, flash-attn-cute, etc.
uv sync --all-extras # recommended: includes envs, flash-attn, flash-attn-cute, etc.
```
The `envs` extra installs the env packages listed in `pyproject.toml > [tool.uv.workspace] members`. Adding a new env means adding it there, in the `envs` extra, and in `[tool.uv.sources]`.
## Advanced
### Mamba-SSM (NemotronH models)
+2
View File
@@ -145,6 +145,8 @@ These tell you whether training is healthy or diverging.
|--------|--------|-------------|
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
| `entropy/mean` | trainer | policy entropy |
| `masked_advantage_positive/mean` | trainer | fraction of DPPO-masked trainable tokens with positive advantage (W&B) |
| `masked_advantage_negative/mean` | trainer | fraction of DPPO-masked trainable tokens with negative advantage (W&B) |
| `optim/grad_norm` | trainer | gradient norm — spikes may precede divergence |
#### Performance
-1
View File
@@ -1 +0,0 @@
import prime_rl._compat # noqa: F401 — must run before ring_flash_attn is imported
+48 -14
View File
@@ -1,21 +1,55 @@
"""Compatibility shim: ring_flash_attn + transformers >= 5.4.
"""Compatibility shims for upstream regressions.
ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
`transformers.modeling_flash_attention_utils`. This symbol was removed from
that module in transformers 5.4 (still available as a deprecated function
in `transformers.utils.import_utils`, scheduled for removal in 5.8).
ring_flash_attn's except-branch is a no-op (imports the same symbol again),
so the import crashes on transformers >= 5.4. We patch the symbol back in as
`True` — the check is dead code since no one uses flash_attn < 2.1.0 anymore.
Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
Remove this shim once ring_flash_attn ships a fixed version.
Imported early (before any model code) by trainer and orchestrator entrypoints.
Each shim documents the upstream issue and removal condition.
"""
# ---------------------------------------------------------------------------
# ring_flash_attn + transformers >= 5.4
#
# ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
# `transformers.modeling_flash_attention_utils`, removed in transformers 5.4.
#
# Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
# Remove once ring_flash_attn ships a fixed version.
# ---------------------------------------------------------------------------
import transformers.modeling_flash_attention_utils as _mfau
if not hasattr(_mfau, "is_flash_attn_greater_or_equal_2_10"):
# ring_flash_attn uses this as a bare value (if x:), but other code may
# call it as a function (if x():). Use a callable that is also truthy.
_mfau.is_flash_attn_greater_or_equal_2_10 = lambda: True
# ---------------------------------------------------------------------------
# transformers >= 5.5 hub_kernels offline regression
#
# lazy_load_kernel() resolves kernel versions via HfApi().list_repo_refs(),
# which raises OfflineModeIsEnabled when HF_HUB_OFFLINE=1 — even if the
# kernel is already cached locally. Only FileNotFoundError and AssertionError
# are caught; OfflineModeIsEnabled (a ConnectionError subclass) is not.
#
# This breaks Mamba-based models (NemotronH, Zamba2, Jamba, etc.) on SLURM
# worker nodes where HF_HUB_OFFLINE=1 is set.
#
# Fix: patch the except clause to also catch ConnectionError.
# Remove once huggingface/transformers fixes lazy_load_kernel offline handling.
# ---------------------------------------------------------------------------
try:
import transformers.integrations.hub_kernels as _hub_kernels
except ImportError:
_hub_kernels = None # transformers < 5.5, no patch needed
if _hub_kernels is not None:
from huggingface_hub.errors import OfflineModeIsEnabled
_original_lazy_load_kernel = _hub_kernels.lazy_load_kernel
def _patched_lazy_load_kernel(kernel_name, mapping=_hub_kernels._KERNEL_MODULE_MAPPING):
try:
return _original_lazy_load_kernel(kernel_name, mapping)
except OfflineModeIsEnabled:
# Return None so NemotronH skips hub kernels; prime-rl's
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
mapping[kernel_name] = None
return None
_hub_kernels.lazy_load_kernel = _patched_lazy_load_kernel
+2 -4
View File
@@ -45,6 +45,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
disaggregated=is_disaggregated,
kv_offload=config.kv_cache_offload is not None,
)
is_multi_node = config.deployment.type == "multi_node"
@@ -63,10 +64,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
use_deep_gemm=config.use_deep_gemm,
prefill_env_overrides=config.deployment.prefill_env_overrides,
decode_env_overrides=config.deployment.decode_env_overrides,
kv_offload=config.deployment.kv_cache_offload is not None,
kv_offload_cpu_bytes=int(config.deployment.kv_cache_offload.cpu_bytes)
if config.deployment.kv_cache_offload
else 0,
kv_offload_cpu_bytes=int(config.kv_cache_offload.cpu_bytes) if config.kv_cache_offload else 0,
)
elif is_multi_node:
template_vars.update(
+24 -8
View File
@@ -12,7 +12,9 @@ from threading import Event, Thread
import pynvml
import tomli_w
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
from prime_rl.configs.rl import RLConfig
from prime_rl.trainer.model import pre_download_model
from prime_rl.utils.config import cli
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
@@ -347,10 +349,10 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing trainer logs...")
logger.success("Startup complete. Showing orchestrator logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
f"tail -F '{log_dir / 'orchestrator.log'}'",
shell=True,
)
processes.append(tail_process)
@@ -443,8 +445,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
prefill_env_overrides=infer_deploy.prefill_env_overrides,
decode_env_overrides=infer_deploy.decode_env_overrides,
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
kv_offload=infer_deploy.kv_cache_offload is not None,
kv_offload_cpu_bytes=int(infer_deploy.kv_cache_offload.cpu_bytes) if infer_deploy.kv_cache_offload else 0,
kv_offload=config.inference.kv_cache_offload is not None,
kv_offload_cpu_bytes=int(config.inference.kv_cache_offload.cpu_bytes)
if config.inference.kv_cache_offload
else 0,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
wandb_shared=config.wandb is not None and config.wandb.shared,
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
@@ -468,6 +472,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
kv_offload=config.inference is not None and config.inference.kv_cache_offload is not None,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
wandb_shared=config.wandb is not None and config.wandb.shared,
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
@@ -547,15 +552,26 @@ def rl(config: RLConfig):
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
# Clean stale artifacts from steps after the resume point
# Clean stale rollouts and broadcasts. When resuming, anything past the resume
# step is stale. When training from scratch, every existing step directory is
# stale — without this, a fresh run in a dirty output_dir would pick up rollouts
# from a previous run and the orchestrator would see a negative async level.
resume_step: int | None = None
if resuming:
resume_step = config.ckpt.resume_step
if resume_step == -1:
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.output_dir
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
if resume_step is not None:
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
clean_future_steps(config.output_dir, resume_step)
if resume_step is not None:
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
clean_future_steps(config.output_dir, resume_step)
else:
get_logger().info("Training from scratch, cleaning any stale rollouts and broadcasts")
clean_future_steps(config.output_dir, -1)
if not config.dry_run:
pre_download_model(config.trainer.model.name)
if config.slurm is not None:
rl_slurm(config)
+5
View File
@@ -8,7 +8,9 @@ from threading import Event, Thread
import tomli_w
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
from prime_rl.configs.sft import SFTConfig
from prime_rl.trainer.model import pre_download_model
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
@@ -196,6 +198,9 @@ def sft(config: SFTConfig):
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if not config.dry_run:
pre_download_model(config.model.name)
if config.slurm is not None:
sft_slurm(config)
else:
+297 -280
View File
@@ -3,7 +3,7 @@ from vllm.triton_utils import tl, triton
def transformers_v5_compat():
"""vLLM general plugin: patch transformers v5 config attrs that vLLM 0.16 still expects.
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
in every vLLM process, including spawned workers.
@@ -16,8 +16,39 @@ def transformers_v5_compat():
_patch_qwen35_lora()
_patch_lora_key_prefix()
monkey_patch_deep_gemm_ep_scatter()
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_dp_engine_core_pause_resume_deadlock()
monkey_patch_offloading_connector_cpu_block_count()
monkey_patch_vllm_layerwise_reload_alias_buffers()
def monkey_patch_vllm_layerwise_reload_alias_buffers():
# vLLM's layerwise reload materializes each buffer as an independent tensor
# and then copies it back into the original kernel storage. When a buffer
# aliases a parameter (e.g. NemotronH Mamba's mixer.conv_weights, a view of
# mixer.conv1d.weight), the buffer copy stamps garbage into the parameter's
# storage *after* the parameter has been correctly reloaded. Skip the copy
# for any buffer that shares storage with a parameter; _place_kernel_tensors
# re-registers the original view, which trivially reflects the parameter.
from vllm.logger import init_logger
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
logger = init_logger(__name__)
def _copy_and_restore_kernel_tensors(layer: torch.nn.Module, info: reload_layerwise.LayerReloadingInfo):
assert info.kernel_tensors is not None
parameters, buffers = info.kernel_tensors
param_storage_ptrs = {p.untyped_storage().data_ptr() for p in layer.parameters(recurse=True)}
for name, param in parameters.items():
param.data.copy_(getattr(layer, name))
for name, buffer in buffers.items():
if buffer.untyped_storage().data_ptr() in param_storage_ptrs:
continue
buffer.data.copy_(getattr(layer, name))
reload_layerwise._place_kernel_tensors(layer, info)
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
@triton.jit
@@ -174,6 +205,140 @@ def monkey_patch_deep_gemm_ep_scatter():
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM ep_scatter.")
@triton.jit
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
y_ptr,
y_q_ptr,
y_s_ptr,
M: tl.int64,
N: tl.int64,
y_s_col_stride: tl.int64,
eps,
fp8_min: tl.constexpr,
fp8_max: tl.constexpr,
use_ue8m0: tl.constexpr,
GROUP_SIZE: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
N_2 = N // 2
m_offset = (pid_m * BLOCK_M).to(tl.int64)
n_offset = (pid_n * BLOCK_N).to(tl.int64)
if m_offset >= M:
return
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
base_y_ptr = y_ptr + m_offset * N + n_offset
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
act_in = tl.load(act_in_ptrs)
mul_in = tl.load(act_in_ptrs + N_2)
act_in = act_in.to(tl.float32)
one_f32 = tl.cast(1, tl.float32)
silu_out = (act_in / (one_f32 + tl.exp(-act_in))).to(y_ptr.dtype.element_ty)
y = (silu_out * mul_in).to(tl.float32)
absmax = tl.maximum(tl.max(tl.abs(y), axis=1), eps)
scale_raw = absmax * (1.0 / fp8_max)
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
y_s = tl.reshape(y_s, (BLOCK_M, 1))
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
base_y_q_ptr = y_q_ptr + m_offset * N_2 + n_offset
y_q_ptrs = base_y_q_ptr + offs_m[:, None] * N_2 + offs_n[None, :]
tl.store(y_q_ptrs, y_q)
group_id = n_offset // GROUP_SIZE
base_y_s_ptr = y_s_ptr + group_id * y_s_col_stride + m_offset
y_s_ptrs = base_y_s_ptr + offs_m
y_s = tl.reshape(y_s, (BLOCK_M,))
tl.store(y_s_ptrs, y_s)
def _silu_mul_per_token_group_quant_fp8_colmajor_int64(
input: torch.Tensor,
output: torch.Tensor | None = None,
use_ue8m0: bool | None = None,
eps: float = 1e-10,
):
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
group_size = 128
assert input.ndim == 2
if output is not None:
assert output.ndim == 2
assert input.size(0) % group_size == 0
assert input.size(1) % (group_size * 2) == 0
if use_ue8m0 is None:
use_ue8m0 = is_deep_gemm_e8m0_used()
M, N = input.size()
N_2 = N // 2
fp8_dtype = current_platform.fp8_dtype()
if output is None:
output = torch.empty((M, N_2), dtype=fp8_dtype, device=input.device)
output_scales = torch.empty(((N_2 // group_size), M), dtype=torch.float32, device=input.device).transpose(0, 1)
block_m = 8
block_n = group_size
assert M % block_m == 0
assert N_2 % block_n == 0
finfo = torch.finfo(fp8_dtype)
fp8_min = -224.0 if current_platform.is_fp8_fnuz() else finfo.min
fp8_max = 224.0 if current_platform.is_fp8_fnuz() else finfo.max
grid = (M // block_m, N_2 // block_n)
_silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel[grid](
input,
output,
output_scales,
M,
N,
output_scales.stride(-1),
eps,
fp8_min,
fp8_max,
use_ue8m0,
group_size,
block_m,
block_n,
)
return output, output_scales
def monkey_patch_deep_gemm_silu_mul_quant_int64():
# Temporary local carry for large DeepGEMM profile shapes whose row offsets
# exceed signed int32 address arithmetic in vLLM's Triton kernel.
import sys
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.utils import fp8_utils
logger = init_logger(__name__)
fp8_utils.silu_mul_per_token_group_quant_fp8_colmajor = _silu_mul_per_token_group_quant_fp8_colmajor_int64
deep_gemm_moe_module = sys.modules.get("vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe")
if deep_gemm_moe_module is not None:
deep_gemm_moe_module.silu_mul_per_token_group_quant_fp8_colmajor = (
_silu_mul_per_token_group_quant_fp8_colmajor_int64
)
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
def _patch_qwen35_lora():
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
@@ -195,6 +360,7 @@ def _patch_qwen35_lora():
from vllm.model_executor.models.qwen3_5 import (
Qwen3_5ForCausalLMBase,
Qwen3_5ForConditionalGeneration,
Qwen3_5MoeForConditionalGeneration,
)
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
@@ -202,6 +368,8 @@ def _patch_qwen35_lora():
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
@classmethod
@@ -302,10 +470,14 @@ def _patch_lora_key_prefix():
# is embedded: "...experts.N.down_proj". Taking everything
# after ".experts" gives "experts.N.down_proj" which is
# never in the expected set even though "down_proj" is.
# Fix: always compare just the last component of the path.
# Qwen3-30B-A3B goes the other way: the expected set
# contains the fully-qualified per-expert name
# ("experts.N.down_proj") but not the bare suffix.
# Accept either form.
if ".experts" in module_name:
expert_suffix = module_name.split(".")[-1]
if expert_suffix not in expected_lora_modules:
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
unexpected_modules.append(module_name)
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
@@ -478,6 +650,65 @@ def monkey_patch_LRUCacheWorkerLoRAManager():
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
# recompiling regex patterns inside is_supported_lora_module — purely to emit
# logger.warning_once about modules that will be ignored. Adapter validity is
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
def monkey_patch_skip_lora_module_warnings():
from vllm.exceptions import LoRAAdapterNotFoundError
from vllm.lora.lora_model import LoRAModel
from vllm.lora.peft_helper import PEFTHelper
from vllm.lora.request import LoRARequest
from vllm.lora.utils import get_adapter_absolute_path
from vllm.lora.worker_manager import WorkerLoRAManager
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
try:
supported_lora_modules = self._adapter_manager.supported_lora_modules
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
expected_lora_lst: list[str] = []
for module in supported_lora_modules:
if module in packed_modules_mapping:
expected_lora_lst.extend(packed_modules_mapping[module])
else:
expected_lora_lst.append(module)
if module == "experts":
expected_lora_lst.append(module)
expected_lora_modules = set(expected_lora_lst)
lora_path = get_adapter_absolute_path(lora_request.lora_path)
peft_helper = PEFTHelper.from_local_dir(
lora_path,
self.max_position_embeddings,
lora_request.tensorizer_config_dict,
)
peft_helper.validate_legal(self.lora_config)
model = self._adapter_manager.model
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
lora = self._lora_model_cls.from_local_checkpoint(
lora_path,
expected_lora_modules,
peft_helper=peft_helper,
lora_model_id=lora_request.lora_int_id,
device="cpu",
dtype=self.lora_config.lora_dtype,
model_vocab_size=self.vocab_size,
tensorizer_config_dict=lora_request.tensorizer_config_dict,
weights_mapper=hf_to_vllm_mapper,
skip_prefixes=lora_skip_prefixes,
)
except FileNotFoundError as e:
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
return lora
WorkerLoRAManager._load_adapter = _patched_load_adapter
# Monkeypatch TokenizeParams to fix overly conservative validation
def monkey_patch_tokenize_params_validation():
"""
@@ -649,239 +880,6 @@ def monkey_patch_harmony_stop_token_propagation():
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
def monkey_patch_fused_moe_lora_dp():
"""Fix: LoRA + MoE + DP>1 produces corrupted output in vLLM 0.17.0.
Two bugs:
1. LoRA injection sets supports_internal_mk=True (via moe_kernel not None),
causing the MoE runner to skip DP dispatch/combine. But the LoRA kernel
uses NoDPEP and doesn't handle DP internally.
2. LoRA decorators capture full-batch tensors but fire per-chunk inside the
kernel's chunk loop. At DP>=3, dispatched batch > CHUNK_SIZE causes
shape mismatches.
Fix: Replace _inject_lora_into_fused_moe with a version that:
(a) sets moe_kernel=None so the runner correctly dispatches
(b) makes decorators chunk-aware by tracking chunk offsets
Upstream: https://github.com/vllm-project/vllm/issues/23244
"""
import types
from vllm import envs
from vllm.distributed.utils import divide
from vllm.lora.layers.fused_moe import FusedMoEWithLoRA
from vllm.model_executor.layers.fused_moe.config import _get_config_dtype_str
from vllm.model_executor.layers.fused_moe.fused_marlin_moe import MarlinExperts
from vllm.model_executor.layers.fused_moe.fused_moe import TritonExperts
from vllm.model_executor.layers.fused_moe.fused_moe_modular_method import FusedMoEModularMethod
from vllm.model_executor.layers.fused_moe.gpt_oss_triton_kernels_moe import UnfusedOAITritonExperts
from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel
from vllm.model_executor.layers.fused_moe.prepare_finalize import MoEPrepareAndFinalizeNoDPEPModular
def _fixed_inject(self):
moe_state_dict = {}
top_k = self.base_layer.top_k
self.base_layer.ensure_moe_quant_config_init()
quant_config = self.base_layer.quant_method.moe_quant_config
if getattr(self.base_layer.quant_method, "supports_internal_mk", False):
m_fused_moe_fn = self.base_layer.quant_method.moe_kernel
m_fused_moe_fn.shared_experts = None
else:
prepare_finalize = MoEPrepareAndFinalizeNoDPEPModular()
m_fused_moe_fn = FusedMoEKernel(
prepare_finalize,
self.base_layer.quant_method.select_gemm_impl(prepare_finalize, self.base_layer),
)
if quant_config.use_mxfp4_w4a16:
assert isinstance(m_fused_moe_fn.impl.fused_experts, (MarlinExperts, UnfusedOAITritonExperts))
else:
assert isinstance(m_fused_moe_fn.impl.fused_experts, TritonExperts)
# --- Decorators (chunk-aware) ---
def fwd_decorator(layer, func):
def wrapper(*args, **kwargs):
moe_state_dict["hidden_states"] = kwargs["hidden_states"]
moe_state_dict["topk_ids"] = kwargs["topk_ids"]
moe_state_dict["topk_weights"] = kwargs["topk_weights"]
moe_state_dict["expert_map"] = kwargs["expert_map"]
moe_state_dict["apply_router_weight_on_input"] = kwargs["apply_router_weight_on_input"]
moe_state_dict["_chunk_offset"] = 0
return func(*args, **kwargs)
return wrapper
def act_decorator(layer, func):
def wrapper(*args, **kwargs):
_, output, input = args
chunk_M = input.view(-1, top_k, input.shape[-1]).shape[0]
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
curr_topk_ids = moe_state_dict["topk_ids"][chunk_offset : chunk_offset + chunk_M]
expert_map = moe_state_dict["expert_map"]
config_dtype = _get_config_dtype_str(
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
)
num_tokens = hidden_states.size(0)
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
max_lora_rank = self.w13_lora_a_stacked[0].shape[-2]
shrink_config, expand_config = self._get_lora_moe_configs(
op_prefix="w13",
num_loras=self.max_loras,
rank=max_lora_rank,
num_slices=self._w13_slices,
M=M,
layer=layer,
top_k=top_k,
config_dtype=config_dtype,
)
SPARSITY_FACTOR = 8
naive_block_assignment = (
expert_map is None
and num_tokens * top_k * SPARSITY_FACTOR <= self.base_layer.local_num_experts * self.max_loras
)
token_lora_mapping, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora = (
self.punica_wrapper.moe_lora_align_block_size(
curr_topk_ids,
num_tokens,
shrink_config["BLOCK_SIZE_M"],
self.base_layer.local_num_experts,
self.max_loras,
self.adapter_enabled,
expert_map,
naive_block_assignment=naive_block_assignment,
)
)
moe_state_dict["sorted_token_ids_lora"] = sorted_token_ids_lora
moe_state_dict["expert_ids_lora"] = expert_ids_lora
moe_state_dict["num_tokens_post_padded_lora"] = num_tokens_post_padded_lora
moe_state_dict["token_lora_mapping"] = token_lora_mapping
if sorted_token_ids_lora is not None:
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
self.punica_wrapper.add_lora_fused_moe(
input.view(-1, top_k, input.shape[-1]),
hidden_states,
self.w13_lora_a_stacked,
self.w13_lora_b_stacked,
topk_weights,
sorted_token_ids_lora,
expert_ids_lora,
num_tokens_post_padded_lora,
max_lora_rank,
top_k,
shrink_config,
expand_config,
self.adapter_enabled,
fully_sharded=self.fully_sharded,
token_lora_mapping=token_lora_mapping,
)
result = func(*args, **kwargs)
moe_state_dict["intermediate_cache2"] = output
moe_state_dict["_chunk_M"] = chunk_M
return result
return wrapper
def moe_sum_decorator(layer, func):
def wrapper(*args, **kwargs):
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
chunk_M = moe_state_dict.get("_chunk_M", moe_state_dict["hidden_states"].size(0))
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
config_dtype = _get_config_dtype_str(
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
)
num_tokens = hidden_states.size(0)
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
max_lora_rank = self.w2_lora_a_stacked[0].shape[-2]
shrink_config, expand_config = self._get_lora_moe_configs(
op_prefix="w2",
num_loras=self.max_loras,
rank=max_lora_rank,
num_slices=1,
M=M,
layer=layer,
top_k=top_k,
config_dtype=config_dtype,
)
sorted_token_ids_lora = moe_state_dict["sorted_token_ids_lora"]
expert_ids_lora = moe_state_dict["expert_ids_lora"]
num_tokens_post_padded_lora = moe_state_dict["num_tokens_post_padded_lora"]
token_lora_mapping = moe_state_dict.get("token_lora_mapping")
if sorted_token_ids_lora is not None:
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
intermediate_cache2 = moe_state_dict["intermediate_cache2"]
intermediate_cache3 = args[0]
shard_size_w2 = divide(self.base_layer.hidden_size, self.tp_size)
self.punica_wrapper.add_lora_fused_moe(
intermediate_cache3,
intermediate_cache2,
self.w2_lora_a_stacked,
self.w2_lora_b_stacked,
topk_weights,
sorted_token_ids_lora,
expert_ids_lora,
num_tokens_post_padded_lora,
max_lora_rank,
top_k,
shrink_config,
expand_config,
self.adapter_enabled,
True,
fully_sharded=self.fully_sharded,
offset=shard_size_w2 * self.tp_rank if self.fully_sharded else 0,
token_lora_mapping=token_lora_mapping,
)
result = func(*args, **kwargs)
moe_state_dict["_chunk_offset"] = chunk_offset + chunk_M
return result
return wrapper
# --- Install decorators and replace quant method ---
fused_experts = m_fused_moe_fn.impl.fused_experts
m_fused_moe_fn.apply = fwd_decorator(self.base_layer, m_fused_moe_fn.apply)
fused_experts.activation = act_decorator(self.base_layer, fused_experts.activation)
fused_experts.moe_sum = moe_sum_decorator(self.base_layer, fused_experts.moe_sum)
new_method = FusedMoEModularMethod(self.base_layer.quant_method, m_fused_moe_fn)
# Bug 1 fix: NoDPEP kernel makes supports_internal_mk=True, causing the
# runner to skip DP dispatch/combine. Set moe_kernel=None and patch apply().
if isinstance(m_fused_moe_fn.prepare_finalize, MoEPrepareAndFinalizeNoDPEPModular):
saved_kernel = new_method.moe_kernel
saved_disable_expert_map = new_method.disable_expert_map
new_method.moe_kernel = None
def _apply_with_saved_kernel(self, layer, x, topk_weights, topk_ids, shared_experts_input):
return saved_kernel.apply(
hidden_states=x,
w1=layer.w13_weight,
w2=layer.w2_weight,
topk_weights=topk_weights,
topk_ids=topk_ids,
activation=layer.activation,
global_num_experts=layer.global_num_experts,
apply_router_weight_on_input=layer.apply_router_weight_on_input,
expert_map=None if saved_disable_expert_map else layer.expert_map,
shared_experts_input=shared_experts_input,
)
new_method.apply = types.MethodType(_apply_with_saved_kernel, new_method)
self.base_layer._replace_quant_method(new_method)
FusedMoEWithLoRA._inject_lora_into_fused_moe = _fixed_inject
def monkey_patch_dp_engine_core_pause_resume_deadlock():
"""Fix DP pause/resume deadlocks around weight updates.
@@ -954,49 +952,6 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
def monkey_patch_offloading_connector_cpu_block_count():
"""Fix CPU block count miscalculation in OffloadingConnector.
CPUOffloadingSpec erroneously multiplies page_size_bytes by
len(kv_cache_config.kv_cache_tensors) when computing kv_bytes_per_block.
For UniformTypeKVCacheSpecs the page_size is already the total per-block
size across all layers, so the extra multiplier makes num_blocks far too
small. When the OffloadingManager later allocates block IDs past the
undersized CPU tensor, swap_blocks (cuMemcpyDtoHAsync_v2) segfaults on the
invalid pinned address.
Fix: remove the num_tensors multiplier.
Upstream: https://github.com/vllm-project/vllm/pull/38395
Related: https://github.com/vllm-project/vllm/issues/39500
"""
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
_original_init = CPUOffloadingSpec.__init__
def _patched_init(self, vllm_config, kv_cache_config):
_original_init(self, vllm_config, kv_cache_config)
# Recalculate num_blocks WITHOUT the erroneous num_tensors multiplier.
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
if not cpu_bytes_to_use:
return
page_sizes = {g.kv_cache_spec.page_size_bytes for g in kv_cache_config.kv_cache_groups}
assert len(page_sizes) == 1
page_size_bytes = page_sizes.pop()
# page_size_bytes already covers all layers in the group.
# Only multiply by world_size (each TP rank stores its own copy).
kv_bytes_per_block = page_size_bytes * vllm_config.parallel_config.world_size
kv_bytes_per_offloaded_block = kv_bytes_per_block * self.block_size_factor
self.num_blocks = (
int(cpu_bytes_to_use) // kv_bytes_per_offloaded_block if kv_bytes_per_offloaded_block > 0 else 0
)
CPUOffloadingSpec.__init__ = _patched_init
def monkey_patch_no_moe_lora():
"""This disables LoRA for MoE layers and makes them pick better kernels.
@@ -1023,3 +978,65 @@ def monkey_patch_no_moe_lora():
self.is_lora_enabled = False
FusedMoEConfig.__post_init__ = _patched__post_init__
def monkey_patch_fp32_lm_head():
"""Run the lm_head projection in fp32, via a native bf16xbf16 -> fp32 GEMM.
Uses ``torch.mm(..., out_dtype=torch.float32)`` (PyTorch >= 2.10) so the
matmul accumulates and emits fp32 directly without zero-padding the bf16
operands or maintaining a separate fp32 weight copy. This avoids the
epilogue truncation to bf16 that `F.linear(bf16, bf16)` does, which is
where lm_head precision actually leaks before the sampler's softmax.
Activated by setting ``additional_config["fp32_lm_head"] = True`` on the
vLLM namespace; the launcher does this when ``inference.enable_fp32_lm_head``
is set. The flag is captured once on ``LogitsProcessor.__init__`` (where
vLLM guarantees a ``set_current_vllm_config()`` context) and stored on the
instance — reading it from ``_get_logits`` during serving doesn't work
because vLLM doesn't keep the context set during forwards.
Tracks vllm-project/vllm#24567 (which uses the operand-upcast approach).
Per @Jackmin801 on PR #2438, native ``out_dtype=fp32`` mm is more efficient
and just as correct.
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.layers.logits_processor import LogitsProcessor
logger = init_logger(__name__)
_original_init = LogitsProcessor.__init__
_original_get_logits = LogitsProcessor._get_logits
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
vllm_config = get_current_vllm_config()
additional_config = vllm_config.additional_config or {}
self._fp32_lm_head_enabled = additional_config.get("fp32_lm_head", False)
if self._fp32_lm_head_enabled:
logger.warning("fp32 lm_head ENABLED for this LogitsProcessor instance.")
def _patched_get_logits(self, hidden_states, lm_head, embedding_bias):
if not getattr(self, "_fp32_lm_head_enabled", False):
return _original_get_logits(self, hidden_states, lm_head, embedding_bias)
# Native bf16xbf16 -> fp32 GEMM. torch.mm requires 2D inputs; vLLM v1's
# generative path passes 2D [num_tokens, hidden_size] hidden_states, but
# flatten defensively in case some future caller passes 3D.
flat = hidden_states.reshape(-1, hidden_states.shape[-1])
logits = torch.mm(flat, lm_head.weight.t(), out_dtype=torch.float32)
if embedding_bias is not None:
logits = logits + embedding_bias.to(torch.float32)
if hidden_states.dim() > 2:
logits = logits.reshape(*hidden_states.shape[:-1], -1)
logits = self._gather_logits(logits)
if logits is not None:
logits = logits[..., : self.org_vocab_size]
return logits
LogitsProcessor.__init__ = _patched_init
LogitsProcessor._get_logits = _patched_get_logits
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
+81 -57
View File
@@ -1,3 +1,4 @@
import asyncio
from argparse import Namespace
from http import HTTPStatus
from typing import Any
@@ -151,7 +152,7 @@ monkey_patch_harmony_stop_token_propagation()
# May be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
monkey_patch_load_lora_adapter()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.19 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
logger = init_logger("vllm.entrypoints.openai.api_server")
@@ -182,59 +183,6 @@ def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
return request.app.state.openai_serving_chat_with_tokens
@router.post("/pause")
async def pause(request: Request):
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
return {"status": "paused"}
@router.post("/resume")
async def resume(request: Request):
await engine_client(request).resume_generation()
return {"status": "resumed"}
@router.post("/update_weights")
async def update_weights(request: Request):
data = await request.json()
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
if request.app.state.reset_prefix_cache_after_update:
await engine_client(request).reset_prefix_cache()
return {"status": "ok"}
@router.post("/load_lora_adapter")
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
"""Load a LoRA adapter, optionally resetting the prefix cache.
Wrapper around vLLM's /v1/load_lora_adapter that also resets the prefix cache
to invalidate KV states computed with old weights (unless disabled via config).
"""
handler = models(raw_request)
response = await handler.load_lora_adapter(lora_request)
if isinstance(response, ErrorResponse):
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
if raw_request.app.state.reset_prefix_cache_after_update:
await engine_client(raw_request).reset_prefix_cache()
return {"status": "ok"}
@router.post("/init_broadcaster")
async def init_broadcaster(request: Request):
data = await request.json()
host = data.get("host")
port = data.get("port")
timeout = data.get("timeout")
rank_offset = data.get("rank_offset")
inference_world_size = data.get("inference_world_size")
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
await engine_client(request).collective_rpc(
"init_broadcaster",
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
)
return {"status": "ok"}
@router.post(
"/v1/chat/completions/tokens",
dependencies=[Depends(validate_json_request)],
@@ -261,6 +209,64 @@ async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_reques
return StreamingResponse(content=generator, media_type="text/event-stream")
@router.post("/pause")
async def pause(request: Request):
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
return {"status": "paused"}
@router.post("/resume")
async def resume(request: Request):
await engine_client(request).resume_generation()
return {"status": "resumed"}
@router.post("/update_weights")
async def update_weights(request: Request):
data = await request.json()
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
return {"status": "ok"}
@router.post("/load_lora_adapter")
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
"""Wrapper around vLLM's /v1/load_lora_adapter."""
handler = models(raw_request)
response = await handler.load_lora_adapter(lora_request)
if isinstance(response, ErrorResponse):
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
return {"status": "ok"}
@router.get("/liveness")
async def liveness(raw_request: Request):
"""Check that the engine event loop can service a no-op worker RPC."""
try:
await asyncio.wait_for(
engine_client(raw_request).collective_rpc("liveness_probe"),
timeout=raw_request.app.state.liveness_timeout_seconds,
)
except asyncio.TimeoutError:
return JSONResponse({"status": "engine_unresponsive"}, status_code=503)
return {"status": "ok"}
@router.post("/init_broadcaster")
async def init_broadcaster(request: Request):
data = await request.json()
host = data.get("host")
port = data.get("port")
timeout = data.get("timeout")
rank_offset = data.get("rank_offset")
inference_world_size = data.get("inference_world_size")
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
await engine_client(request).collective_rpc(
"init_broadcaster",
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
)
return {"status": "ok"}
async def custom_init_app_state(
engine_client: EngineClient,
state: State,
@@ -269,13 +275,21 @@ async def custom_init_app_state(
):
"""
Modifies init_app_state:
1. Call the original init_app_state to set up standard state.
2. Replace the serving_chat with our OpenAIServingChatWithTokens wrapper.
1. Call the original init_app_state to set up standard state, including
vLLM 0.20's ``serving_tokens`` for ``/inference/v1/generate``.
2. Replace ``serving_chat`` with our ``OpenAIServingChatWithTokens`` wrapper
so the ``/v1/chat/completions/tokens`` (TITO) endpoint can stream
token IDs alongside the rendered chat completion.
3. Replace ``serving_tokens`` with ``PrimeRlServingTokens`` so DP-rank
routing and ``routed_experts`` export survive the migration off the
legacy ``/v1/generate`` endpoint.
"""
await init_app_state(engine_client, state, args, supported_tasks)
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
state.liveness_timeout_seconds = args.liveness_timeout_seconds
# TITO: server-side chat templating + token IDs.
if "generate" in supported_tasks and state.openai_serving_chat is not None:
original_chat = state.openai_serving_chat
serving_chat = object.__new__(OpenAIServingChatWithTokens)
@@ -285,6 +299,17 @@ async def custom_init_app_state(
else:
state.openai_serving_chat_with_tokens = None
# Swap in our ServingTokens subclass for /inference/v1/generate so the
# X-data-parallel-rank header and routed_experts response field — both
# used by prime-RL's renderer / router-replay paths — keep working.
if "generate" in supported_tasks and state.serving_tokens is not None:
from prime_rl.inference.vllm.serving_tokens import PrimeRlServingTokens
upstream = state.serving_tokens
prime_serving = object.__new__(PrimeRlServingTokens)
prime_serving.__dict__.update(upstream.__dict__)
state.serving_tokens = prime_serving
import vllm.entrypoints.openai.api_server
import vllm.v1.utils
@@ -342,7 +367,6 @@ def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
args.enable_auto_tool_choice = args.tool_call_parser is not None
args.reset_prefix_cache_after_update = config.experimental.reset_prefix_cache_after_update
if args.tool_call_parser is not None:
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
@@ -1,8 +1,6 @@
import base64
from collections.abc import AsyncGenerator, AsyncIterator
from typing import ClassVar, Optional, Union
import numpy as np
from fastapi import Request
from pydantic import Field
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest, ChatCompletionResponse
@@ -16,28 +14,17 @@ from vllm.outputs import RequestOutput
from vllm.reasoning import ReasoningParser
from vllm.sampling_params import BeamSearchParams, SamplingParams
from prime_rl.inference.vllm.serving_tokens import _RoutedExpertsCaptureBase
logger = init_logger(__name__)
class _RoutedExpertsCapture:
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
self._generator = generator
self.routed_experts: dict[int, dict] = {}
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
"""Chat-endpoint variant: mutates choices in-place because
``ChatCompletionResponseChoice`` is ``extra='allow'``, so an extra
``routed_experts`` attribute survives serialization."""
def _encode_routed_experts(self, arr: np.ndarray) -> dict:
return {
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
"shape": list(arr.shape),
}
async def __aiter__(self):
async for request_output in self._generator:
for output in request_output.outputs:
if output.routed_experts is not None:
self.routed_experts[output.index] = self._encode_routed_experts(output.routed_experts)
yield request_output
def post_process(self, response: ChatCompletionResponse):
def post_process(self, response: ChatCompletionResponse) -> None:
for choice in response.choices:
if choice.index in self.routed_experts:
choice.routed_experts = self.routed_experts[choice.index]
@@ -0,0 +1,321 @@
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
vLLM 0.20 ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs and
priority. Three prime-RL features are not in the upstream protocol though, so
we subclass it to add them back:
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
header and forwarded to ``engine_client.generate``. The DP-replicated
inference servers prime-RL runs need this to target a specific replica.
2. ``routed_experts`` per-token export — when the engine emits routing
decisions (``enable_return_routed_experts``), surface them on each choice.
This is what the trainer's router-replay path consumes.
3. Server-side ``max_tokens`` defaulting — ``ServingTokens`` hands the
client-supplied ``SamplingParams`` to the engine verbatim, and
``SamplingParams.max_tokens`` defaults to ``16`` (a dataclass-level
default that predates the OpenAI-compat layer). Every other vLLM
endpoint masks this server-side via
``vllm.entrypoints.utils.get_max_tokens`` (see e.g.
``OpenAIServingChat`` at ``serving.py:284``); the disagg endpoint
skips that path. Mirror it here so callers that omit ``max_tokens``
don't silently truncate at 16. Drop once vLLM patches upstream.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
"""
from __future__ import annotations
import base64
from collections.abc import AsyncGenerator
from functools import cached_property
import numpy as np
from fastapi import Request
from pydantic import Field
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
from vllm.entrypoints.serve.disagg.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
)
from vllm.entrypoints.serve.disagg.serving import ServingTokens
from vllm.entrypoints.utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
routed_experts: dict | None = Field(
default=None,
description=(
"Per-token expert routing decisions (base85-encoded int32 array + shape). "
"Populated only when the engine was launched with "
"``enable_return_routed_experts=True``; otherwise ``None``."
),
)
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
def encode_routed_experts(arr: np.ndarray) -> dict:
return {
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
"shape": list(arr.shape),
}
class _RoutedExpertsCaptureBase:
"""Wraps the engine result generator and accumulates a
``{output_index: encoded_experts}`` map as outputs stream. Subclasses
implement ``post_process`` to fold the captured map into the response
in whatever shape the endpoint returns (in-place vs rebuilt)."""
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
self._generator = generator
self.routed_experts: dict[int, dict] = {}
async def __aiter__(self):
async for request_output in self._generator:
for output in request_output.outputs:
if output.routed_experts is not None:
self.routed_experts[output.index] = encode_routed_experts(output.routed_experts)
yield request_output
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
"""Generate-endpoint variant: rebuilds the response with
``PrimeRlGenerateResponseChoice`` because upstream's
``GenerateResponseChoice`` isn't ``extra='allow'``, so an attribute
set after construction wouldn't survive serialization."""
def post_process(self, response: GenerateResponse) -> PrimeRlGenerateResponse:
new_choices = [
PrimeRlGenerateResponseChoice(
**choice.model_dump(),
routed_experts=self.routed_experts.get(choice.index),
)
for choice in response.choices
]
return PrimeRlGenerateResponse(
request_id=response.request_id,
choices=new_choices,
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
instance, which means an unset ``max_tokens`` is indistinguishable from
an explicit ``max_tokens=16`` once the request reaches the handler —
both surface as ``sampling_params.max_tokens == 16``. We re-read the
cached body to recover that distinction. When we can't (no raw_request,
non-JSON body, or read error), pessimistically assume the client did
set it so we never clobber an explicit value.
"""
if raw_request is None:
return True
try:
body = await raw_request.json()
except Exception:
return True
if not isinstance(body, dict):
return True
sp = body.get("sampling_params")
return isinstance(sp, dict) and "max_tokens" in sp
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + DP-rank routing + routed_experts export + max_tokens defaulting."""
@cached_property
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
"""Server-side ``max_tokens`` defaulting inputs, mirroring ``OpenAIServingChat``.
Computed lazily because ``custom_init_app_state`` swaps in this
subclass via ``object.__new__`` + ``__dict__.update`` (so our
``__init__`` never runs).
"""
diff = self.model_config.get_diff_sampling_param()
mc = self.model_config
override = (
diff.get("max_tokens")
if mc.generation_config not in ("auto", "vllm")
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
# in case a downstream caller ever sets the attribute to ``None``
# (``getattr``'s default only fires when the attribute is missing,
# not when it exists with a ``None`` value).
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
)
return diff, override
async def serve_tokens(
self,
request: GenerateRequest,
raw_request: Request | None = None,
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.20). Diffs:
# (a) inject ``data_parallel_rank`` from the inbound header into
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
# (c) dispatch to our overridden response builder so ``routed_experts``
# makes it into the JSON.
error_check_ret = await self._check_model(request)
if error_check_ret is not None:
return error_check_ret
if self.engine_client.errored:
raise self.engine_client.dead_error
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
model_name = self.models.model_name(lora_request)
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
request_metadata = RequestResponseMetadata(request_id=request_id)
if raw_request:
raw_request.state.request_metadata = request_metadata
# Build the engine input — features-aware (MM) or text-only fallback.
# Identical to upstream so we keep tracking it.
if features := request.features:
from vllm.entrypoints.serve.disagg.mm_serde import decode_mm_kwargs_item
from vllm.inputs import mm_input
from vllm.multimodal.inputs import (
MultiModalKwargsItem,
PlaceholderRange,
)
mm_placeholders = {
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
for modality, ranges in features.mm_placeholders.items()
}
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
if features.kwargs_data is not None:
for modality, items in features.kwargs_data.items():
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
else:
for modality, hashes in features.mm_hashes.items():
mm_kwargs[modality] = [None] * len(hashes)
engine_input = mm_input(
prompt_token_ids=request.token_ids,
mm_kwargs=mm_kwargs, # type: ignore[arg-type]
mm_hashes=features.mm_hashes,
mm_placeholders=mm_placeholders,
cache_salt=request.cache_salt,
)
else:
(engine_input,) = await self.openai_serving_render.preprocess_completion(
request,
prompt_input=request.token_ids,
prompt_embeds=None,
skip_mm_cache=True,
)
sampling_params: SamplingParams = request.sampling_params
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
# but never threads it into the engine, so PD disagg never fires on
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
# and ends up re-prefilling the prompt locally (~100× slower under
# concurrency). The chat path bridges this via
# ``ChatCompletionRequestWithTokens.to_sampling_params``; we mirror that
# bridge here so the engine's KV connector picks the params up out of
# ``sampling_params.extra_args``.
#
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
# this block once we pin a vLLM version that includes it.
if request.kv_transfer_params is not None:
extra = sampling_params.extra_args or {}
extra["kv_transfer_params"] = request.kv_transfer_params
sampling_params.extra_args = extra
# Server-side ``max_tokens`` defaulting — see module docstring.
# Mirrors ``OpenAIServingChat`` (vllm/entrypoints/openai/chat_completion/
# serving.py:284) so callers that omit ``max_tokens`` don't get capped
# at vLLM's 16-token ``SamplingParams`` default.
if not await _client_set_max_tokens(raw_request):
diff_sp, override = self._max_tokens_defaults
sampling_params.max_tokens = get_max_tokens(
max_model_len=self.model_config.max_model_len,
max_tokens=None,
input_length=len(request.token_ids),
default_sampling_params=diff_sp,
override_max_tokens=override,
)
if self.force_no_detokenize:
sampling_params.detokenize = False
if request.stream:
sampling_params.output_kind = RequestOutputKind.DELTA
self._log_inputs(
request_id,
engine_input,
params=sampling_params,
lora_request=lora_request,
)
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
result_generator = self.engine_client.generate(
engine_input,
sampling_params,
request_id,
lora_request=lora_request,
trace_headers=trace_headers,
priority=request.priority,
data_parallel_rank=self._get_data_parallel_rank(raw_request),
)
if request.stream:
# Streaming path: defer to upstream — prime-RL's renderer client
# only consumes the full response, so adding routed_experts to the
# streaming choice schema is unnecessary churn.
return self.serve_tokens_stream_generator(
request,
result_generator,
request_id,
model_name,
request_metadata,
)
return await self.serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
async def serve_tokens_full_generator( # type: ignore[override]
self,
request: GenerateRequest,
result_generator: AsyncGenerator[RequestOutput, None],
request_id: str,
model_name: str,
request_metadata: RequestResponseMetadata,
) -> ErrorResponse | GenerateResponse:
# Mirror serving_chat_with_tokens: wrap the result generator to capture
# routed_experts as it streams, defer the rest to upstream, then post-
# process the response into our PrimeRlGenerateResponse subclass so the
# encoded experts surface in the JSON. Skipping the wrapper when the
# engine isn't producing routed experts keeps us a no-op subclass on
# the common path.
capture: _RoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
capture = _RoutedExpertsCapture(result_generator)
result_generator = capture # type: ignore[assignment]
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
if capture is not None and isinstance(response, GenerateResponse):
response = capture.post_process(response)
return response
@@ -2,15 +2,20 @@ import logging
import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_LRUCacheWorkerLoRAManager,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
monkey_patch_skip_lora_module_warnings,
)
logger = logging.getLogger(__name__)
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
monkey_patch_LRUCacheWorkerLoRAManager()
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
monkey_patch_skip_lora_module_warnings()
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
monkey_patch_minimax_m2_for_lora()
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
@@ -19,3 +24,6 @@ if os.environ.get("PRIME_NO_MOE_LORA") == "1":
monkey_patch_no_moe_lora()
else:
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()

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