Compare commits

..
Author SHA1 Message Date
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
54 changed files with 2332 additions and 657 deletions
+56
View File
@@ -38,3 +38,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
+1
View File
@@ -2,6 +2,7 @@
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)
+2 -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,7 @@ 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 configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
+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
@@ -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):
@@ -390,6 +400,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(
@@ -450,10 +467,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")
@@ -500,6 +516,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",
@@ -536,6 +553,13 @@ class InferenceConfig(BaseConfig):
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
# 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
@@ -17,7 +18,6 @@ from prime_rl.configs.shared import (
)
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):
@@ -149,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
@@ -248,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
@@ -685,6 +689,52 @@ 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."""
@@ -692,11 +742,11 @@ class DefaultAdvantageConfig(BaseModel):
type: Literal["default"] = "default"
length_penalty: Annotated[
Literal["tokens", "turns"] | None,
LengthPenaltyConfig | None,
Field(
description=(
"Cost metric for correctness-gated length penalty. `tokens` shapes by completion-token "
"count, `turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
"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."
@@ -1103,15 +1153,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
@@ -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,
@@ -745,9 +745,10 @@ 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
@@ -763,13 +764,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
@@ -957,13 +960,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
@@ -21,7 +21,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):
@@ -425,11 +425,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
@@ -299,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(
@@ -330,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(
@@ -386,9 +409,13 @@ class ModelConfig(BaseModelConfig):
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(
f"CP with {self.attn} requires model.impl='custom' "
"(the ring-attention kernel is only implemented for the custom model path)"
"(FA3/FA4 paths are only implemented for the custom model attention class)"
)
return self
@@ -417,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
+27 -11
View File
@@ -5,21 +5,20 @@ 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",
"vllm>=0.20.1",
"wandb>=0.26.1",
"ring-flash-attn>=0.1.8",
"prime>=0.5.73",
@@ -51,7 +50,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"]
@@ -108,6 +107,9 @@ dev = [
]
[tool.uv.workspace]
members = ["packages/*"]
[tool.uv]
exclude-newer = "7 days"
preview = true
@@ -125,8 +127,8 @@ override-dependencies = [
]
[tool.uv.exclude-newer-package]
# pytorch-cu128 / pytorch-cu128-test indexes don't publish upload dates
torch = false
# we want latest vllm, remove next patch
vllm = false
flash_attn_3 = false
# Self-vendored packages on our primeintellect index
reverse-text = false
@@ -158,7 +160,10 @@ deep-gemm = false
nixl-cu12 = false
[tool.uv.sources]
prime-rl-configs = { workspace = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3b77145" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
@@ -180,9 +185,11 @@ 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" }
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
# DeepGEMM bumped from 477618c to d30fc36 (newer kernel APIs needed by the
# FP8 grouped-GEMM training path). Rebuild via scripts/install_deep_gemm.sh.
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-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" }
@@ -214,6 +221,12 @@ 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
@@ -228,5 +241,8 @@ markers = [
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/prime_rl"]
[tool.hatch.metadata]
allow-direct-references = true
+86 -54
View File
@@ -4,86 +4,118 @@ 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
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
log_info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
log_info "Installing prime..."
uv tool install prime
log_info "Sourcing uv environment..."
if ! command -v uv &>/dev/null; then
source $HOME/.local/bin/env
fi
log_info "Syncing virtual environment..."
uv sync --all-extras
log_info "Installing prime..."
uv tool install prime
log_info "Installing pre-commit hooks..."
uv run pre-commit install
log_info "Syncing virtual environment..."
uv sync --all-extras
log_info "Installation completed!"
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
-1
View File
@@ -1 +0,0 @@
import prime_rl._compat # noqa: F401 — must run before ring_flash_attn is imported
+1
View File
@@ -12,6 +12,7 @@ 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
+1
View File
@@ -8,6 +8,7 @@ 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
+63 -275
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.
@@ -17,7 +17,6 @@ def transformers_v5_compat():
_patch_lora_key_prefix()
monkey_patch_deep_gemm_ep_scatter()
monkey_patch_dp_engine_core_pause_resume_deadlock()
monkey_patch_offloading_connector_cpu_block_count()
@triton.jit
@@ -715,239 +714,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.
@@ -1020,46 +786,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 derives kv_bytes_per_block from page_size_bytes multiplied
by len(kv_cache_config.kv_cache_tensors), which double-counts: page_size is
already aggregated across layers in the group. The undersized CPU pool then
produces out-of-bounds block mappings and swap_blocks segfaults.
Fix: derive kv_bytes_per_block from the actual total GPU KV tensor size
divided by num_blocks, matching the upstream PR.
Upstream: https://github.com/vllm-project/vllm/pull/39617
"""
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)
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
if not cpu_bytes_to_use:
return
if kv_cache_config.num_blocks > 0:
total_gpu_kv_bytes = sum(t.size for t in kv_cache_config.kv_cache_tensors)
kv_bytes_per_block = (
total_gpu_kv_bytes // kv_cache_config.num_blocks
) * vllm_config.parallel_config.world_size
else:
kv_bytes_per_block = 0
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.
@@ -1086,3 +812,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).")
+3 -3
View File
@@ -153,14 +153,13 @@ 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")
# Create our own router for custom endpoints
router = APIRouter()
LIVENESS_TIMEOUT_SECONDS = 5.0
def engine_client(request: Request) -> EngineClient:
@@ -272,7 +271,7 @@ async def liveness(raw_request: Request):
try:
await asyncio.wait_for(
engine_client(raw_request).collective_rpc("liveness_probe"),
timeout=LIVENESS_TIMEOUT_SECONDS,
timeout=raw_request.app.state.liveness_timeout_seconds,
)
except asyncio.TimeoutError:
return JSONResponse({"status": "engine_unresponsive"}, status_code=503)
@@ -312,6 +311,7 @@ async def custom_init_app_state(
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:
@@ -2,6 +2,7 @@ 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,
@@ -23,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()
+31 -17
View File
@@ -1,17 +1,21 @@
from dataclasses import dataclass
from typing import Callable, Literal
from typing import Callable
import torch
import verifiers as vf
from jaxtyping import Float
from torch import Tensor
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
LengthPenaltyConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
)
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns, get_tool_response_len
from prime_rl.utils.utils import import_object
LengthPenalty = Literal["tokens", "turns"]
@dataclass
class AdvantageInputs:
@@ -42,18 +46,27 @@ Expected signature:
def default_advantage_fn(
inputs: AdvantageInputs,
length_penalty: LengthPenalty | None = None,
length_penalty: LengthPenaltyConfig | None = None,
) -> AdvantageOutputs:
"""Default GRPO advantage: reward minus per-problem baseline."""
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
"""Default GRPO advantage: reward minus per-problem baseline.
if length_penalty == "tokens":
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
cost: tokens (weighted completion + tool-response) or trajectory turn count.
"""
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts], dtype=torch.float32)
if isinstance(length_penalty, TokensLengthPenaltyConfig):
w_c = length_penalty.completion_weight
w_t = length_penalty.tool_response_weight
costs = torch.tensor(
[[get_model_completion_len(r) for r in group] for group in inputs.rollouts],
[
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in group]
for group in inputs.rollouts
],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
if length_penalty == "turns":
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
costs = torch.tensor(
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
dtype=rewards.dtype,
@@ -88,8 +101,12 @@ def _efficiency_shaping(
correct_costs = costs * correct_mask
mean_correct_cost = correct_costs.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
has_cost = mean_correct_cost > 0
safe_mean = torch.where(has_cost, mean_correct_cost, torch.ones_like(mean_correct_cost))
bonus = (1 - costs / safe_mean).clamp(0, 1) * has_cost
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
shaped_rewards = rewards * (1 + bonus * correct_mask)
@@ -112,10 +129,7 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(
inputs,
length_penalty=config.length_penalty,
)
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
return advantage_fn
@@ -5,6 +5,7 @@ import time
import tomli_w
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
from prime_rl.orchestrator.advantage import compute_advantages
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
+15
View File
@@ -64,6 +64,21 @@ def get_num_turns(output: vf.RolloutOutput) -> int:
return len(output["trajectory"])
def get_tool_response_len(output: vf.RolloutOutput) -> int:
"""
Total tool-response tokens consumed across the whole rollout.
Read from a harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`,
deduped across turns/branches/sub-RLMs). Returns 0 if no harness metric is
present, which makes this a no-op for envs without tool-response accounting.
"""
metrics = output.get("metrics") or {}
for key, value in metrics.items():
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
return int(value)
return 0
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts to a JSONL file using verifiers serialization."""
path.parent.mkdir(parents=True, exist_ok=True)
@@ -52,6 +52,7 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
export VLLM_CACHE_ROOT=/tmp/.vllm_cache_$(whoami)
# Setup environment
@@ -66,6 +66,7 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
{% if wandb_shared -%}
export WANDB_SHARED_MODE=1
@@ -36,6 +36,7 @@ ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
+5
View File
@@ -43,6 +43,7 @@ from prime_rl.trainer.models.layers.checkpointing import (
set_selective_activation_checkpointing,
supports_selective_activation_checkpointing,
)
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
from prime_rl.trainer.parallel_dims import ParallelDims
@@ -470,6 +471,7 @@ def get_model(
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.use_grouped_mm = config.moe_use_grouped_mm
model_config.fp8 = config.fp8
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
@@ -1040,6 +1042,9 @@ def setup_model(
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
if config.fp8:
replace_linear_with_fp8_blockwise_linear(model)
# Apply LoRA before FSDP setup
if config.lora is not None:
apply_lora_to_model(model, config.lora)
@@ -353,6 +353,7 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
top_k=config.num_experts_per_tok,
use_grouped_mm=getattr(config, "use_grouped_mm", True),
load_balance_coeff=getattr(config, "load_balance_coeff", None),
fp8=getattr(config, "fp8", False),
)
if self.moe_enabled:
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
@@ -68,6 +68,7 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
top_k=config.num_experts_per_tok,
load_balance_coeff=1e-3,
use_grouped_mm=config.use_grouped_mm,
fp8=getattr(config, "fp8", False),
)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
@@ -65,6 +65,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
top_k=config.num_experts_per_tok,
load_balance_coeff=1e-3,
use_grouped_mm=config.use_grouped_mm,
fp8=getattr(config, "fp8", False),
)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
@@ -83,6 +83,9 @@ class GptOssMoE(nn.Module):
def __init__(self, config: GptOssConfig):
super().__init__()
# GptOssGroupedExperts has fused gate_up_proj + per-expert biases; the
# current FP8 grouped-GEMM path doesn't model that yet.
assert not getattr(config, "fp8", False), "FP8 training is not supported for GPT-OSS"
self.num_experts = config.num_local_experts
self.top_k = config.num_experts_per_tok
self.router = GptOssTopKRouter(config)
@@ -304,6 +307,10 @@ class GptOssForCausalLM(GptOssPreTrainedModel, GenerationMixin):
temperature: torch.Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
"""
assert use_cache is None or not use_cache, "use_cache is not supported for custom GPT-OSS"
assert past_key_values is None, "past_key_values is not supported for custom GPT-OSS"
@@ -0,0 +1,546 @@
from __future__ import annotations
from typing import Tuple
import torch
import triton
import triton.language as tl
FP8_MAX = 448.0
MIN_SCALE = 1e-4
GROUP_ALIGNMENT = 128
def ceil_div(x: int, y: int) -> int:
return (x + y - 1) // y
def align(x: int, y: int) -> int:
return ceil_div(x, y) * y
# ---------------------------------------------------------------------------
# Layout building
# ---------------------------------------------------------------------------
def build_grouped_layout(offs: torch.Tensor, *, total_m: int | None = None):
assert offs.dim() == 1
assert offs.dtype == torch.int32
device = offs.device
total_m = (total_m if total_m is not None else int(offs[-1].item())) if offs.numel() else 0
starts_tensor = torch.empty_like(offs)
if offs.numel() > 0:
starts_tensor[0] = 0
if offs.numel() > 1:
starts_tensor[1:] = offs[:-1]
actual_ms_tensor = offs - starts_tensor
aligned_ms_tensor = ((actual_ms_tensor + GROUP_ALIGNMENT - 1) // GROUP_ALIGNMENT) * GROUP_ALIGNMENT
padded_ends = aligned_ms_tensor.cumsum(0)
block_starts_tensor = (padded_ends - aligned_ms_tensor) // GROUP_ALIGNMENT
ks_tensor = aligned_ms_tensor.contiguous()
padded_total_m = int(padded_ends[-1].item()) if offs.numel() else 0
total_blocks = padded_total_m // GROUP_ALIGNMENT
grouped_layout = torch.empty((padded_total_m,), dtype=torch.int32, device=device)
block_to_group = torch.empty((total_blocks,), dtype=torch.int32, device=device)
if offs.numel():
_build_grouped_layout_triton(
grouped_layout,
block_to_group,
starts_tensor,
actual_ms_tensor,
aligned_ms_tensor,
block_starts_tensor,
)
return (
total_m,
padded_total_m,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
def _build_grouped_layout_triton(
grouped_layout: torch.Tensor,
block_to_group: torch.Tensor,
starts_tensor: torch.Tensor,
actual_ms_tensor: torch.Tensor,
aligned_ms_tensor: torch.Tensor,
block_starts_tensor: torch.Tensor,
) -> None:
_build_grouped_layout_kernel[(actual_ms_tensor.numel(),)](
grouped_layout,
block_to_group,
starts_tensor,
actual_ms_tensor,
aligned_ms_tensor,
block_starts_tensor,
BLOCK_M=128,
num_warps=4,
)
# ---------------------------------------------------------------------------
# Triton kernels
# ---------------------------------------------------------------------------
@triton.jit
def _build_grouped_layout_kernel(
grouped_layout_ptr,
block_to_group_ptr,
starts_ptr,
actual_ms_ptr,
aligned_ms_ptr,
block_starts_ptr,
BLOCK_M: tl.constexpr,
):
pid_g = tl.program_id(axis=0)
actual_m = tl.load(actual_ms_ptr + pid_g)
aligned_m = tl.load(aligned_ms_ptr + pid_g)
block_start = tl.load(block_starts_ptr + pid_g)
dst_start = block_start * BLOCK_M
block_idx = 0
while block_idx < (aligned_m // BLOCK_M):
row_offsets = block_idx * BLOCK_M + tl.arange(0, BLOCK_M)
values = tl.where(row_offsets < actual_m, pid_g, -1)
tl.store(grouped_layout_ptr + dst_start + row_offsets, values)
tl.store(block_to_group_ptr + block_start + block_idx, pid_g)
block_idx += 1
@triton.jit
def _unpack_grouped_rows_kernel(
x_ptr,
block_to_group_ptr,
starts_ptr,
actual_ms_ptr,
block_starts_ptr,
out_ptr,
cols,
stride_xm,
stride_xn,
stride_ym,
stride_yn,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
GROUP_BLOCK_M: tl.constexpr,
):
pid_blk = tl.program_id(axis=0)
pid_sub = tl.program_id(axis=1)
pid_n = tl.program_id(axis=2)
pid_g = tl.load(block_to_group_ptr + pid_blk)
block_start = tl.load(block_starts_ptr + pid_g)
dst_start = tl.load(starts_ptr + pid_g)
actual_m = tl.load(actual_ms_ptr + pid_g)
row_offsets = (pid_blk - block_start) * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
valid_rows = row_offsets < actual_m
valid_cols = col_offsets < cols
x = tl.load(
x_ptr
+ (pid_blk * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M))[:, None] * stride_xm
+ col_offsets[None, :] * stride_xn,
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
)
tl.store(
out_ptr + (dst_start + row_offsets)[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
x,
mask=valid_rows[:, None] & valid_cols[None, :],
)
@triton.jit
def _per_token_fp8_kernel(
x_ptr,
out_ptr,
sf_ptr,
rows,
cols,
stride_xm,
stride_xn,
stride_ym,
stride_yn,
stride_sm,
stride_sk,
USE_UE8M0: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_K: tl.constexpr,
):
pid_m = tl.program_id(axis=0)
pid_k = tl.program_id(axis=1)
row_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
col_offsets = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
mask = (row_offsets[:, None] < rows) & (col_offsets[None, :] < cols)
x = tl.load(
x_ptr + row_offsets[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
mask=mask,
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
tl.store(
out_ptr + row_offsets[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
y.to(tl.float8e4nv),
mask=mask,
)
tl.store(sf_ptr + row_offsets * stride_sm + pid_k * stride_sk, scale, mask=row_offsets < rows)
@triton.jit
def _grouped_per_token_fp8_kernel(
x_ptr,
block_to_group_ptr,
starts_ptr,
actual_ms_ptr,
block_starts_ptr,
out_ptr,
sf_ptr,
cols,
stride_xm,
stride_xn,
stride_ym,
stride_yn,
stride_sm,
stride_sk,
USE_UE8M0: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_K: tl.constexpr,
GROUP_BLOCK_M: tl.constexpr,
):
pid_blk = tl.program_id(axis=0)
pid_sub = tl.program_id(axis=1)
pid_k = tl.program_id(axis=2)
pid_g = tl.load(block_to_group_ptr + pid_blk)
src_start = tl.load(starts_ptr + pid_g)
actual_m = tl.load(actual_ms_ptr + pid_g)
block_start = tl.load(block_starts_ptr + pid_g)
local_block = pid_blk - block_start
row_offsets = local_block * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
col_offsets = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
valid_rows = row_offsets < actual_m
valid_cols = col_offsets < cols
src_rows = src_start + row_offsets
dst_rows = pid_blk * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
x = tl.load(
x_ptr + src_rows[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
tl.store(
out_ptr + dst_rows[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
y.to(tl.float8e4nv),
mask=valid_rows[:, None] & valid_cols[None, :],
)
tl.store(sf_ptr + dst_rows * stride_sm + pid_k * stride_sk, scale, mask=valid_rows)
@triton.jit
def _grouped_per_channel_fp8_sm90_kmajor_kernel(
x_ptr,
block_to_group_ptr,
starts_ptr,
actual_ms_ptr,
aligned_ms_ptr,
block_starts_ptr,
out_ptr,
sf_ptr,
cols,
stride_xm,
stride_xn,
stride_sf0,
stride_sf1,
USE_UE8M0: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_blk = tl.program_id(axis=0)
pid_n = tl.program_id(axis=1)
pid_g = tl.load(block_to_group_ptr + pid_blk)
src_start = tl.load(starts_ptr + pid_g)
actual_m = tl.load(actual_ms_ptr + pid_g)
aligned_m = tl.load(aligned_ms_ptr + pid_g)
block_start = tl.load(block_starts_ptr + pid_g)
local_block = pid_blk - block_start
row_offsets = local_block * BLOCK_K + tl.arange(0, BLOCK_K)
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
valid_rows = row_offsets < actual_m
valid_cols = col_offsets < cols
src_rows = src_start + row_offsets
x = tl.load(
x_ptr + src_rows[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=0)
scale = tl.maximum(amax / 448.0, 1e-4)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[None, :]
flat_base = block_start * BLOCK_K * cols
out_ptrs = out_ptr + flat_base + col_offsets[:, None] * aligned_m + row_offsets[None, :]
tl.store(out_ptrs, tl.trans(y).to(tl.float8e4nv), mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m))
tl.store(
sf_ptr + pid_blk * stride_sf0 + col_offsets * stride_sf1,
scale,
mask=valid_cols,
)
@triton.jit
def _grouped_per_block_fp8_kernel(
x_ptr,
out_ptr,
sf_ptr,
groups,
rows,
cols,
stride_xg,
stride_xm,
stride_xn,
stride_yg,
stride_ym,
stride_yn,
stride_sg,
stride_sm,
stride_sn,
USE_UE8M0: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_g = tl.program_id(axis=0)
pid_m = tl.program_id(axis=1)
pid_n = tl.program_id(axis=2)
row_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
mask = (pid_g < groups) & (row_offsets[:, None] < rows) & (col_offsets[None, :] < cols)
x = tl.load(
x_ptr + pid_g * stride_xg + row_offsets[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
mask=mask,
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x))
scale = tl.maximum(amax / 448.0, 1e-4)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale
tl.store(
out_ptr + pid_g * stride_yg + row_offsets[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
y.to(tl.float8e4nv),
mask=mask,
)
tl.store(sf_ptr + pid_g * stride_sg + pid_m * stride_sm + pid_n * stride_sn, scale, mask=pid_g < groups)
# ---------------------------------------------------------------------------
# Public quantization functions
# ---------------------------------------------------------------------------
def unpack_rows_triton(
x: torch.Tensor,
total_m: int,
block_to_group: torch.Tensor,
starts_tensor: torch.Tensor,
actual_ms_tensor: torch.Tensor,
block_starts_tensor: torch.Tensor,
) -> torch.Tensor:
out = torch.empty((total_m, x.size(1)), device=x.device, dtype=x.dtype)
if total_m == 0:
return out
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 32, ceil_div(x.size(1), 128))
_unpack_grouped_rows_kernel[grid](
x,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
out,
x.size(1),
x.stride(0),
x.stride(1),
out.stride(0),
out.stride(1),
BLOCK_M=32,
BLOCK_N=128,
GROUP_BLOCK_M=GROUP_ALIGNMENT,
num_warps=4,
)
return out
def per_token_cast_to_fp8_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
rows, cols = x.shape
out = torch.empty_like(x, dtype=torch.float8_e4m3fn)
sf = torch.empty((rows, ceil_div(cols, gran_k)), device=x.device, dtype=torch.float32)
grid = lambda meta: (ceil_div(rows, meta["BLOCK_M"]), ceil_div(cols, meta["BLOCK_K"]))
_per_token_fp8_kernel[grid](
x,
out,
sf,
rows,
cols,
x.stride(0),
x.stride(1),
out.stride(0),
out.stride(1),
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_K=gran_k,
num_warps=4,
)
return out, sf
def grouped_per_token_cast_to_fp8_triton(
x: torch.Tensor,
padded_total_m: int,
block_to_group: torch.Tensor,
starts_tensor: torch.Tensor,
actual_ms_tensor: torch.Tensor,
block_starts_tensor: torch.Tensor,
use_ue8m0: bool,
gran_k: int = GROUP_ALIGNMENT,
) -> Tuple[torch.Tensor, torch.Tensor]:
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
out = torch.empty((padded_total_m, x.size(1)), device=x.device, dtype=torch.float8_e4m3fn)
sf = torch.empty(
(padded_total_m, ceil_div(x.size(1), gran_k)),
device=x.device,
dtype=torch.float32,
)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 8, ceil_div(x.size(1), gran_k))
_grouped_per_token_fp8_kernel[grid](
x,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
out,
sf,
x.size(1),
x.stride(0),
x.stride(1),
out.stride(0),
out.stride(1),
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_K=gran_k,
GROUP_BLOCK_M=GROUP_ALIGNMENT,
num_warps=4,
)
return out, sf
def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
x: torch.Tensor,
padded_total_m: int,
block_to_group: torch.Tensor,
starts_tensor: torch.Tensor,
actual_ms_tensor: torch.Tensor,
ks_tensor: torch.Tensor,
block_starts_tensor: torch.Tensor,
use_ue8m0: bool,
gran_k: int = GROUP_ALIGNMENT,
) -> Tuple[torch.Tensor, torch.Tensor]:
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
out = torch.empty((padded_total_m * x.size(1),), device=x.device, dtype=torch.float8_e4m3fn)
total_blocks = padded_total_m // gran_k
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf.T
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
_grouped_per_channel_fp8_sm90_kmajor_kernel[grid](
x,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
out,
sf,
x.size(1),
x.stride(0),
x.stride(1),
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
)
return out, sf.T
def grouped_per_block_cast_to_fp8_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
assert x.dim() == 3
assert gran_k == GROUP_ALIGNMENT
groups, rows, cols = x.shape
out = torch.empty((groups, rows, cols), device=x.device, dtype=torch.float8_e4m3fn)
sf = torch.empty(
(groups, ceil_div(rows, gran_k), ceil_div(cols, gran_k)),
device=x.device,
dtype=torch.float32,
)
grid = (groups, ceil_div(rows, gran_k), ceil_div(cols, gran_k))
_grouped_per_block_fp8_kernel[grid](
x,
out,
sf,
groups,
rows,
cols,
x.stride(0),
x.stride(1),
x.stride(2),
out.stride(0),
out.stride(1),
out.stride(2),
sf.stride(0),
sf.stride(1),
sf.stride(2),
USE_UE8M0=use_ue8m0,
BLOCK_M=gran_k,
BLOCK_N=gran_k,
num_warps=8,
)
return out, sf
def per_block_cast_to_fp8_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
assert x.dim() == 2
out, sf = grouped_per_block_cast_to_fp8_triton(
x.unsqueeze(0),
use_ue8m0,
gran_k,
)
return out[0], sf[0]
@@ -1,5 +1,18 @@
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
# (because nothing loaded the real libcudart globally yet), the self-check fails
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
# ensures dlsym finds it before the stub's own exports.
import ctypes as _ctypes
try:
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
except Exception:
# This is expected on CPU-only machines
pass
import tilelang
import torch
from tilelang import language as T
@@ -1,5 +1,18 @@
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
# (because nothing loaded the real libcudart globally yet), the self-check fails
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
# ensures dlsym finds it before the stub's own exports.
import ctypes as _ctypes
try:
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
except Exception:
# This is expected on CPU-only machines
pass
import tilelang
from tilelang import language as T
@@ -0,0 +1,224 @@
from __future__ import annotations
try:
import deep_gemm
except ImportError:
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
# are GPU-only at runtime, so leaving the symbol None is safe — only the
# autograd Function bodies below actually call into it.
import torch
from prime_rl.trainer.models.kernels.fp8_utils import (
GROUP_ALIGNMENT,
build_grouped_layout,
grouped_per_block_cast_to_fp8_triton,
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
grouped_per_token_cast_to_fp8_triton,
unpack_rows_triton,
)
def _compute_grad_weight(
x: torch.Tensor,
grad_output: torch.Tensor,
weight_shape: torch.Size,
padded_total_m: int,
block_to_group: torch.Tensor,
ks_tensor: torch.Tensor,
starts_tensor: torch.Tensor,
actual_ms_tensor: torch.Tensor,
block_starts_tensor: torch.Tensor,
aligned_ms: list[int],
) -> torch.Tensor:
x_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
dy_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
deep_gemm.k_grouped_fp8_gemm_nt_contiguous(
x_k_major,
dy_k_major,
grad_weight,
aligned_ms,
ks_tensor,
grad_weight,
)
return grad_weight.to(torch.bfloat16)
class _GroupedFP8Gemm(torch.autograd.Function):
@staticmethod
def forward(
ctx,
x: torch.Tensor,
weight: torch.Tensor,
offs: torch.Tensor,
) -> torch.Tensor:
(
total_m,
padded_total_m,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
) = build_grouped_layout(offs, total_m=x.size(0))
x_fp8 = grouped_per_token_cast_to_fp8_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
weight.transpose(1, 2),
False,
GROUP_ALIGNMENT,
)
out_padded = torch.empty(
(padded_total_m, weight.size(2)),
device=x.device,
dtype=x.dtype,
)
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
x_fp8,
weight_fp8,
out_padded,
grouped_layout,
use_psum_layout=False,
)
out = unpack_rows_triton(
out_padded,
total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
ctx.padded_total_m = padded_total_m
ctx.aligned_ms = ks_tensor.tolist()
ctx.save_for_backward(
x,
weight,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
return out
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
(
x,
weight,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
) = ctx.saved_tensors
padded_total_m = ctx.padded_total_m
aligned_ms = ctx.aligned_ms
grad_output = grad_output.contiguous()
grad_x = grad_weight = None
if ctx.needs_input_grad[1]:
grad_weight = _compute_grad_weight(
x,
grad_output,
weight.shape,
padded_total_m,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
aligned_ms,
)
if ctx.needs_input_grad[0]:
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
weight,
False,
GROUP_ALIGNMENT,
)
grad_x_padded = torch.empty(
(padded_total_m, weight.size(1)),
device=grad_output.device,
dtype=grad_output.dtype,
)
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
dy_fp8,
weight_dx_fp8,
grad_x_padded,
grouped_layout,
use_psum_layout=False,
)
grad_x = unpack_rows_triton(
grad_x_padded,
x.size(0),
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
return grad_x, grad_weight, None
def grouped_fp8_gemm(
x: torch.Tensor,
weight: torch.Tensor,
offs: torch.Tensor,
) -> torch.Tensor:
"""FP8 grouped GEMM, drop-in replacement for torch._grouped_mm.
Args:
x: (M, K) concatenated token activations in bfloat16.
weight: (G, K, N) expert weights in bfloat16.
offs: (G,) int32 cumulative token counts per expert.
Returns:
(M, N) output tensor in bfloat16.
"""
return _GroupedFP8Gemm.apply(x, weight, offs)
@@ -0,0 +1,179 @@
from __future__ import annotations
import re
try:
import deep_gemm
except ImportError:
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
# are GPU-only at runtime, so leaving the symbol None is safe — only the
# autograd Function bodies below actually call into it.
import torch
from torch import nn
from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_triton,
per_token_cast_to_fp8_triton,
)
from prime_rl.utils.logger import get_logger
class _FP8BlockwiseMM(torch.autograd.Function):
@staticmethod
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
x_shape = x.shape
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
x_fp8 = per_token_cast_to_fp8_triton(x_2d, False, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, False, block_size)
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
ctx.save_for_backward(x_2d, weight)
ctx.x_shape = x_shape
ctx.block_size = block_size
return out.reshape(*x_shape[:-1], out.size(-1))
@staticmethod
def backward(ctx, grad_output):
x_2d, weight = ctx.saved_tensors
block_size = ctx.block_size
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
grad_x = grad_weight = None
if ctx.needs_input_grad[0]:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
weight_t = weight.transpose(0, 1).contiguous()
weight_dx_fp8 = per_block_cast_to_fp8_triton(weight_t, False, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(ctx.x_shape)
if ctx.needs_input_grad[1]:
# deep_gemm.fp8_gemm_nt with recipe=(1, 1, 128) requires the K (token)
# dim to be a multiple of 128. Zero-pad along the token axis so non-
# aligned per-rank batches (from sequence packing) don't trip the kernel.
M_tok = grad_output_2d.size(0)
M_pad = (M_tok + block_size - 1) // block_size * block_size
if M_pad != M_tok:
pad_rows = M_pad - M_tok
grad_output_2d_padded = torch.nn.functional.pad(grad_output_2d, (0, 0, 0, pad_rows))
x_2d_padded = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
else:
grad_output_2d_padded = grad_output_2d
x_2d_padded = x_2d
grad_output_t = grad_output_2d_padded.transpose(0, 1).contiguous()
x_t = x_2d_padded.transpose(0, 1).contiguous()
grad_output_t_fp8 = per_token_cast_to_fp8_triton(grad_output_t, False, block_size)
x_t_fp8 = per_token_cast_to_fp8_triton(x_t, False, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
x_t_fp8,
grad_weight_fp32,
c=grad_weight_fp32,
recipe=(1, 1, 128),
)
grad_weight = grad_weight_fp32.to(weight.dtype)
return grad_x, grad_weight, None, None
class Float8BlockwiseLinear(nn.Linear):
"""nn.Linear replacement that uses FP8 blockwise matmul via DeepGEMM.
Requires:
- SM90 (Hopper) GPU
- bfloat16 inputs/weights
- No bias
- in_features and out_features divisible by 128
"""
def __init__(self, *args, block_size: int = 128, dtype=torch.bfloat16, **kwargs):
super().__init__(*args, **kwargs)
self.block_size = block_size
def forward(self, x: torch.Tensor) -> torch.Tensor:
return _FP8BlockwiseMM.apply(x, self.weight, self.block_size, torch.bfloat16)
@classmethod
def from_linear(cls, mod: nn.Linear) -> "Float8BlockwiseLinear":
"""Convert an existing nn.Linear to Float8BlockwiseLinear."""
with torch.device("meta"):
new_mod = cls(
mod.in_features,
mod.out_features,
bias=mod.bias is not None,
)
new_mod.weight = mod.weight
new_mod.bias = mod.bias
return new_mod
DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
"lm_head",
"router",
# Use escaped dots — re.search treats `.` as any-char, so the previous
# "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the
# trailing `.` was matching `_`). That left the dense MLP gate projection
# in BF16 on the trainer while inference quantized it to FP8, causing
# hidden-state drift before the MoE router.
r"mlp\.gate\.",
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
"eh_proj",
"weights_proj",
"in_proj_a",
"in_proj_b",
]
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str] | None = None) -> None:
"""Replace nn.Linear in `model` with Float8BlockwiseLinear, skipping any
module whose qualified name matches an ignore pattern (substring or regex).
The default ignore list covers layers that should never be quantized:
- lm_head
- MoE routers and gates (router, mlp.gate., shared_expert_gate)
- sparse-MLA scalar projection (weights_proj)
- GLM-5.1 MTP head (eh_proj)
- hybrid-Mamba projections (in_proj_a, in_proj_b)
Independently of the name-based ignore list, we also skip any nn.Linear
whose in_features or out_features is not a multiple of 128. Float8BlockwiseLinear
documents that requirement and DeepGEMM's fp8_gemm_nt crashes at runtime
on unaligned dims — better to keep them in BF16 with a clear log line than
silently break in the kernel.
Conv1d, layer norms, and embedding tables are not nn.Linear and are
skipped automatically by the type check; we don't need to list them.
"""
if ignore_modules is None:
ignore_modules = list(DEFAULT_FP8_IGNORE_PATTERNS)
logger = get_logger()
logger.info(f"Replacing linear layers with FP8 blockwise linear layers (ignore={ignore_modules})")
replaced_modules = []
skipped_modules = []
skipped_unaligned: list[str] = []
named_modules = dict(model.named_modules())
for name, module in named_modules.items():
if not isinstance(module, nn.Linear):
continue
if any(re.search(pattern, name) for pattern in ignore_modules):
skipped_modules.append(name)
continue
if module.in_features % 128 != 0 or module.out_features % 128 != 0:
skipped_unaligned.append(f"{name}({module.in_features}->{module.out_features})")
continue
parent_name, attr_name = name.rsplit(".", 1) if "." in name else ("", name)
parent = model.get_submodule(parent_name) if parent_name else model
setattr(parent, attr_name, Float8BlockwiseLinear.from_linear(module))
replaced_modules.append(name)
logger.info(
f"Replaced {len(replaced_modules)} linear layers with FP8 blockwise linear "
f"(skipped {len(skipped_modules)} by name, "
f"{len(skipped_unaligned)} by 128-divisibility); "
f"first replaced={replaced_modules[:3]}, "
f"first skipped(name)={skipped_modules[:3]}, "
f"first skipped(unaligned)={skipped_unaligned[:3]}"
)
+57 -8
View File
@@ -30,6 +30,7 @@ class MoEArgs:
top_k: int = 1
use_grouped_mm: bool = True # grouped mm or for-loop for the experts computation
load_balance_coeff: float | None = 1e-3
fp8: bool = False # use FP8 grouped GEMM via DeepGEMM (requires SM90)
# can be used as dense FFN layer or shared experts in MoE layers
@@ -144,20 +145,39 @@ def _run_experts_grouped_mm(
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
def _run_experts_grouped_mm_impl(
@expert_parallel
def _run_experts_fp8_grouped_mm(
w1: torch.Tensor,
w2: torch.Tensor,
w3: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=True)
def _run_experts_grouped_mm_impl(
w1: torch.Tensor,
w2: torch.Tensor,
w3: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
fp8: bool = False,
) -> torch.Tensor:
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
# grouped mm between a 2D tensor and a 3D tensor
assert x.dim() == 2
h = F.silu(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
h = h * torch._grouped_mm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offs=offsets)
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
if fp8:
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
h = F.silu(grouped_fp8_gemm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offsets))
h = h * grouped_fp8_gemm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offsets)
out = grouped_fp8_gemm(h, w2.bfloat16().transpose(-2, -1), offsets).type_as(x)
else:
h = F.silu(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
h = h * torch._grouped_mm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offs=offsets)
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
return out
@@ -169,6 +189,7 @@ class GroupedExperts(nn.Module):
hidden_dim: int,
num_experts: int,
use_grouped_mm: bool,
fp8: bool = False,
):
super().__init__()
self.num_experts = num_experts
@@ -176,6 +197,7 @@ class GroupedExperts(nn.Module):
self.w2 = nn.Parameter(torch.empty(num_experts, dim, hidden_dim))
self.w3 = nn.Parameter(torch.empty(num_experts, hidden_dim, dim))
self.use_grouped_mm = use_grouped_mm
self.fp8 = fp8
self.ep_comm_backend: EPCommBackend = "torch"
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
@@ -186,7 +208,7 @@ class GroupedExperts(nn.Module):
w2 = self.w2.to_local()
w3 = self.w3.to_local()
if self.use_grouped_mm:
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=self.fp8)
return _run_experts_for_loop_impl(w1, w2, w3, x, num_tokens_per_expert)
def forward(
@@ -198,6 +220,8 @@ class GroupedExperts(nn.Module):
return self._forward_deepep(x, num_tokens_per_expert)
if self.use_grouped_mm:
if self.fp8:
return _run_experts_fp8_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
return _run_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
else:
return _run_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
@@ -534,6 +558,7 @@ class MoE(nn.Module):
hidden_dim=hidden_dim,
num_experts=num_experts,
use_grouped_mm=moe_args.use_grouped_mm,
fp8=moe_args.fp8,
)
self.ep_comm_backend: EPCommBackend = "torch"
self.experts.set_ep_comm_backend(self.ep_comm_backend)
@@ -799,12 +824,19 @@ def _run_nongated_experts_grouped_mm_impl(
_w3: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
fp8: bool = False,
) -> torch.Tensor:
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
assert x.dim() == 2
h = relu2(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
if fp8:
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
h = relu2(grouped_fp8_gemm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offsets))
out = grouped_fp8_gemm(h, w2.bfloat16().transpose(-2, -1), offsets).type_as(x)
else:
h = relu2(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
return out
@@ -819,6 +851,17 @@ def _run_nongated_experts_grouped_mm(
return _run_nongated_experts_grouped_mm_impl(w1, w2, _w3, x, num_tokens_per_expert)
@expert_parallel
def _run_nongated_experts_fp8_grouped_mm(
w1: torch.Tensor,
w2: torch.Tensor,
_w3: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
return _run_nongated_experts_grouped_mm_impl(w1, w2, _w3, x, num_tokens_per_expert, fp8=True)
class NonGatedGroupedExperts(nn.Module):
def __init__(
self,
@@ -826,6 +869,7 @@ class NonGatedGroupedExperts(nn.Module):
intermediate_dim: int,
num_experts: int,
use_grouped_mm: bool,
fp8: bool = False,
):
super().__init__()
self.num_experts = num_experts
@@ -834,6 +878,7 @@ class NonGatedGroupedExperts(nn.Module):
# Dummy w3 for @expert_parallel decorator compatibility (expects w1, w2, w3 signature)
self.w3 = nn.Parameter(torch.empty(0))
self.use_grouped_mm = use_grouped_mm
self.fp8 = fp8
self.ep_comm_backend: EPCommBackend = "torch"
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
@@ -844,7 +889,7 @@ class NonGatedGroupedExperts(nn.Module):
w2 = self.w2.to_local()
w3 = self.w3.to_local()
if self.use_grouped_mm:
return _run_nongated_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
return _run_nongated_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=self.fp8)
return _run_nongated_experts_for_loop_impl(w1, w2, w3, x, num_tokens_per_expert)
def forward(
@@ -855,6 +900,8 @@ class NonGatedGroupedExperts(nn.Module):
if self.ep_comm_backend == "deepep":
return self._forward_deepep(x, num_tokens_per_expert)
if self.use_grouped_mm:
if self.fp8:
return _run_nongated_experts_fp8_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
return _run_nongated_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
else:
return _run_nongated_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
@@ -971,6 +1018,7 @@ class LatentMoE(nn.Module):
routed_scaling_factor: float,
use_grouped_mm: bool,
load_balance_coeff: float | None,
fp8: bool = False,
):
super().__init__()
effective_latent_dim = latent_dim if latent_dim is not None else dim
@@ -988,6 +1036,7 @@ class LatentMoE(nn.Module):
intermediate_dim=moe_intermediate_size,
num_experts=num_experts,
use_grouped_mm=use_grouped_mm,
fp8=fp8,
)
self.ep_comm_backend: EPCommBackend = "torch"
self.experts.set_ep_comm_backend(self.ep_comm_backend)
@@ -1,10 +1,26 @@
from __future__ import annotations
# ruff: noqa: I001 — `prime_rl._compat` must run before `ring_flash_attn` imports below.
import prime_rl._compat # noqa: F401
import torch
import torch.distributed as dist
from ring_flash_attn.utils import AllGatherComm, get_default_args
def _set_fa3_signature_params(params: dict, causal: bool, window_size: tuple[int, int]) -> None:
if "is_causal" in params:
params["is_causal"] = causal
else:
params["causal"] = causal
if "window_size" in params:
params["window_size"] = window_size
else:
params["window_size_left"] = window_size[0]
params["window_size_right"] = window_size[1]
def _fa3_varlen_forward(
q: torch.Tensor,
k: torch.Tensor,
@@ -30,11 +46,9 @@ def _fa3_varlen_forward(
"max_seqlen_q": max_seqlen_q,
"max_seqlen_k": max_seqlen_k,
"softmax_scale": softmax_scale,
"is_causal": causal,
"window_size_left": window_size[0],
"window_size_right": window_size[1],
}
)
_set_fa3_signature_params(params, causal, window_size)
out, lse, _, _ = _flash_attn_forward(**params)
return out, lse
@@ -76,11 +90,9 @@ def _fa3_varlen_backward(
"dk": dk,
"dv": dv,
"softmax_scale": softmax_scale,
"is_causal": causal,
"window_size_left": window_size[0],
"window_size_right": window_size[1],
}
)
_set_fa3_signature_params(params, causal, window_size)
_flash_attn_backward(**params)
@@ -0,0 +1,296 @@
"""Ulysses-style context parallelism via all-to-all on the head/seq dimensions.
Ulysses is the simpler alternative to ring attention for context parallelism:
sequence-sharded Q/K/V head-sharded Q/K/V
[S/cp, H, D] ── all-to-all ──▶ [S, H/cp, D]
(heads ↔ seq)
│
▼
run vanilla local attention
on the *full* sequence with
*fewer* heads (any kernel works)
│
▼
[S/cp, H, D] ◀── all-to-all ── [S, H/cp, D]
(seq ↔ heads)
Key benefit: the attention kernel itself does not need to be CP-aware. The
all-to-all is purely on Q/K/V tensors, so this works out of the box with
softmax flash-attn, linear attention, mamba, etc., without rewriting kernels.
Constraints:
- cp_size must divide both num_attention_heads and num_key_value_heads.
- Sequence length must be divisible by cp_size.
"""
from __future__ import annotations
import torch
import torch.distributed as dist
import torch.distributed.nn.functional as dist_nn
# Populated by `update_ulysses_params` before each forward pass. Mirrors
# ring_flash_attn's DATA_PARAMS pattern so the patched attention path can
# reach the *full* (un-sharded) cu_seqlens / max_seqlen at call time.
ULYSSES_PARAMS: dict = {}
def update_ulysses_params(cu_seqlens: torch.Tensor, max_seqlen: int) -> None:
ULYSSES_PARAMS["cu_seqlens"] = cu_seqlens
ULYSSES_PARAMS["max_seqlen"] = int(max_seqlen)
def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
"""Redistribute [S_local, H, D] -> [S_global, H_local, D].
Splits the head dim into cp_size groups and exchanges them so each rank
ends up with the full sequence but only H/cp_size heads. Differentiable.
"""
s_local, h, d = t.shape
assert h % cp_size == 0, f"num_heads ({h}) must be divisible by cp_size ({cp_size})"
h_local = h // cp_size
# [S_local, cp_size, H_local, D] -> [cp_size, S_local, H_local, D]
t = t.reshape(s_local, cp_size, h_local, d).transpose(0, 1).contiguous()
output = torch.empty_like(t)
out = dist_nn.all_to_all_single(output, t, group=cp_group)
# out[i] is the chunk that source-rank i had at position my_rank, i.e.
# source-rank i's local sequence shard for *my* head slice.
return out.reshape(cp_size * s_local, h_local, d)
def _all_to_all_head_to_seq(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
"""Inverse of `_all_to_all_seq_to_head`: [S_global, H_local, D] -> [S_local, H, D]."""
s_global, h_local, d = t.shape
assert s_global % cp_size == 0
s_local = s_global // cp_size
h = h_local * cp_size
t = t.reshape(cp_size, s_local, h_local, d).contiguous()
output = torch.empty_like(t)
out = dist_nn.all_to_all_single(output, t, group=cp_group)
# out[s']: original chunk for sequence-rank s' (which now becomes head-rank s').
return out.transpose(0, 1).contiguous().reshape(s_local, h, d)
def ulysses_flash_attn_varlen_func(
flash_fn,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
causal: bool,
cp_group: dist.ProcessGroup,
cp_size: int,
flash_attn_version: int = 2,
window_size: tuple[int, int] = (-1, -1),
softmax_scale: float | None = None,
dropout_p: float = 0.0,
deterministic: bool | None = None,
) -> torch.Tensor:
"""Run varlen flash attention under Ulysses CP.
`cu_seqlens_*` and `max_seqlen_*` describe the *full* (un-sharded) sequence,
because after the seq->head all-to-all each rank holds the full sequence.
"""
q = _all_to_all_seq_to_head(q, cp_size, cp_group)
k = _all_to_all_seq_to_head(k, cp_size, cp_group)
v = _all_to_all_seq_to_head(v, cp_size, cp_group)
kwargs: dict = {"causal": causal}
if window_size != (-1, -1):
kwargs["window_size"] = window_size
if softmax_scale is not None:
kwargs["softmax_scale"] = softmax_scale
if dropout_p:
kwargs["dropout_p"] = dropout_p
if deterministic is not None:
kwargs["deterministic"] = deterministic
if flash_attn_version == 4:
# FA4 takes cu_seqlens as keyword args (qv positional collides otherwise).
kwargs["cu_seqlens_q"] = cu_seqlens_q
kwargs["cu_seqlens_k"] = cu_seqlens_k
out = flash_fn(q, k, v, **kwargs)
else:
out = flash_fn(q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, **kwargs)
if isinstance(out, tuple):
out = out[0]
return _all_to_all_head_to_seq(out, cp_size, cp_group)
def substitute_ulysses_attn(
process_group: dist.ProcessGroup,
attn_impl: str = "flash_attention_2",
) -> None:
"""Patch FlashAttention._compute_attention to do Ulysses all-to-all + local FA.
Mirrors `substitute_ring_attn` so swapping CP styles is a one-line change
in the trainer.
"""
cp_size = dist.get_world_size(group=process_group)
# Resolve flash kernel + version from attn_impl.
if attn_impl == "fa4":
from flash_attn.cute import flash_attn_varlen_func as flash_fn
flash_attn_version = 4
flash_fn = torch._dynamo.disable(flash_fn)
elif attn_impl == "flash_attention_3":
from flash_attn_interface import flash_attn_varlen_func as flash_fn
flash_attn_version = 3
else:
from flash_attn import flash_attn_varlen_func as flash_fn
flash_attn_version = 2
def _ulysses_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
# cu_seqlens / max_seqlen passed in are for the *local* sharded sequence;
# ulysses needs the *full* ones (each rank holds the full seq after a2a).
cu_seqlens_full = ULYSSES_PARAMS["cu_seqlens"]
max_seqlen_full = ULYSSES_PARAMS["max_seqlen"]
window_size = (-1, -1)
sliding_window = getattr(self, "sliding_window", None)
if sliding_window is not None:
window_size = (sliding_window - 1, 0)
return ulysses_flash_attn_varlen_func(
flash_fn,
q,
k,
v,
cu_seqlens_q=cu_seqlens_full,
cu_seqlens_k=cu_seqlens_full,
max_seqlen_q=max_seqlen_full,
max_seqlen_k=max_seqlen_full,
causal=True,
cp_group=process_group,
cp_size=cp_size,
flash_attn_version=flash_attn_version,
window_size=window_size,
)
from prime_rl.trainer.models.layers.attn import FlashAttention
FlashAttention._compute_attention = _ulysses_compute_attention
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
AfmoeFlashAttention._compute_attention = _ulysses_compute_attention
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
Qwen3_5MoeGatedFlashAttention._compute_attention = _ulysses_compute_attention
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
"""Patch HF's `_flash_attention_forward` to use Ulysses all-to-all + local FA2.
Used for HF (non-custom) model paths, e.g. qwen2/qwen3 dense models. Mirrors
ring_flash_attn's `substitute_hf_flash_attn` but with all-to-all instead of
ring all-gather.
"""
import transformers
import transformers.modeling_flash_attention_utils
from flash_attn import flash_attn_varlen_func
cp_size = dist.get_world_size(group=process_group)
def _ulysses_flash_attention_forward(
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
attention_mask,
query_length: int,
is_causal: bool,
dropout: float = 0.0,
position_ids=None,
softmax_scale=None,
sliding_window=None,
use_top_left_mask: bool = False,
softcap=None,
deterministic=None,
**kwargs,
):
assert is_causal, "ulysses CP only supports causal attention"
assert softcap is None, "ulysses CP path does not support softcap"
assert query_states.size(0) == 1, "varlen data should be processed with batch=1"
cu_seqlens = ULYSSES_PARAMS["cu_seqlens"]
max_seqlen = ULYSSES_PARAMS["max_seqlen"]
window_size = (-1, -1)
if sliding_window is not None and key_states.shape[1] > sliding_window:
window_size = (sliding_window, sliding_window)
out = ulysses_flash_attn_varlen_func(
flash_attn_varlen_func,
query_states.squeeze(0),
key_states.squeeze(0),
value_states.squeeze(0),
cu_seqlens_q=cu_seqlens,
cu_seqlens_k=cu_seqlens,
max_seqlen_q=max_seqlen,
max_seqlen_k=max_seqlen,
causal=True,
cp_group=process_group,
cp_size=cp_size,
flash_attn_version=2,
window_size=window_size,
softmax_scale=softmax_scale,
dropout_p=dropout,
deterministic=deterministic,
)
return out.unsqueeze(0)
transformers.modeling_flash_attention_utils._flash_attention_forward = _ulysses_flash_attention_forward
# Newer transformers route attention through ALL_ATTENTION_FUNCTIONS["flash_attention_2"].
try:
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
except ImportError:
ALL_ATTENTION_FUNCTIONS = None
if ALL_ATTENTION_FUNCTIONS is not None:
def _ulysses_flash_attention_forward_v2(
module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask=None,
dropout: float = 0.0,
scaling=None,
sliding_window=None,
softcap=None,
**kw,
):
# Match HF v2 entrypoint: query/key/value arrive as [B, H, S, D].
seq_len = query.shape[2]
query = query.transpose(1, 2)
key = key.transpose(1, 2)
value = value.transpose(1, 2)
kw.pop("is_causal", None)
attn_out = _ulysses_flash_attention_forward(
query,
key,
value,
attention_mask,
query_length=seq_len,
is_causal=module.is_causal,
dropout=dropout,
softmax_scale=scaling,
sliding_window=sliding_window,
softcap=softcap,
)
return attn_out, None
ALL_ATTENTION_FUNCTIONS["flash_attention_2"] = _ulysses_flash_attention_forward_v2
@@ -55,6 +55,7 @@ class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=1e-3 if config.use_routing_bias else None,
fp8=getattr(config, "fp8", False),
)
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
@@ -257,6 +257,7 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
routed_scaling_factor=config.routed_scaling_factor,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
def forward(
@@ -613,6 +613,7 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
@@ -73,6 +73,7 @@ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
+27 -6
View File
@@ -186,13 +186,32 @@ def train(config: TrainerConfig):
if parallel_dims.cp_enabled:
cp_group = parallel_dims.world_mesh["cp"].get_group()
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
if config.model.cp_style == "ring":
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
else:
from prime_rl.trainer.models.layers.ulysses_attn import (
substitute_hf_ulysses_attn,
substitute_ulysses_attn,
)
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
substitute_hf_ulysses_attn(cp_group)
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
from prime_rl.utils.cp import (
assert_cp_style_supports_model,
setup_hybrid_cp,
setup_nemotron_h_cp,
setup_sparse_mla_cp,
)
assert_cp_style_supports_model(config.model.cp_style, model)
# sparse MLA is softmax (works with both ring and ulysses).
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Linear-attn / Mamba layers are only configured under ulysses; with ring
# we'd have already raised above.
if config.model.cp_style == "ulysses":
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Optionally, resume training from a checkpoint
progress = Progress()
@@ -371,7 +390,9 @@ def train(config: TrainerConfig):
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
if cp_enabled:
input_ids, forward_position_ids = setup_cp_params(input_ids, position_ids, cp_rank, cp_size, cp_group)
input_ids, forward_position_ids = setup_cp_params(
input_ids, position_ids, cp_rank, cp_size, cp_group, cp_style=config.model.cp_style
)
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
if routed_experts is not None:
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
+31 -8
View File
@@ -107,8 +107,17 @@ def train(config: SFTConfig):
assert config.data.seq_len % parallel_dims.cp == 0, "Sequence length must be divisible by CP degree"
cp_group = parallel_dims.world_mesh["cp"].get_group()
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
if config.model.cp_style == "ring":
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
else:
from prime_rl.trainer.models.layers.ulysses_attn import (
substitute_hf_ulysses_attn,
substitute_ulysses_attn,
)
substitute_hf_ulysses_attn(cp_group)
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
# Set up checkpoint manager
@@ -129,9 +138,16 @@ def train(config: SFTConfig):
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=fused_cross_entropy)
if parallel_dims.cp_enabled:
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
from prime_rl.utils.cp import assert_cp_style_supports_model
assert_cp_style_supports_model(config.model.cp_style, model)
# sparse MLA is softmax (works with both ring and ulysses).
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Linear-attn / Mamba layers are only configured under ulysses; with ring
# we'd have already raised above.
if config.model.cp_style == "ulysses":
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
if config.model.lora is not None:
multi_run_manager = get_multi_run_manager()
@@ -213,7 +229,9 @@ def train(config: SFTConfig):
loss_mask = micro_batch["loss_mask"].to("cuda")
if cp_enabled:
input_ids, position_ids = setup_cp_params(input_ids, position_ids, cp_rank, cp_size, cp_group)
input_ids, position_ids = setup_cp_params(
input_ids, position_ids, cp_rank, cp_size, cp_group, cp_style=config.model.cp_style
)
target_ids = shard_for_cp(target_ids, cp_rank=cp_rank, cp_world_size=cp_size)
loss_mask = shard_for_cp(loss_mask, cp_rank=cp_rank, cp_world_size=cp_size)
@@ -422,9 +440,14 @@ def train(config: SFTConfig):
if memory_profiler is not None:
memory_profiler.step()
# Compute step metrics
# Divide by CP since those ranks process the same data
num_tokens = config.data.batch_size * config.data.seq_len // config.model.cp
# Compute step metrics. CP shards the same sequences across cp ranks
# (sequence-sharded data parallelism on the seq dim), so the unique
# training tokens per step is dp_size * (batch_per_dp_rank * seq).
# The `dp` mesh excludes cp by construction (parallel_dims.py), mirroring
# the RL trainer's accounting (rl/train.py).
dp_size = parallel_dims.get_mesh("dp").size()
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
num_tokens = dp_size * num_local_tokens
progress.total_tokens += num_tokens
progress.total_samples = dataset.step
perf_counter = get_perf_counter(model, config.data.seq_len)
-19
View File
@@ -1,19 +0,0 @@
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
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
+70 -24
View File
@@ -1,5 +1,10 @@
from __future__ import annotations
# ruff: noqa: I001 — `prime_rl._compat` must run before `ring_flash_attn` imports below.
import prime_rl._compat # noqa: F401
from typing import Literal
import torch
import torch.distributed as dist
import torch.distributed.nn as dist_nn
@@ -8,9 +13,47 @@ from ring_flash_attn import update_ring_flash_attn_params
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
CPStyle = Literal["ring", "ulysses"]
def _has_linear_attn_layer(model: nn.Module) -> bool:
"""True if the model contains any non-softmax (linear/SSM) attention layer."""
inner = getattr(model, "model", model)
if hasattr(inner, "language_model"):
inner = inner.language_model
layers = getattr(inner, "layers", None)
if layers is None:
return False
for layer in layers:
# Qwen3.5 hybrid DeltaNet
if getattr(layer, "layer_type", None) == "linear_attention":
return True
# NemotronH Mamba
if hasattr(layer, "mamba"):
return True
return False
def assert_cp_style_supports_model(cp_style: CPStyle, model: nn.Module) -> None:
"""Refuse `cp_style='ring'` on models that have linear/SSM attention layers.
Ring CP is a softmax-attention algorithm (sequence ring all-gather of K/V).
For non-softmax layers (DeltaNet, Mamba) we'd need a fundamentally different
CP scheme, which is not implemented. Use `cp_style='ulysses'` for those:
ulysses' all-to-all is purely on Q/K/V tensors, so the linear/SSM kernel
runs unchanged on a sequence shard.
"""
if cp_style == "ring" and _has_linear_attn_layer(model):
raise ValueError(
"cp_style='ring' is not supported for models with linear-attention "
"or Mamba/SSM layers (e.g. Qwen3.5 hybrid, NemotronH). Use "
"cp_style='ulysses' instead — its all-to-all on Q/K/V works "
"out-of-the-box with non-softmax kernels."
)
def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Configure DeltaNet modules in Qwen3.5 hybrid models for native fla CP."""
"""Configure DeltaNet modules in Qwen3.5 hybrid models for ulysses-style CP."""
layers = None
if hasattr(model, "model"):
inner = model.model
@@ -39,7 +82,7 @@ def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int,
def setup_nemotron_h_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Configure NemotronH Mamba layers for context-parallel gather/scatter."""
"""Configure NemotronH Mamba layers for ulysses-style all-to-all head partitioning."""
layers = None
if hasattr(model, "model") and hasattr(model.model, "layers"):
layers = model.model.layers
@@ -140,35 +183,38 @@ def get_padding_logit_from_prev_cp_rank(
return None
def _get_cu_seqlens_for_cp(position_ids: torch.Tensor) -> torch.Tensor:
cu_seqlens, _ = get_cu_seqlens_from_position_ids(position_ids)
return cu_seqlens
def setup_cp_params(
input_ids: torch.Tensor,
position_ids: torch.Tensor,
cp_rank: int,
cp_world_size: int,
cp_group: dist.ProcessGroup,
cp_style: CPStyle = "ring",
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Prepare the input for context parallelism and sets required parameters for ring flash attention.
Args:
input_ids: The input ids tensor.
position_ids: The position ids tensor.
cp_rank: The rank of the current process.
cp_world_size: The number of processes in the context parallel group.
cp_group: The context parallel group.
Returns:
The sharded input_ids and position_ids for context parallelism.
"""
input_ids = shard_for_cp(input_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
Prepare the input for context parallelism and set required attention params.
cu_seqlens = _get_cu_seqlens_for_cp(position_ids)
update_ring_flash_attn_params(cu_seqlens, cp_group)
Both ring and ulysses styles need cu_seqlens computed from the *full*
(un-sharded) position_ids, then publish them to the patched attention layer:
- ring: via ring_flash_attn's DATA_PARAMS (with local_k_slice).
- ulysses: via ULYSSES_PARAMS (just the full cu_seqlens / max_seqlen).
Returns the sequence-sharded input_ids and position_ids — the rest of the
model still runs sequence-sharded; only attention sees the full sequence.
"""
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
if cp_style == "ring":
update_ring_flash_attn_params(cu_seqlens, cp_group)
elif cp_style == "ulysses":
# Delayed import: ulysses_attn lives under trainer.models, which imports
# back into prime_rl.utils — top-level import would deadlock at startup.
from prime_rl.trainer.models.layers.ulysses_attn import update_ulysses_params
update_ulysses_params(cu_seqlens, max_seqlen)
else:
raise ValueError(f"Unknown cp_style: {cp_style}")
input_ids = shard_for_cp(input_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
position_ids = shard_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
return (
input_ids,
position_ids,
)
return input_ids, position_ids
-71
View File
@@ -41,77 +41,6 @@ def import_object(dotted_path: str) -> Any:
return getattr(module, name)
def rgetattr(obj: Any, attr_path: str) -> Any:
"""
Try to get a (nested) attribute from an object. For example:
```python
class Foo:
bar = "baz"
class Bar:
foo = Foo()
foo = Foo()
bar = Bar()
```
Here, the following holds:
- `getattr(foo, "bar")` will return `"baz"`.
- `getattr(bar, "foo)` will return an object of type `Foo`.
- `getattr(bar, "foo.bar")` will error
This function solves this. `rgetattr(bar, "foo.bar")` will return `"baz"`.
Args:
obj: The object to get the attribute from.
attr_path: The path to the attribute, nested using `.` as separator.
Returns:
The attribute
"""
attrs = attr_path.split(".")
current = obj
for attr in attrs:
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:
"""
Try to set a (nested) attribute from an object. For example:
```python
class Foo:
bar = "baz"
class Bar:
foo = Foo()
foo = Foo()
bar = Bar()
```
Here, the following holds:
- `rsetattr(bar, "foo.bar", "qux")` will set `bar.foo.bar` to `"qux"`.
- `rsetattr(bar, "foo.bar", "qux")` will set `bar.foo.bar` to `"qux"`.
Args:
obj: The object to set the attribute on.
attr_path: The path to the attribute, nested using `.` as separator.
value: The value to set the attribute to.
"""
if "." not in attr_path:
return setattr(obj, attr_path, value)
attr_path, attr = attr_path.rsplit(".", 1)
obj = rgetattr(obj, attr_path)
setattr(obj, attr, value)
def capitalize(s: str) -> str:
"""Capitalize the first letter of a string."""
return s[0].upper() + s[1:]
+103 -11
View File
@@ -1,6 +1,11 @@
import torch
from prime_rl.configs.orchestrator import CustomAdvantageConfig, DefaultAdvantageConfig
from prime_rl.configs.orchestrator import (
CustomAdvantageConfig,
DefaultAdvantageConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
)
from prime_rl.orchestrator.advantage import (
AdvantageInputs,
AdvantageOutputs,
@@ -38,6 +43,11 @@ def _make_inputs(rewards, completion_lengths=None, num_turns=None) -> AdvantageI
return AdvantageInputs(rollouts=rollouts)
# Helper aliases for readability — completion-only and tool-only token shaping.
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
def test_default_advantage_fn_simple_mean():
inputs = _make_inputs(
rewards=[[1.0, 0.5, 0.8], [0.2, 0.9, 0.1]],
@@ -56,7 +66,7 @@ def test_efficiency_mixed_group():
rewards=[[1.0, 1.0, 0.0, 1.0]],
completion_lengths=[[10, 30, 20, 20]],
)
result = default_advantage_fn(inputs, length_penalty="tokens")
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# mean_correct_len = (10+30+20)/3 = 20
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
@@ -81,7 +91,7 @@ def test_efficiency_all_correct_group():
rewards=[[1.0, 1.0, 1.0]],
completion_lengths=[[10, 20, 40]],
)
result = default_advantage_fn(inputs, length_penalty="tokens")
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# mean_len = 70/3 ≈ 23.33
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
@@ -106,7 +116,7 @@ def test_efficiency_all_zero_rewards():
rewards=[[0.0, 0.0, 0.0]],
completion_lengths=[[10, 20, 15]],
)
result_with = default_advantage_fn(inputs, length_penalty="tokens")
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
result_without = default_advantage_fn(inputs)
assert torch.allclose(result_with.advantages, result_without.advantages, atol=1e-6)
@@ -118,7 +128,7 @@ def test_efficiency_single_correct():
rewards=[[1.0, 0.0, 0.0, 0.0]],
completion_lengths=[[100, 50, 200, 150]],
)
result = default_advantage_fn(inputs, length_penalty="tokens")
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
expected = torch.tensor([[0.75, -0.25, -0.25, -0.25]])
assert torch.allclose(result.advantages, expected, atol=1e-6)
@@ -130,7 +140,7 @@ def test_efficiency_shorter_correct_higher_advantage():
rewards=[[1.0, 1.0, 1.0, 0.0, 0.0]],
completion_lengths=[[50, 100, 200, 80, 120]],
)
result = default_advantage_fn(inputs, length_penalty="tokens")
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
advs = result.advantages[0]
assert advs[0] > advs[1] > advs[2]
@@ -150,7 +160,7 @@ def test_efficiency_zero_mean_per_group():
[10, 20, 40, 80],
],
)
result = default_advantage_fn(inputs, length_penalty="tokens")
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
@@ -161,7 +171,7 @@ def test_efficiency_amplification_bounded():
rewards=[[1.0, 1.0, 0.0]],
completion_lengths=[[1, 10000, 5000]],
)
result = default_advantage_fn(inputs, length_penalty="tokens")
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
# Standard reward = 1, so amplification ≈ 2x
@@ -181,7 +191,7 @@ def test_efficiency_multiple_problems():
[10, 20, 40],
],
)
result = default_advantage_fn(inputs, length_penalty="tokens")
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# Row 0: mixed group — shorter correct > longer correct
assert result.advantages[0, 0] > result.advantages[0, 1]
@@ -195,15 +205,97 @@ def test_efficiency_multiple_problems():
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
def test_efficiency_tokens_with_tool_response_weight():
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
rollouts = [
[
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 200},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 0},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 100},
},
]
]
inputs = AdvantageInputs(rollouts=rollouts)
# completion tokens identical (10 each) → completion-only shaping is a no-op
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert torch.allclose(result_completion_only.advantages, torch.zeros(1, 3), atol=1e-6)
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
advs = result_tool_only.advantages[0]
assert advs[1] > advs[0]
assert advs[1] > advs[2]
assert torch.allclose(advs[0], advs[2], atol=1e-6)
assert torch.allclose(result_tool_only.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
def test_efficiency_fractional_weight_with_int_rewards():
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
rollouts_int = [
[
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
]
]
rollouts_float = [[{**r, "reward": float(r["reward"])} for r in g] for g in rollouts_int]
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
assert torch.allclose(int_result.advantages, float_result.advantages, atol=1e-6)
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
# tool-only weights but no harness metric → all costs == 0
rollouts = [
[
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
]
]
inputs = AdvantageInputs(rollouts=rollouts)
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
expected = default_advantage_fn(inputs) # plain GRPO
assert not torch.isnan(result.advantages).any()
assert torch.allclose(result.advantages, expected.advantages, atol=1e-6)
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0, 1.0]],
completion_lengths=[[10, 30, 20, 20]],
)
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert torch.allclose(result_default.advantages, result_completion.advantages, atol=1e-6)
def test_efficiency_turns_penalty():
"""`length_penalty='turns'` shapes by trajectory turn count rather than token count."""
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0, 1.0]],
# token counts identical, but turns differ — turns penalty should still differentiate
completion_lengths=[[100, 100, 100, 100]],
num_turns=[[1, 3, 2, 2]],
)
result = default_advantage_fn(inputs, length_penalty="turns")
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
# mean_correct_turns = (1+3+2)/3 = 2
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
Generated
+171 -90
View File
@@ -11,14 +11,14 @@ supported-markers = [
]
[options]
exclude-newer = "2026-04-23T20:00:49.639641409Z"
exclude-newer = "2026-04-29T22:09:49.355713533Z"
exclude-newer-span = "P7D"
[options.exclude-newer-package]
vllm = false
verifiers = false
vllm-router = false
dion = false
torch = false
alphabet-sort = false
science-env = false
color-codeword = false
@@ -44,6 +44,10 @@ aime2025 = false
prime-sandboxes = false
[manifest]
members = [
"prime-rl",
"prime-rl-configs",
]
overrides = [
{ name = "nvidia-cudnn-cu12", specifier = ">=9.15" },
{ name = "nvidia-cutlass-dsl", specifier = ">=4.4.1" },
@@ -214,17 +218,17 @@ wheels = [
[[package]]
name = "apache-tvm-ffi"
version = "0.1.8.post2"
version = "0.1.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e3/e9/a13952726228fa6282154ecf927092396bc759739e5e045019f6ab92f3ca/apache_tvm_ffi-0.1.8.post2.tar.gz", hash = "sha256:4513e38852894f290172ecfefcbc18d34e817fd29c16a0f1770e130c82b4067e", size = 2441111, upload-time = "2026-01-13T18:11:27.864Z" }
sdist = { url = "https://files.pythonhosted.org/packages/6f/60/1e787a0b5ebf318483235be2a689ee367173983067e441b8379564f667c0/apache_tvm_ffi-0.1.9.tar.gz", hash = "sha256:d2d402587e8906de0a07f4746aa78f3d452c7efe3625d4bb39ac2ad693bce530", size = 2513731, upload-time = "2026-02-27T19:28:06.602Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/8e/3a/7b1c9edcaeaebb945038144896cf17eb828a40b6ace0371823e133132664/apache_tvm_ffi-0.1.8.post2-cp312-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8c78b4caf17304a1f47881bccdb2f9ac24d98b3b7fbe761a6dd4fd0585934d96", size = 1967259, upload-time = "2026-01-13T18:10:47.851Z" },
{ url = "https://files.pythonhosted.org/packages/6c/b6/463602f57dda2e1c69165c044c07061cd59404593f313a427a3ad9c02cf3/apache_tvm_ffi-0.1.8.post2-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4a48da3fa8f47130f3502134f01e97044388c5217e7b91be4b0acec4feab81a0", size = 2044821, upload-time = "2026-01-13T18:10:49.396Z" },
{ url = "https://files.pythonhosted.org/packages/fe/e6/9cdc7f4814b2fbdfceba5dc640c3704d07d8db18e3d1aef5aa49bbf1ba7e/apache_tvm_ffi-0.1.8.post2-cp312-abi3-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61cc98e489ebc03bc96d1a966dc863eb1c0a607383f6bf4a416ff0a96170ca85", size = 1910964, upload-time = "2026-01-13T18:10:51.345Z" },
{ url = "https://files.pythonhosted.org/packages/7d/f5/a2e5487cdad575fe6cf34f8a23f8c49e08ce5808fa75dc19d98bcebc20ec/apache_tvm_ffi-0.1.8.post2-cp312-abi3-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:caa48509f0c7d9b896823b492a9ee42afac2548065c1ec7ef07f9a0dc30d2796", size = 2025814, upload-time = "2026-01-13T18:10:52.804Z" },
{ url = "https://files.pythonhosted.org/packages/a7/c0/6d3d54f50012255b41bc3e24944c086f63c4707c8686c7c6780e9283eb96/apache_tvm_ffi-0.1.9-cp312-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7d503029e66c43b1a1cb1a42a1e9bb428c8a28dcbdec31c28e705472ca648a3a", size = 2203712, upload-time = "2026-02-27T19:27:25.867Z" },
{ url = "https://files.pythonhosted.org/packages/c6/dd/2bab4c6cd86257dbf99e93452a1af833113f8dc3e25a25579f6e4e4c8a94/apache_tvm_ffi-0.1.9-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28241371934ea8af10d5067087ba1229ebddded7b2c02d33a258ec2a96df8c46", size = 2299704, upload-time = "2026-02-27T19:27:27.477Z" },
{ url = "https://files.pythonhosted.org/packages/7a/4a/b469bcb2e1014cb84d336d2a59f42958a058251c577a4c2680cacad346e2/apache_tvm_ffi-0.1.9-cp312-abi3-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:87cacce81df55685fc6a76e1e3c5db1200e85e87bf5974b692c59d131b7bc622", size = 2130865, upload-time = "2026-02-27T19:27:29.092Z" },
{ url = "https://files.pythonhosted.org/packages/70/ef/5402da5d37f5270fd88ea0348acca78dba9be8bdbf6c2bcae0935eb03ef1/apache_tvm_ffi-0.1.9-cp312-abi3-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f45eb43499acac45ff6c93564f0ff2d3ca27b69656d540fd56ce59d51c0b4c65", size = 2278991, upload-time = "2026-02-27T19:27:30.729Z" },
]
[[package]]
@@ -508,7 +512,7 @@ wheels = [
[[package]]
name = "compressed-tensors"
version = "0.14.0.1"
version = "0.15.0.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "loguru", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -516,9 +520,9 @@ dependencies = [
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "transformers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/eb/f1/4c9b01ceaf82ad58ad00919223e09b8e74d4073a2ba8e3ab2f97521ef65c/compressed_tensors-0.14.0.1.tar.gz", hash = "sha256:5ad3841184b6f5020e06059b2463191c5c57a144bb97cab9159978d8118839b1", size = 226393, upload-time = "2026-03-11T17:04:35.57Z" }
sdist = { url = "https://files.pythonhosted.org/packages/41/1b/c3c4a98ec5f2727656336f07a0c35862195c310d8eb0b2fa5b4be6848680/compressed_tensors-0.15.0.1.tar.gz", hash = "sha256:a8e93054e8a5ec49c980b09ed36c4c1249b4a8ee167920a8e461c4da26e78d99", size = 229412, upload-time = "2026-04-10T14:23:54.708Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0a/26/16a13993ecf4fdc9c39d63b3a6daabafd32a452cf68b81aa9eb3b8170913/compressed_tensors-0.14.0.1-py3-none-any.whl", hash = "sha256:46c4940a3a779d3d97108c294bfcd9acf4bd0491f7c6737c320f0e815ec732e4", size = 196454, upload-time = "2026-03-11T17:04:33.2Z" },
{ url = "https://files.pythonhosted.org/packages/a8/52/93833dc1610e017ac5b7dcd59b8304d8ef67d1114c2d124e728a2cbbea12/compressed_tensors-0.15.0.1-py3-none-any.whl", hash = "sha256:e1b1f322e82e475715e242bad46925a304ea8e5c98b5055a15b8eb22fb6bfea9", size = 194260, upload-time = "2026-04-10T14:23:53.098Z" },
]
[[package]]
@@ -592,6 +596,61 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/af/f3/6b032a554019cfb3447e671798c1bd3e79b5f1af20d10253f56cea269ef2/cuda_python-12.9.4-py3-none-any.whl", hash = "sha256:d2cacea882a69863f1e7d27ee71d75f0684f4c76910aff839067e4f89c902279", size = 7594, upload-time = "2025-10-21T14:55:12.846Z" },
]
[[package]]
name = "cuda-tile"
version = "1.3.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/f3/49/4592bc94ca05a07c7947ea114fd12734c8497f2daffee9faa79a03e39fb5/cuda_tile-1.3.0-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:375316b64c51ee7cfadb2f170a30c1547bc41eb39f1e233a6556713857d2e81f", size = 245744, upload-time = "2026-04-20T15:52:09.621Z" },
{ url = "https://files.pythonhosted.org/packages/40/76/84cb68be463c827bf79da9fa0aa5140838de6455ef6f438bbe0ffa75d378/cuda_tile-1.3.0-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:e4865acbff1172aaee304bf9c550586088d8b4545a384423597a590899386709", size = 247301, upload-time = "2026-04-20T15:51:04.042Z" },
]
[[package]]
name = "cuda-toolkit"
version = "12.8.1"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d4/c8/7dce3a0b15b42a3b58e7d96eb22a687d3bf2c44e01d149a6874629cd9938/cuda_toolkit-12.8.1-py2.py3-none-any.whl", hash = "sha256:adc7906af4ecbf9a352f9dca5734eceb21daec281ccfcf5675e1d2f724fc2cba", size = 2283, upload-time = "2025-08-13T02:03:07.842Z" },
]
[package.optional-dependencies]
cublas = [
{ name = "nvidia-cublas-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
cudart = [
{ name = "nvidia-cuda-runtime-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
cufft = [
{ name = "nvidia-cufft-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
cufile = [
{ name = "nvidia-cufile-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
cupti = [
{ name = "nvidia-cuda-cupti-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
curand = [
{ name = "nvidia-curand-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
cusolver = [
{ name = "nvidia-cusolver-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
cusparse = [
{ name = "nvidia-cusparse-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
nvjitlink = [
{ name = "nvidia-nvjitlink-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
nvrtc = [
{ name = "nvidia-cuda-nvrtc-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
nvtx = [
{ name = "nvidia-nvtx-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
[[package]]
name = "datasets"
version = "4.0.0"
@@ -638,17 +697,17 @@ wheels = [
[[package]]
name = "deep-ep"
version = "1.2.1+73b6ea4"
source = { 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" }
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
wheels = [
{ 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", hash = "sha256:ddf25e5d9c8543d27d7ae7a62ff7752560bf79c03c5991d48721352818b320d3" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl", hash = "sha256:ddf25e5d9c8543d27d7ae7a62ff7752560bf79c03c5991d48721352818b320d3" },
]
[[package]]
name = "deep-gemm"
version = "2.3.0+477618c"
source = { 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" }
version = "2.3.0+d30fc36"
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl" }
wheels = [
{ 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", hash = "sha256:a40cea03705cfa50eefe5651d91e3e7ebf87a53acf06cde8bbb877fb95f0f921" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl", hash = "sha256:dfa8dbeff3d820193f4f94b75f12734c7d73650495e9e8bbdb276953316db6f9" },
]
[[package]]
@@ -868,6 +927,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1e/5c/9516828037b1680de14bae4d93b2868b26417059e1e5cb7d8ad7be649197/fastcore-1.12.31-py3-none-any.whl", hash = "sha256:2634f117fe3a2f6c250f8500f70211c96158399936e90fa6d1010d2d516bf03a", size = 98509, upload-time = "2026-03-22T02:21:19.274Z" },
]
[[package]]
name = "fastsafetensors"
version = "0.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typer", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/39/98/053c622e61bb766d31327a88215082320a4ba8bd6a62c4c5435221844103/fastsafetensors-0.3.tar.gz", hash = "sha256:89f392569d2281d1a966d3b64f99a6386149116e37eef4f4890168c87a8c4f19", size = 57500, upload-time = "2026-04-22T07:16:30.84Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0a/06/bca80663bf8136f273643d149953dd29ca2c52aa4faac4b67506b871a5ec/fastsafetensors-0.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3ce38241c5afedf94ef37531b8b8703016b2ea39350cfd33e819e65d4d5305e0", size = 1855661, upload-time = "2026-04-22T07:16:25.833Z" },
]
[[package]]
name = "filelock"
version = "3.19.1"
@@ -879,14 +950,14 @@ wheels = [
[[package]]
name = "flash-attn"
version = "2.8.3+cu128torch2.10"
source = { url = "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" }
version = "2.8.3+cu128torch2.11"
source = { url = "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" }
dependencies = [
{ name = "einops", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
wheels = [
{ url = "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", hash = "sha256:5ef676dfd01d198eed36795d924eb6af4c87674896de6bd102390afa7f522bc0" },
{ url = "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", hash = "sha256:a16162f436286cc03ebbfb174c0853343ed98ae13c37abf1042947668ec40549" },
]
[package.metadata]
@@ -935,19 +1006,20 @@ dependencies = [
[[package]]
name = "flashinfer-cubin"
version = "0.6.6"
version = "0.6.8.post1"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/12/e8/826f9452bc5f76b94d7eb025f03dcaf1b51b9ed7790386c0285191e69be4/flashinfer_cubin-0.6.6-py3-none-any.whl", hash = "sha256:36508dfc792eb5ecfb15d2c140a7702812e1fa1ab0fb03929b2ed55e3e8191f3", size = 267661457, upload-time = "2026-03-11T01:36:36.538Z" },
{ url = "https://files.pythonhosted.org/packages/11/b7/5e3b1a8c67031b421a8bd29c2bc29b900a550bb3392e8bda18bb15b5e476/flashinfer_cubin-0.6.8.post1-py3-none-any.whl", hash = "sha256:43636d4cd39e694a83d76a89f87fefcdf4cecb4c4f7dd22dac25ec368c1e901f", size = 295154113, upload-time = "2026-04-18T18:28:21.738Z" },
]
[[package]]
name = "flashinfer-python"
version = "0.6.6"
version = "0.6.8.post1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "apache-tvm-ffi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "click", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "cuda-tile", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "einops", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "ninja", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -960,9 +1032,9 @@ dependencies = [
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/03/70/c5a235297351021f5d3d3233523a85f5a6468495587489ad2f257e8eafe2/flashinfer_python-0.6.6.tar.gz", hash = "sha256:0730ba7c7aad332961933bcebc5119762797161ede57d955f6fd199818ed1d92", size = 5344156, upload-time = "2026-03-11T01:36:21.434Z" }
sdist = { url = "https://files.pythonhosted.org/packages/53/1e/2760fef9e74abc4480961048e5790b4c9e955872fb4d7d97900cfddced5a/flashinfer_python-0.6.8.post1.tar.gz", hash = "sha256:b18e4121baf9b93fa9a9f368ba9b981a0342895f50ab9dddc224aeb964ed346f", size = 6675885, upload-time = "2026-04-18T18:28:13.299Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/61/385d06755f3ab66333018285657adf0daf8a90a129448231fd09e315bd2e/flashinfer_python-0.6.6-py3-none-any.whl", hash = "sha256:078f158636969eec1a0d3dea19c3ca90b426b66df89bbf7b7b8276ce2ec08148", size = 7817047, upload-time = "2026-03-11T01:36:19.198Z" },
{ url = "https://files.pythonhosted.org/packages/73/6d/1e8a8533913e33a50a486332ce0673f4fdb860f6eb9ed450327c5c1762cb/flashinfer_python-0.6.8.post1-py3-none-any.whl", hash = "sha256:818f9b8cc2fe66c42a1f6264be4841ac8821ada703685a02cfccb2b5124a710b", size = 9385316, upload-time = "2026-04-18T18:28:10.285Z" },
]
[[package]]
@@ -1593,12 +1665,12 @@ wheels = [
[[package]]
name = "llvmlite"
version = "0.44.0"
version = "0.47.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/89/6a/95a3d3610d5c75293d5dbbb2a76480d5d4eeba641557b69fe90af6c5b84e/llvmlite-0.44.0.tar.gz", hash = "sha256:07667d66a5d150abed9157ab6c0b9393c9356f229784a4385c02f99e94fc94d4", size = 171880, upload-time = "2025-01-20T11:14:41.342Z" }
sdist = { url = "https://files.pythonhosted.org/packages/01/88/a8952b6d5c21e74cbf158515b779666f692846502623e9e3c39d8e8ba25f/llvmlite-0.47.0.tar.gz", hash = "sha256:62031ce968ec74e95092184d4b0e857e444f8fdff0b8f9213707699570c33ccc", size = 193614, upload-time = "2026-03-31T18:29:53.497Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/da/8341fd3056419441286c8e26bf436923021005ece0bff5f41906476ae514/llvmlite-0.44.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0143a5ef336da14deaa8ec26c5449ad5b6a2b564df82fcef4be040b9cacfea9", size = 42361901, upload-time = "2025-01-20T11:13:46.711Z" },
{ url = "https://files.pythonhosted.org/packages/53/ad/d79349dc07b8a395a99153d7ce8b01d6fcdc9f8231355a5df55ded649b61/llvmlite-0.44.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d752f89e31b66db6f8da06df8b39f9b91e78c5feea1bf9e8c1fba1d1c24c065d", size = 41184247, upload-time = "2025-01-20T11:13:56.159Z" },
{ url = "https://files.pythonhosted.org/packages/e6/4b/e3f2cd17822cf772a4a51a0a8080b0032e6d37b2dbe8cfb724eac4e31c52/llvmlite-0.47.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5853bf26160857c0c2573415ff4efe01c4c651e59e2c55c2a088740acfee51cd", size = 56275178, upload-time = "2026-03-31T18:28:48.342Z" },
{ url = "https://files.pythonhosted.org/packages/b6/55/a3b4a543185305a9bdf3d9759d53646ed96e55e7dfd43f53e7a421b8fbae/llvmlite-0.47.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:003bcf7fa579e14db59c1a1e113f93ab8a06b56a4be31c7f08264d1d4072d077", size = 55128632, upload-time = "2026-03-31T18:28:52.901Z" },
]
[[package]]
@@ -2006,7 +2078,7 @@ version = "0.10.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "nixl-cu12", version = "0.10.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' and sys_platform == 'linux'" },
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/bb/a4/10e80e623790d3fb070e966b36bced009419d483c92ae0df6645230f606f/nixl-0.10.1-py3-none-any.whl", hash = "sha256:616465673dae5180d296525a03237af4cd5f2c00c3228d185bc06dbe621509b7", size = 6680, upload-time = "2026-03-03T19:55:44.848Z" },
@@ -2030,7 +2102,7 @@ wheels = [
[[package]]
name = "nixl-cu12"
version = "0.10.1"
source = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
@@ -2039,7 +2111,7 @@ dependencies = [
{ name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
wheels = [
{ url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl", hash = "sha256:bd01eb9e52f1affee3330062baa2f3bea7d711664f7cb602bf5d3f694daeb796" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl", hash = "sha256:bd01eb9e52f1affee3330062baa2f3bea7d711664f7cb602bf5d3f694daeb796" },
]
[package.metadata]
@@ -2059,16 +2131,16 @@ wheels = [
[[package]]
name = "numba"
version = "0.61.2"
version = "0.65.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "llvmlite", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1c/a0/e21f57604304aa03ebb8e098429222722ad99176a4f979d34af1d1ee80da/numba-0.61.2.tar.gz", hash = "sha256:8750ee147940a6637b80ecf7f95062185ad8726c8c28a2295b8ec1160a196f7d", size = 2820615, upload-time = "2025-04-09T02:58:07.659Z" }
sdist = { url = "https://files.pythonhosted.org/packages/49/61/7299643b9c18d669e04be7c5bcb64d985070d07553274817b45b049e7bfe/numba-0.65.0.tar.gz", hash = "sha256:edad0d9f6682e93624c00125a471ae4df186175d71fd604c983c377cdc03e68b", size = 2764131, upload-time = "2026-04-01T03:52:01.946Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9a/2d/e518df036feab381c23a624dac47f8445ac55686ec7f11083655eb707da3/numba-0.61.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5b1bb509d01f23d70325d3a5a0e237cbc9544dd50e50588bc581ba860c213546", size = 3885928, upload-time = "2025-04-09T02:57:55.206Z" },
{ url = "https://files.pythonhosted.org/packages/10/0f/23cced68ead67b75d77cfcca3df4991d1855c897ee0ff3fe25a56ed82108/numba-0.61.2-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:48a53a3de8f8793526cbe330f2a39fe9a6638efcbf11bd63f3d2f9757ae345cd", size = 3577115, upload-time = "2025-04-09T02:57:56.818Z" },
{ url = "https://files.pythonhosted.org/packages/73/36/88406bd58600cc696417b8e5dd6a056478da808f3eaf48d18e2421e0c2d9/numba-0.65.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a52d92ffd297c10364bce60cd1fcb88f99284ab5df085f2c6bcd1cb33b529a6f", size = 3801411, upload-time = "2026-04-01T03:51:34.321Z" },
{ url = "https://files.pythonhosted.org/packages/0c/61/ce753a1d7646dd477e16d15e89473703faebb8995d2f71d7ad69a540b565/numba-0.65.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da8e371e328c06d0010c3d8b44b21858652831b85bcfba78cb22c042e22dbd8e", size = 3501622, upload-time = "2026-04-01T03:51:36.348Z" },
]
[[package]]
@@ -2241,11 +2313,11 @@ wheels = [
[[package]]
name = "nvidia-nccl-cu12"
version = "2.27.5"
version = "2.28.9"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/bb/1c/857979db0ef194ca5e21478a0612bcdbbe59458d7694361882279947b349/nvidia_nccl_cu12-2.27.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:31432ad4d1fb1004eb0c56203dc9bc2178a1ba69d1d9e02d64a6938ab5e40e7a", size = 322400625, upload-time = "2025-06-26T04:11:04.496Z" },
{ url = "https://files.pythonhosted.org/packages/6e/89/f7a07dc961b60645dbbf42e80f2bc85ade7feb9a491b11a1e973aa00071f/nvidia_nccl_cu12-2.27.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ad730cf15cb5d25fe849c6e6ca9eb5b76db16a80f13f425ac68d8e2e55624457", size = 322348229, upload-time = "2025-06-26T04:11:28.385Z" },
{ url = "https://files.pythonhosted.org/packages/08/c4/120d2dfd92dff2c776d68f361ff8705fdea2ca64e20b612fab0fd3f581ac/nvidia_nccl_cu12-2.28.9-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:50a36e01c4a090b9f9c47d92cec54964de6b9fcb3362d0e19b8ffc6323c21b60", size = 296766525, upload-time = "2025-11-18T05:49:16.094Z" },
{ url = "https://files.pythonhosted.org/packages/4a/4e/44dbb46b3d1b0ec61afda8e84837870f2f9ace33c564317d59b70bc19d3e/nvidia_nccl_cu12-2.28.9-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:485776daa8447da5da39681af455aa3b2c2586ddcf4af8772495e7c532c7e5ab", size = 296782137, upload-time = "2025-11-18T05:49:34.248Z" },
]
[[package]]
@@ -2502,12 +2574,12 @@ wheels = [
[[package]]
name = "outlines-core"
version = "0.2.11"
version = "0.2.14"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/1a/d3/e04e9145f8f806723dec9b9e5227ad695a3efcd3ced7794cf7c22b15df5e/outlines_core-0.2.11.tar.gz", hash = "sha256:dfce56f717ff5083e54cbcfdb66cad243365437fccbb5509adaa7e31e030f1d8", size = 197263, upload-time = "2025-05-19T10:12:51.719Z" }
sdist = { url = "https://files.pythonhosted.org/packages/6a/04/4a0812eb27c086cfd2e66e7ec9150f33e105912a9b7f8b335e3479f03a06/outlines_core-0.2.14.tar.gz", hash = "sha256:64808deed1591ca3029ff64346ceb974cd5d780c916ea82504951fe83523039e", size = 191539, upload-time = "2026-01-09T15:59:10.016Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/92/c7/a65d1fddf49830ebc41422294eacde35286d9f68994a8aa905cb14f5aade/outlines_core-0.2.11-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:86df9740368866295077346440d911df4972da2b3f1f54b8125e6f329e8a8891", size = 2287677, upload-time = "2025-05-19T10:12:24.24Z" },
{ url = "https://files.pythonhosted.org/packages/23/79/8795aed8be9b77dd69d78e7cfbfcf28c179e6b08da6e56bbbf48a09fe55f/outlines_core-0.2.11-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:96ce4dd78f106799be4a0a5795cefd1352806162973756a4b6fce4bb6eddd7e4", size = 2113000, upload-time = "2025-05-19T10:12:25.446Z" },
{ url = "https://files.pythonhosted.org/packages/29/29/3a04944407207a5d214879ca5ca33c2bd3e65199a4e927051c1bdaaa4d50/outlines_core-0.2.14-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3bb2060c240c4507f334965a8948dbeeb22007560d797f6debd92346c0b620cb", size = 2341426, upload-time = "2026-01-09T15:58:33.553Z" },
{ url = "https://files.pythonhosted.org/packages/b2/a7/a77f746272504bac3f628047d56ea1731b61549a3e1d9bbfd226f2968246/outlines_core-0.2.14-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:1de34681c7e0e7e1551fc9036e4fa3c57986336c905a10536591ceb6d869c258", size = 2236941, upload-time = "2026-01-09T15:58:35.118Z" },
]
[[package]]
@@ -2690,20 +2762,19 @@ dependencies = [
{ name = "nvidia-ml-py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "openai", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "prime", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "prime-rl-configs", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "pyarrow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "pydantic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "pydantic-config", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "pyzmq", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "ring-flash-attn", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "setproctitle", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tenacity", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tilelang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tomli", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tomli-w", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torchaudio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torchdata", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torchtitan", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torchvision", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "transformers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "uvloop", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "verifiers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -2719,7 +2790,7 @@ all = [
{ name = "flash-attn-3", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "flash-attn-4", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nixl", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "quack-kernels", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
@@ -2727,7 +2798,7 @@ disagg = [
{ name = "deep-ep", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "nixl", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
envs = [
@@ -2784,11 +2855,11 @@ requires-dist = [
{ name = "code-env", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
{ name = "color-codeword", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
{ name = "datasets", specifier = ">=4.0.0" },
{ name = "deep-ep", marker = "platform_machine == 'x86_64' and extra == 'disagg'", 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" },
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and extra == 'disagg'", 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" },
{ name = "deep-ep", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" },
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl" },
{ name = "deepdive", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
{ name = "dion", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "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" },
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "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" },
{ name = "flash-attn-3", marker = "extra == 'flash-attn-3'", index = "https://download.pytorch.org/whl/test/cu128" },
{ name = "flash-attn-4", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=96bd151" },
{ name = "flash-linear-attention", git = "https://github.com/fla-org/flash-linear-attention" },
@@ -2802,7 +2873,7 @@ requires-dist = [
{ name = "math500", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
{ name = "mini-swe-agent-plus", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
{ name = "nixl", marker = "extra == 'disagg'" },
{ name = "nixl-cu12", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" },
{ name = "nixl-cu12", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" },
{ name = "numpy", specifier = ">=2.2.6" },
{ name = "nvidia-ml-py", specifier = ">=12.575.51" },
{ name = "openai", specifier = ">=1.106.1" },
@@ -2812,9 +2883,8 @@ requires-dist = [
{ name = "prime-rl", extras = ["flash-attn-3"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["flash-attn-cute"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pydantic", specifier = ">=1.10.13" },
{ name = "pydantic-config", git = "https://github.com/samsja/pydantic_config.git?branch=main" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "quack-kernels", marker = "extra == 'quack'", specifier = ">=0.3.3" },
{ name = "reverse-text", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
@@ -2824,15 +2894,15 @@ requires-dist = [
{ name = "setproctitle", specifier = ">=1.3.0" },
{ name = "tenacity", specifier = ">=8.2.0" },
{ name = "tilelang", specifier = ">=0.1.8" },
{ name = "tomli", specifier = ">=2.2.1" },
{ name = "tomli-w", specifier = ">=1.2.0" },
{ name = "torch", specifier = ">=2.9.0", index = "https://download.pytorch.org/whl/cu128" },
{ name = "torchaudio", index = "https://download.pytorch.org/whl/cu128" },
{ name = "torchdata", specifier = ">=0.11.0" },
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
{ name = "torchvision", index = "https://download.pytorch.org/whl/cu128" },
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=c1c3424" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3b77145" },
{ name = "vllm", specifier = ">=0.19.0" },
{ name = "vllm", specifier = ">=0.20.1" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wiki-search", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
@@ -2849,6 +2919,25 @@ dev = [
]
mamba-ssm = [{ name = "mamba-ssm", specifier = ">=2.3.0" }]
[[package]]
name = "prime-rl-configs"
version = "0.4.0"
source = { editable = "packages/prime-rl-configs" }
dependencies = [
{ name = "pydantic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "pydantic-config", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tomli", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tomli-w", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
[package.metadata]
requires-dist = [
{ name = "pydantic", specifier = ">=1.10.13" },
{ name = "pydantic-config", git = "https://github.com/samsja/pydantic_config.git?branch=main" },
{ name = "tomli", specifier = ">=2.2.1" },
{ name = "tomli-w", specifier = ">=1.2.0" },
]
[[package]]
name = "prime-sandboxes"
version = "0.2.22"
@@ -3690,7 +3779,7 @@ wheels = [
[[package]]
name = "tilelang"
version = "0.1.8"
version = "0.1.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "apache-tvm-ffi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -3704,10 +3793,10 @@ dependencies = [
{ name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "z3-solver", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e6/27/6e363f48f878389078e2899756b8fecc326388b585122fd7f8a86590dfab/tilelang-0.1.8.tar.gz", hash = "sha256:da967821698eb7a79a76d27fbe25e314a3273f2b12ba4833e981658139d0e6d9", size = 93247335, upload-time = "2026-02-16T14:03:28.706Z" }
sdist = { url = "https://files.pythonhosted.org/packages/56/70/5051f65821baa30a3d61fc48f8ba10c776490315e8c90f82559b92089756/tilelang-0.1.9.tar.gz", hash = "sha256:287f727c913bb648fcf6c1968809ba3390e55eeed257a5c6bb9a80bc05966af4", size = 93395292, upload-time = "2026-04-22T09:19:11.988Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5d/0b/96ba853aa9e4795020d183e0ca832e9e37d82d4f7f48896241323d1b5ece/tilelang-0.1.8-cp38-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a4018e581f55c852d98a42d3b4acf2dbcfb8b7d8b9156ba7c6b0ab61600a10c", size = 43477401, upload-time = "2026-02-16T14:03:02.879Z" },
{ url = "https://files.pythonhosted.org/packages/e6/db/d130c8db9140bb21a2ef81a455614a4aeec3388088bf9af5df01ad0ba45d/tilelang-0.1.8-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:bcc2e28202cde516bdd59e1c25b7f6a139d1c52207d92576f4e711c6217e16ba", size = 40422585, upload-time = "2026-02-16T14:03:12.092Z" },
{ url = "https://files.pythonhosted.org/packages/f7/8a/1cbeee79d62abaa02441c2d00621554e41aa62dbf3b94a4feb3867184b01/tilelang-0.1.9-cp38-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4bbccfe9035aed775ffafb6dc25a5994504b24e2c5d95d0f39643edfafa7bf12", size = 45419374, upload-time = "2026-04-22T09:15:56.014Z" },
{ url = "https://files.pythonhosted.org/packages/c6/a7/f4bfb86f87e107703146e703204cec2c0eae2492b633e0052b0ace3febb6/tilelang-0.1.9-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:77ab0ee2f40f66ea015b6b21426d482751e28cbc635ef9d1198cbd6502454a7c", size = 42110365, upload-time = "2026-04-22T09:17:18.292Z" },
]
[[package]]
@@ -3758,37 +3847,27 @@ wheels = [
[[package]]
name = "torch"
version = "2.10.0+cu128"
version = "2.11.0+cu128"
source = { registry = "https://download.pytorch.org/whl/cu128" }
dependencies = [
{ name = "cuda-bindings", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "filelock", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "fsspec", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "jinja2", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "networkx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cublas-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cuda-cupti-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cuda-nvrtc-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cuda-runtime-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cudnn-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cufft-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cufile-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-curand-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cusolver-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cusparse-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-cusparselt-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-nccl-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-nvjitlink-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-nvshmem-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nvidia-nvtx-cu12", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "setuptools", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "sympy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "triton", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
wheels = [
{ url = "https://download-r2.pytorch.org/whl/cu128/torch-2.10.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6f09cdf2415516be028ae82e6b985bcfc3eac37bc52ab401142689f6224516ca", upload-time = "2026-01-21T15:22:03Z" },
{ url = "https://download-r2.pytorch.org/whl/cu128/torch-2.10.0%2Bcu128-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:628e89bd5110ced7debee2a57c69959725b7fbc64eab81a39dd70e46c7e28ba5", upload-time = "2026-01-21T15:22:11Z" },
{ url = "https://download-r2.pytorch.org/whl/cu128/torch-2.11.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:9c8f38efee365cb9d334de8a83ce52fc7e5fc9e5a7b0853285efa1b69e00b0f2", upload-time = "2026-04-27T17:41:30Z" },
{ url = "https://download-r2.pytorch.org/whl/cu128/torch-2.11.0%2Bcu128-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:d252cf975fb18c94a85336323ad425f473df56dab35a44b00399bd70c7a3b997", upload-time = "2026-04-27T17:42:06Z" },
]
[[package]]
@@ -3806,14 +3885,11 @@ wheels = [
[[package]]
name = "torchaudio"
version = "2.10.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
version = "2.11.0+cu128"
source = { registry = "https://download.pytorch.org/whl/cu128" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ea/3f/df620439a76ece170472d41438d11a1545d5db5dc9f1eaeab8c6e055a328/torchaudio-2.10.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:42b148a0921a3721abd1f6ae098b1ec9f89703e555c4f7a0d44da87b8decbcb9", size = 391973, upload-time = "2026-01-21T16:28:39.732Z" },
{ url = "https://files.pythonhosted.org/packages/98/25/e55a30d7138f8fe56ed006df25b0a3c27681f0ec7bc9989e1778e6d559c3/torchaudio-2.10.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:0e77b2956448d63790a99beed0b74ac8b8cd3a94dcdd9ad01974411078f46278", size = 1895234, upload-time = "2026-01-21T16:28:37.034Z" },
{ url = "https://download-r2.pytorch.org/whl/cu128/torchaudio-2.11.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:d055c9ca9d4f0ffcbaa0fc22138bafd675256de392bdaadde00d797faa90ca56", upload-time = "2026-03-23T15:50:23Z" },
{ url = "https://download-r2.pytorch.org/whl/cu128/torchaudio-2.11.0%2Bcu128-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:78b86a17f164bdaabdcee93fdfde2587fc43b9ebf15cd61dcf730b4f8615176b", upload-time = "2026-03-23T15:50:23Z" },
]
[[package]]
@@ -3845,16 +3921,16 @@ dependencies = [
[[package]]
name = "torchvision"
version = "0.25.0"
source = { registry = "https://pypi.org/simple" }
version = "0.26.0+cu128"
source = { registry = "https://download.pytorch.org/whl/cu128" }
dependencies = [
{ name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/51/f8/c0e1ef27c66e15406fece94930e7d6feee4cb6374bbc02d945a630d6426e/torchvision-0.25.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:b75deafa2dfea3e2c2a525559b04783515e3463f6e830cb71de0fb7ea36fe233", size = 2344556, upload-time = "2026-01-21T16:27:40.125Z" },
{ url = "https://files.pythonhosted.org/packages/68/2f/f24b039169db474e8688f649377de082a965fbf85daf4e46c44412f1d15a/torchvision-0.25.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:f25aa9e380865b11ea6e9d99d84df86b9cc959f1a007cd966fc6f1ab2ed0e248", size = 8072351, upload-time = "2026-01-21T16:27:21.074Z" },
{ url = "https://download-r2.pytorch.org/whl/cu128/torchvision-0.26.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:63e35234aed13b6edda37056f417b5c281249669db631e706811917af36b21d7", upload-time = "2026-04-09T23:21:35Z" },
{ url = "https://download-r2.pytorch.org/whl/cu128/torchvision-0.26.0%2Bcu128-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:ccf26b4b659cfce6f2208cb8326071d51c70219a34856dfdf468d1e19af52c0d", upload-time = "2026-03-23T15:36:22Z" },
]
[[package]]
@@ -4123,11 +4199,12 @@ wheels = [
[[package]]
name = "vllm"
version = "0.19.0"
version = "0.20.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "anthropic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "apache-tvm-ffi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "blake3", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "cachetools", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "cbor2", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -4137,6 +4214,7 @@ dependencies = [
{ name = "diskcache", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "einops", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "fastapi", extra = ["standard"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "fastsafetensors", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "filelock", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "flashinfer-cubin", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "flashinfer-python", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -4182,6 +4260,7 @@ dependencies = [
{ name = "setuptools", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "six", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tiktoken", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tilelang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tokenizers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "torchaudio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -4192,10 +4271,12 @@ dependencies = [
{ name = "watchfiles", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "xgrammar", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/03/14/c330a72309051f762b357a2e41d5015bedbb106ad1e16a231bdfda2e2163/vllm-0.19.0.tar.gz", hash = "sha256:81e59cf87175e7a62eb8d9acf5989484bbd17089d5eface353f89067bda282d9", size = 31071745, upload-time = "2026-04-03T04:04:52.833Z" }
sdist = { url = "https://files.pythonhosted.org/packages/34/b4/32429ebde396149e5570c9a6b2e3b52dc47261d8b20465cc6ae36c4659fb/vllm-0.20.1.tar.gz", hash = "sha256:778df065237704d51e8b4cc95bcc6f6a0c2317f13feb38295de3ce76146bf140", size = 33519792, upload-time = "2026-05-03T08:24:43.794Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c8/51/467e7a8cb4838022daa731b7f8b34c228691e36f938e1803c3a702c7bd69/vllm-0.19.0-cp38-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:6ab90ccca5d7ca3bd2c8f90133f0fac85e8f4af582a1c67c6cc3f63c615521e3", size = 384650557, upload-time = "2026-04-03T04:05:52.513Z" },
{ url = "https://files.pythonhosted.org/packages/b7/08/6a431731e4c163bc1fab85b63e269d84104aad0fba98dac1af34fdc5077f/vllm-0.19.0-cp38-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:2d0e5fae45367bdbf111fcad68f4c0f8fdddd2f2fb643e52f0f2daebef7b41cf", size = 432281473, upload-time = "2026-04-03T04:05:22.07Z" },
{ url = "https://files.pythonhosted.org/packages/6e/2a/4bee1ddd867895e63bcca4f4ad78048f6a5d96d0ea241cdb70657cce966e/vllm-0.20.1-1-cp38-abi3-manylinux_2_35_aarch64.whl", hash = "sha256:4a5c24a94be8413ce682e72d6c22762ac7be64635cf191f4807d30910f928268", size = 235787780, upload-time = "2026-05-04T10:38:44.956Z" },
{ url = "https://files.pythonhosted.org/packages/f1/ae/55bb24db43e02a21fe98d64293a309d7cf67054785ac8e8ff2e60e59789e/vllm-0.20.1-1-cp38-abi3-manylinux_2_35_x86_64.whl", hash = "sha256:11907857c94c226caf82ada92ab09b1e0dbf538b5b80a93aed74be29e861020c", size = 244425444, upload-time = "2026-05-04T10:39:12.327Z" },
{ url = "https://files.pythonhosted.org/packages/a7/23/8b48eeee87d9e5589f11bf5139f768053b90c4f85a33cfb72655a30cd14a/vllm-0.20.1-cp38-abi3-manylinux_2_35_aarch64.whl", hash = "sha256:1cfa5f5654e4c7a8a9f949ef7a9597a63b9736129202c96c006434b57f511223", size = 235787697, upload-time = "2026-05-03T08:25:12.511Z" },
{ url = "https://files.pythonhosted.org/packages/76/80/16ee5d248a795abefd1476d4884394e3d917c68096f8dd696a8216347a74/vllm-0.20.1-cp38-abi3-manylinux_2_35_x86_64.whl", hash = "sha256:da89341f2a07f49a2571edecbec612071839b04b6d7ea1e3bddb5347d47859df", size = 244425347, upload-time = "2026-05-03T08:25:32.198Z" },
]
[[package]]