Compare commits

...
Author SHA1 Message Date
Florian BrandandGitHub 5f7e3ffcaa chore: migrate environment configs to V1 (#3058)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-17 15:34:42 +02:00
188192ce64 fix(qwen3.5): require FLA for DeltaNet (#3063)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-16 22:53:26 -07:00
samsjaandGitHub cac463e795 feat: use FA3 as default, rename fa4 to flash_attention_4, remove eager (#3057)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: use FA3 as default, rename fa4 to flash_attention_4, remove eager

Three changes:

1. Default attention implementation changed from flash_attention_2 to flash_attention_3.
2. Renamed internal 'fa4' alias to 'flash_attention_4' everywhere for consistency.
   The _ATTN_ALIASES mapping and _normalize_attn_alias validator are removed since
   flash_attention_4 is now the canonical name. The _register_fa4_attention_interface
   noop is also removed since transformers already registers flash_attention_4 in
   AttentionInterface._global_mapping.
3. Removed 'eager' from AttnImplementation Literal. GPT-OSS non-Hopper fallback
   updated to suggest 'sdpa' instead of 'eager'.

* fix: allow impl='auto' with FA3/FA4 + CP, fix ruff format

- Update CP+FA3/FA4 validator to also accept impl='auto' (which resolves
  to 'custom' at runtime for supported models). This fixes the config
  test for rl_qwen3_30b_a3b.toml which uses cp=2 with the new FA3 default.
- Apply ruff format to qwen3_5 and qwen3_5_moe model files (multi-line
  tuple formatting for long in-check).

* feat: remove sdpa and eager attention support

Remove 'sdpa' and 'eager' from AttnImplementation. Only flash_attention_2,
flash_attention_3, and flash_attention_4 are now supported.

Changes:
- Remove 'sdpa' from AttnImplementation Literal in trainer config
- Remove SDPAAttention class from layers/attn.py
- Remove all SDPA attention classes from custom models (AfmoeSDPAAttention,
  LagunaSDPAAttention, Qwen3_5MoeGatedSDPAAttention, Qwen3_5GatedSDPAAttention)
- Remove 'sdpa' entries from all ATTN_IMPL2CLASS dispatch dicts
- Remove eager->sdpa fallback logic in afmoe, laguna, qwen3_5_moe
- Set _supports_sdpa = False on all custom model configs
- Remove GPT-OSS non-Hopper SDPA fallback (now errors on non-Hopper)
- Update normalize_qwen3_5_attn_implementation to drop eager alias
- Update default attn_impl in qwen3_5/qwen3_5_moe _check_and_adjust
- Update configs and tests to use flash_attention_2 instead of sdpa
- Mark test_qwen3_5_dense_matches_hf_state_keys_on_meta as GPU test
  (HF model validates flash attn availability at init, requires GPU)

* fix: accept impl='auto' for flash_attention_4 validator

Same pattern as the CP+FA3/FA4 validator fix: 'auto' resolves to 'custom'
at runtime for supported models, so it should be accepted at config validation
time. Also improve error message to match.

* fix: bypass flash attention availability check for custom models

Override _check_and_adjust_attn_implementation on PreTrainedModelPrimeRL
to skip transformers' flash attention package/device validation.

This restores the behavior of the old _register_fa4_attention_interface()
noop that was removed when fa4 was renamed to flash_attention_4. Without
this override, instantiating a custom model with _from_config fails on
machines where flash_attn_3 or flash_attn_cute is not installed, because
transformers recognizes flash_attention_3/4 as flash attention and tries
to validate availability before our own ATTN_IMPL2CLASS dispatch runs.

Custom models use their own attention dispatch (ATTN_IMPL2CLASS) and never
call transformers' ALL_ATTENTION_FUNCTIONS, so the availability check is
unnecessary. qwen3_5 and qwen3_5_moe already override this method with
their own validation; those overrides take precedence via MRO.
2026-07-16 22:33:03 -07:00
e0d60e4d85 refactor(sft): unify the loss path with the RL trainer (#3044)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* refactor(sft): unify the loss path with the RL trainer

Remove loss_impl (torch / liger / liger_fused / quack_fused) and route SFT
through the same chunked LM head the RL trainer uses:

- fused_lm_head_token_chunk_size (int, default 1024) selects FusedOutputLinear;
  per-token cross-entropy is the negative target logprob computed in token
  chunks — full [N, V] logits are never materialized. "disabled" falls back to
  the vanilla logits + CrossEntropyLoss path.
- The same [model] block now behaves identically across SFT and RL, and SFT
  drops the ~17 GB logits tax that loss_impl="torch" carried at long context.
- Delete the liger/quack fused-CE heads, the fused_cross_entropy plumbing in
  setup_model/inject_prime_lm_head, the SFT validator that force-disabled
  chunking, and the liger-kernel dependency.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: relock without liger-kernel

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: restore _online_logsumexp_and_weighted_update

The fused-CE class removal also swallowed this helper (defined between the
deleted classes) which the chunked logprob head uses at runtime.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: ruff

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 21:50:49 -07:00
d7bcd1b1f5 Add MXFP8 Support (#2910)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Add MXFP8 Linear Layer

* Add MXFP8 Receipe

* Add MXFP8

* Refractor, remove constants, cleanup

* Remove import from local path

* Reformat

* Add MXFP8 expert parallel impl to support TorchAO's MXTensor in backward for all2all in MXFP8

* Build torchao from source for py3.12 MXFP8 CUDA kernel

Pin torchao to the pytorch/ao git source (rev 02105d4) and build its CUDA
kernels from source against the local torch cu128 / cpython-3.12. The PyPI
wheel ships the MXFP8 kernel as a cpython-310-only .so that fails to load on
prime-rl's Python 3.12, so torchao::mxfp8_quantize was never registered with a
CUDA backend and MXFP8 died in backward. Building from source produces a
cpython-312 extension (_C_mxfp8.cpython-312-*.so).

- no-build-isolation-package += torchao (build against local torch)
- extra-build-variables: CUDA_HOME=/usr/local/cuda-12.8,
  TORCH_CUDA_ARCH_LIST=10.0a (B200/sm_100a), USE_CPP=1

Enables the MXFP8 all-to-all and dense-linear paths (verified on 8xB200).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Relax torchao MXFP8 grouped-GEMM torch-nightly gate

torchao's _get_tensor_cls_for_config (added in pytorch/ao#4141, "require torch
nightly and cuda 12.8+", Mar 2026) asserts two post-2.11.0 DTensor symbols
(_ops.scaled_mm_single_dim_strategy, _dispatch.is_pinned_handler) exist, else
raises "install the latest torch nightly". This blanket-blocks all MXFP8 training,
but is over-broad for us: prime-rl's EP path pulls expert weights local
(.to_local()) before the grouped GEMM, so the DTensor scaled-mm strategy is never
hit, and current torch's non-single-dim scaled_mm_strategy covers the rest.

Neutralize just that assert (MXFP8 branch only) before quantize_, so
enable_grouped_gemm works on our pinned torch 2.11 without a nightly bump.

Verified 8xB200 SFT (GLM-0.5B, ep=8, grouped_gemm + a2a): 8/8 steps, all ranks;
numerics vs bf16 within mxfp8 range (out ~4.8%, grads ~6-7%) for both
mxfp8_rceil and mxfp8_rceil_wgrad_with_hp recipes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Use prebuilt torchao wheel from v0.6.0 release (x86_64)

Replace the torchao build-from-source git dependency with the prebuilt
cp312 CUDA wheel hosted on the prime-rl v0.6.0 release, matching how
deep-ep / deep-gemm / nixl-cu12 are shipped. Avoids requiring the CUDA
toolchain at install time on x86_64.

- torchao source -> release wheel URL, scoped to platform_machine == 'x86_64'
  (aarch64 continues to resolve torchao from the default index, untouched)
- drop torchao from no-build-isolation-package + the extra-build-variables block
- add torchao to the exclude-newer-package trusted-sources list

Wheel is H100 (sm90a) + B200 (sm100a), built from pytorch/ao@02105d4,
verified in a fresh py3.12 env (mxfp8 op registers, a2a imports).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Sort imports in expert_parallel.py (ruff I001)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix comments

* Fix alignment of 32 for grouped gemm backward

* Apply Samis Suggestions

* Add back default ignore patterns

* Fix name bug

* Reformat with ruff

* Config verifier

* Fix kernel redirect for > 32 token groups

* Ruff reformat

* chore: update uv.lock for torchao dependency

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: fix import sorting in MXFP8 files

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Move config check to config code

* Fix ruff

* Move config check to trainer

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 01:26:22 +02:00
minh hoangandGitHub 4d8df5120e chore(ci): remove ghcr-publish environment approval gate (#3059)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The build job in build_image.yaml opted into the ghcr-publish
environment solely for its required-reviewers protection rule, which
paused every ghcr build (release + .dev-tag dispatch on merge to main)
pending manual approval. The environment held no scoped secrets or
variables, so it provided nothing functional. The job already has
packages: write and authenticates via GITHUB_TOKEN, and ref
restrictions are enforced in the prepare job, so ghcr builds now
publish automatically.
2026-07-16 15:55:06 -07:00
6b1604380c feat(inference): uint16 routed-experts payload for >256-expert models (#3051)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(inference): uint16 routed-experts payload for >256-expert models

serialize_routed_experts packed expert indices as uint8, which overflows for
models with >256 experts — NemotronH Super/Ultra route top-22 over 512
experts, so every /generate call with routed-experts capture 500'd
(assert array.max() <= iinfo(uint8).max), stalling router-replay training.

Make the payload self-describing: pick uint8 when indices fit, uint16
otherwise, and emit the chosen dtype in the payload. Consumers default to
uint8 when the field is absent, so payloads from <=256-expert models are
byte-identical to before. Decoder half: verifiers feat/routed-experts-dtype
(must land first and be pinned here before a >256-expert model enables
enable_return_routed_experts).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(trainer): dtype-agnostic routed-experts row size

The batch packer sized routed-experts rows via a hardcoded
dtype->itemsize table that lacked uint16 (KeyError on the first >256-expert
batch). Use np.dtype(...).itemsize instead of maintaining the table.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to main (dtype-aware routed-experts decode)

PrimeIntellect-ai/verifiers#2043 merged — the decoder half of the
self-describing routed-experts payload. This pin makes the pair complete:
uint16 payloads from this branch's encoder are decoded correctly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: relock for the verifiers bump

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 11:47:20 -07:00
Mika SenghaasandGitHub 013a7f8c25 Revert "chore: remove fsdp_cpu_offload (#3049)" (#3052)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit c9acaa3c90.
2026-07-16 11:32:26 -07:00
samsjaandGitHub 3ff7902a73 fix(docker): bake optional dependencies into CUDA image (#3053)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-16 11:21:34 -07:00
c9acaa3c90 chore: remove fsdp_cpu_offload (#3049)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove fsdp_cpu_offload

The knob was effectively unusable: it breaks NCCL weight broadcast in RL
(state-dict tensors stay on CPU and the communicator asserts), muon rejects
it, it is mutually exclusive with optim_cpu_offload, and no config in the
repo uses it. Remove the field and all wiring instead of patching around it:
FSDP CPUOffloadPolicy selection, the buffer-migration helper, the gloo
backend plumbing in setup_torch_distributed, both muon validators, and docs.

optim_cpu_offload remains the supported CPU-offload knob. Default behavior
is unchanged: fully_shard's own default offload policy is OffloadPolicy().

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: drop offload_policy kwargs from direct fully_shard calls

Three fully_shard call sites passed offload_policy=offload_policy directly
(not via fsdp_config) and were missed by the removal — setup_fsdp raised
NameError. fully_shard's default is OffloadPolicy(), so omitting the kwarg
is behavior-identical. Verified by importing the trainer modules and
checking setup_fsdp's symbol table.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 17:59:21 -07:00
c7dc7929a0 chore: bump renderers to v0.1.8 (#3048)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 16:54:16 -07:00
0d2a7f5a12 chore: bump verifiers + research-environments (#3041)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump verifiers + research-environments to latest main

verifiers -> 1cfdd39c (incl. docker-runtime entrypoint fix #2015).
research-environments -> dd80d75b (incl. terminal-bench-2 use_prime_registry
fix #668).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: carry provider usage in advantage test rollouts

verifiers #2040 made Trace token counts usage-based, so the synthetic
rollouts (which only had token ids) reported 0 output/input tokens and the
length-penalty tests failed. Attach provider usage to the final sampled
turn so num_output_tokens / num_input_tokens reflect the intended lengths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 16:16:59 -07:00
1cb5d91ab2 feat(trainer): ulysses CP beyond num_kv_heads via GQA KV-head replication (#3042)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): fuse relu2 MoE activation via torch.compile

F.relu(x).square() ran eagerly (the expert path graph-breaks out of the
layer-level compile at the @expert_parallel all-to-all and the _grouped_mm
custom op), materializing an extra full-size copy of the MoE intermediate —
the largest activation for high top-k models (NemotronH Super: top-22,
moe_intermediate 2688; 57.75 GiB at 65k tokens/GPU) and the empirical OOM
site. An explicit torch.compile on relu2 fuses relu+square into a single
pointwise kernel. Measured on Nemotron Super (2xH200 nodes, 16k tokens/GPU):
OOM -> fits at 126.5/139.8 GiB peak.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(trainer): ulysses CP beyond num_kv_heads via GQA KV-head replication

Ulysses CP head-shards Q/K/V, capping the CP degree at num_key_value_heads —
for hybrid-Mamba GQA models like NemotronH Super/Ultra/Nano (2 KV heads) that
means cp <= 2, i.e. at most 2-way context sharding regardless of node count.
(NVIDIA post-trained Super at 256k-512k with CP=64 on Megatron's
sequence-sharded, Mamba-aware CP; prime-rl's ring CP is softmax-only.)

Replicate each KV head cp/num_kv_heads times before the existing seq->head
all-to-all. GQA groups query heads contiguously, so rank r's query-head slice
[r*Hq/cp, (r+1)*Hq/cp) attends KV head floor(r*Hkv/cp) — exactly the replica
the all-to-all lands on rank r. Backward of repeat_interleave sums gradients
over replicas, the exact GQA KV gradient. Q path and the num_kv_heads >= cp
case are unchanged; the Mamba layers already head-shard independently via
cp_mamba (128 heads, n_groups=8 -> cp <= 8 for NemotronH).

New constraint: cp % num_kv_heads == 0 when num_kv_heads < cp (asserted).
Unlocks cp=4/8 for NemotronH on H200 where cp=2 made 131k context
memory-infeasible (65k tokens/GPU through a top-22/512-expert MoE).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop relu2 comment

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 00:35:58 +02:00
87 changed files with 907 additions and 1021 deletions
-1
View File
@@ -116,7 +116,6 @@ jobs:
build:
name: Build and push (${{ matrix.suffix }})
needs: prepare
environment: ghcr-publish
strategy:
fail-fast: true
matrix: ${{ fromJson(needs.prepare.outputs.matrix) }}
+3 -8
View File
@@ -90,20 +90,15 @@ jobs:
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 real configs (with [slurm]) parse on slim install
- name: Verify real SFT config (with [slurm]) parses on slim install
run: |
/tmp/slim/bin/python - <<'PY'
from pydantic_config import cli
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.rl import RLConfig
# Configs that don't pull in a v1 env package parse on the slim
# (prime-rl-configs-only) install: the SFT config has no env sections, and the
# reverse_text RL recipe uses a v0 env id (resolved lazily, not imported at parse).
# RL configs on a v1 taskset can't parse here because vf.EnvServerConfig imports the
# (uninstalled) env package at parse time.
# The slim wheel intentionally excludes taskset packages, so validate a real
# SFT config here. RL recipes are covered by the full config suite.
for cfg_cls, args in [
(SFTConfig, ["@", "examples/reverse_text/slurm_sft.toml"]),
(RLConfig, ["@", "examples/reverse_text/rl.toml", "@", "examples/reverse_text/slurm_rl.toml"]),
]:
cfg = cli(cfg_cls, args=args)
assert cfg.slurm is not None, f"expected [slurm] in {args}"
+2 -6
View File
@@ -91,10 +91,6 @@ COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pr
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
# Opt-in extras for disaggregated P/D inference (deep-ep, deep-gemm, quack).
# Default off — they're heavy source builds only the disagg-MoE path needs.
# Enable via `--build-arg INCLUDE_DISAGG_EXTRAS=1`.
ARG INCLUDE_DISAGG_EXTRAS=0
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/app/.cache/uv \
@@ -109,9 +105,9 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra modelexpress --extra quack --group mamba-ssm --locked --no-dev \
&& \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
+5 -5
View File
@@ -17,20 +17,20 @@ group_size = 16
max_completion_tokens = 512
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2 }
taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2 }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "alphabet-sort"
name = "alphabet-sort"
num_examples = 50
group_size = 4
args = { min_turns = 2, max_turns = 2 }
taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2 }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
[inference]
[inference]
+2 -2
View File
@@ -23,9 +23,9 @@ group_size = 8
max_completion_tokens = 384
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
@@ -24,7 +24,9 @@ group_size = 16
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
@@ -23,7 +23,9 @@ group_size = 16
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
@@ -27,7 +27,9 @@ name = "r8-1e-4"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
enable_lora = true
@@ -26,7 +26,9 @@ name = "r8-1e-4"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
enable_lora = true
@@ -26,7 +26,9 @@ group_size = 16
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
gpu_memory_utilization = 0.7
@@ -15,7 +15,9 @@ lr = 3e-5
max_completion_tokens = 128
[[train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt]
interval = 10
@@ -38,7 +38,9 @@ name = "qwen3"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -48,7 +50,9 @@ num_examples = 16
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -45,7 +45,9 @@ name = "default"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -55,7 +57,9 @@ num_examples = 16
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+4 -3
View File
@@ -1,4 +1,4 @@
# ECHO on the multi-turn alphabet-sort env (bundled with verifiers): GRPO on
# ECHO on the multi-turn alphabet-sort V1 taskset: GRPO on
# action tokens + weighted CE on the env's observation tokens.
# uv run rl @ configs/debug/algorithms/echo.toml
@@ -25,8 +25,9 @@ type = "echo"
alpha = 0.1
[[orchestrator.train.env]]
id = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 512
+6 -2
View File
@@ -22,7 +22,9 @@ name = "qwen3"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -32,7 +34,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+6 -2
View File
@@ -22,7 +22,9 @@ name = "qwen3"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -32,7 +34,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+7 -3
View File
@@ -32,12 +32,14 @@ name = "qwen3"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-grpo"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-opd"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.env.algo]
type = "opd"
@@ -54,7 +56,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+6 -2
View File
@@ -34,7 +34,9 @@ name = "qwen3"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -44,7 +46,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+6 -2
View File
@@ -34,7 +34,9 @@ name = "qwen3"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -44,7 +46,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 1e-4
+6 -2
View File
@@ -30,7 +30,9 @@ name = "qwen3"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -40,7 +42,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+6 -2
View File
@@ -39,7 +39,9 @@ name = "default"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -49,7 +51,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -39,7 +39,9 @@ name = "default"
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -49,7 +51,9 @@ num_examples = 128
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 1e-4
+1 -1
View File
@@ -4,7 +4,7 @@ max_steps = 5
name = "PrimeIntellect/GLM-0.5B"
moe_use_grouped_mm = false
impl = "custom"
attn = "sdpa"
attn = "flash_attention_2"
[model.compile]
+9 -5
View File
@@ -18,12 +18,14 @@ name = "qwen3"
# -- multi train envs --
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-train-1"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-train-2"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
# -- multi eval envs --
@@ -33,12 +35,14 @@ num_examples = 16
group_size = 4
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text-eval-1"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text-eval-2"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
interval = 5
[trainer.optim]
@@ -48,4 +52,4 @@ lr = 3e-6
gpu_memory_utilization = 0.5
[inference.model]
max_model_len = 128
max_model_len = 128
+2 -2
View File
@@ -41,6 +41,6 @@ port = 8000
sync_interval = 5.0
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
+7 -13
View File
@@ -6,16 +6,10 @@ In this example, we demonstrate how to train `Qwen3-0.6B` to answer math problem
## Setup
Install the environment:
The `gsm8k-v1` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
prime env install primeintellect/math-env
```
Verify installation:
```bash
uv run python -c "import math_env"
uv run python -c "import gsm8k_v1"
```
Start the tmux session:
@@ -37,8 +31,8 @@ Evaluate the base model:
```bash
# In the `Trainer` pane
uv run vf-eval math-env \
-a '{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}' \
uv run vf-eval gsm8k-v1 \
-a '{"split": "test"}' \
-m PrimeIntellect/Qwen3-0.6B \
-b http://localhost:8000/v1 \
-n 20 \
@@ -74,10 +68,10 @@ uv run inference --model.name <user>/Qwen3-0.6B-GSM8K-RL
```bash
# In the `Trainer` pane
uv run vf-eval math-env \
-a '{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}' \
uv run vf-eval gsm8k-v1 \
-a '{"split": "test"}' \
-m <user>/Qwen3-0.6B-GSM8K-RL \
-b http://localhost:8000/v1 \
-n 20 \
-t 2048
```
```
+4 -10
View File
@@ -6,16 +6,10 @@ In this example, we demonstrate how to train `Qwen/Qwen3-4B-Instruct-2507` to an
## Setup
Install the environment:
The taskset is included through the research-environments workspace. After syncing the repository, verify it with:
```bash
prime env install primeintellect/math-env
```
Verify installation:
```bash
uv run python -c "import math_env"
uv run python -c "import math_env_v1"
```
Start the tmux session:
@@ -37,7 +31,7 @@ Evaluate the base model:
```bash
# In the `Trainer` pane
uv run vf-eval math-env \
uv run vf-eval math-env-v1 \
-a '{"dataset_name": "PrimeIntellect/Hendrycks-Math", "dataset_subset": "default"}' \
-m Qwen/Qwen3-4B-Instruct-2507 \
-b http://localhost:8000/v1 \
@@ -54,4 +48,4 @@ Train with the config file:
uv run rl @ configs/hendrycks_math/rl.toml \
--wandb.project your-project-name \
--wandb.name your-run-name
```
```
-43
View File
@@ -1,43 +0,0 @@
# math-python
## Setup
CLone `verifiers`
```bash
cd ~ && curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/verifiers/main/scripts/install.sh | bash && cd -
```
Install the environment as local packages
```bash
uv pip install -e ~/verifiers/environments/math_python
```
This will automatically install the environment, and a pinned verifiers commit (`71006c`) which includes necessary changes to the PythonEnv.
## Eval
Get a quick vibe-check of the model
```bash
vllm serve Qwen/Qwen3-4B-Instruct-2507 --enable-auto-tool-choice --tool-call-parser hermes --max-model-len 8192
```
```bash
uv run --no-sync vf-eval math-python -n 16 -r 1 -c -1 -v -m Qwen/Qwen3-4B-Instruct-2507 -b http://localhost:8000/v1 -a '{"dataset_name": "PrimeIntellect/Hendrycks-Math", "dataset_subset": "default"}' -t 512
```
## RL
Again, make sure to have installed the environment as local packages from verifiers
```bash
uv pip install -e ~/verifiers/environments/math_python
```
Then, run RL in debug mode (small batch size, limited turns, 2 GPUs, etc.)
```bash
uv run --no-sync rl @ configs/math_python/math_python.toml --log.level debug
```
-29
View File
@@ -1,29 +0,0 @@
max_steps = 300
seq_len = 4096
[wandb]
project = "math-python-debug"
name = "math-python"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.env]]
id = "math-python"
args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy" }
[trainer] # Default trainer config
[inference]
api_server_count = 4
[inference.model]
tool_call_parser = "hermes"
max_model_len = 4096
+3 -1
View File
@@ -34,7 +34,9 @@ oversampling_factor = 2.0
max_completion_tokens = 512
[[orchestrator.train.env]]
id = "wiki-search"
name = "wiki-search"
taskset = { id = "wiki-search-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference.model]
tool_call_parser = "hermes"
+4 -4
View File
@@ -1,6 +1,5 @@
# Wordle (classic v0 TextArena env) on 2 GPUs (1 trainer + 1 inference), run via the
# legacy bridge. The Wordle-SFT model plays a full ~6-turn game per rollout; the bridge
# serves each multi-turn rollout to the orchestrator as a vf.Trace.
# Wordle on 2 GPUs (1 trainer + 1 inference). The Wordle-SFT model plays a
# full ~6-turn game per rollout.
max_steps = 200
seq_len = 8192
@@ -23,8 +22,9 @@ batch_size = 128
group_size = 8
[[orchestrator.train.env]]
id = "wordle"
name = "wordle"
taskset = { id = "wordle-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 1024
+1 -1
+1 -1
+15 -1
View File
@@ -36,7 +36,21 @@ impl = "custom" # or "hf" to force the HF path
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
### Low-precision training
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
```toml
[trainer.model.quantization]
type = "mxfp8"
recipe = "mxfp8_rceil"
enable_a2a = true
```
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
+9 -7
View File
@@ -148,26 +148,28 @@ Training environments are an array of tables — set one per env, optionally wit
```toml
[[orchestrator.train.env]]
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
taskset = { id = "gsm8k-v1", split = "train" }
harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 3 # 75% of batches
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 1 # default — 25% of batches
[[orchestrator.eval.env]]
id = "math-env"
name = "gsm8k-eval"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
taskset = { id = "gsm8k-v1", split = "test" }
harness = { id = "null", runtime = { type = "subprocess" } }
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
Fields in `taskset` configure the V1 taskset. `harness` selects how its tasks are run.
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
The same taskset can appear multiple times across train and eval (or with different settings) — useful for evaluating on a held-out split or comparing two configurations side by side. When it is reused, set a distinct `name` on each entry; `name` defaults to the taskset id and must be unique across all envs in the same group.
### Environment Variables
+2
View File
@@ -107,6 +107,8 @@ ep_comm_backend = "torch" # or "deepep"
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
```toml
[trainer.model]
impl = "custom"
+7 -11
View File
@@ -1,19 +1,15 @@
# Alphabet Sort
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the [`primeintellect/alphabet-sort`](https://app.primeintellect.ai/dashboard/environments/primeintellect/alphabet-sort) environment.
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the `alphabet-sort-v1` taskset.
> This example runs on a single H100 GPU.
## Setup
Install the environment:
```bash
prime env install primeintellect/alphabet-sort
```
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
Verify installation:
```bash
uv run python -c "import alphabet_sort"
uv run python -c "import alphabet_sort_v1"
```
Start the tmux session:
@@ -42,12 +38,12 @@ uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run vf-eval alphabet-sort \
uv run vf-eval alphabet-sort-v1 \
-m Qwen/Qwen3-4B-Instruct-2507 \
-b http://localhost:8000/v1 \
-n 20 \
--max-tokens 768 \
--env-args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "similarity_power": 8, "power_per_turn": false}'
--env-args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}'
```
We got an **average reward of ~0.26** across 20×3 rollouts. The model achieves **0% perfect attempts** (no rollouts score 1.0) and **0% perfect examples** (no examples have all 3 rollouts at 1.0). The model shows high variance and struggles on most examples, with the high similarity power (8) heavily penalizing even small errors, and the scores aren't different for most attempts.
@@ -118,12 +114,12 @@ uv run inference --enable-lora --model.name PrimeIntellect/Qwen3-4B-Instruct-Alp
```bash
# In the `Trainer` pane
uv run vf-eval alphabet-sort \
uv run vf-eval alphabet-sort-v1 \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
-b http://localhost:8000/v1 \
-n 20 \
--max-tokens 768 \
--env-args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "similarity_power": 8, "power_per_turn": false}'
--env-args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}'
```
Way better! Our model now gets an **average reward of ~0.81** with **73% perfect attempts** (44/60 rollouts score 1.0) and **65% perfect examples** (13/20 examples have all 3 rollouts at 1.0).
+3 -3
View File
@@ -32,8 +32,8 @@ group_size = 8
max_completion_tokens = 768
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference] # Default inference config
[inference] # Default inference config
+3 -1
View File
@@ -61,7 +61,9 @@ fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
fp8 = true
[trainer.model.quantization]
type = "fp8"
[trainer.model.ac]
freq = 1
+7 -7
View File
@@ -1,15 +1,15 @@
# Reverse Text
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run to reverse smaller chunks of text in the [`reverse-text`](https://app.primeintellect.ai/dashboard/environments/primeintellect/reverse-text) environment. We use a similar setup in our CI at the moment and for development.
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text-v1` taskset. We use a similar setup in our CI and for development.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
## Setup
We keep the `reverse-text` in our lock file because we use it frequently in our CI and for development. If you have synced the environment, you should already have it installed. To verify, run
The `reverse-text-v1` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import reverse_text"
uv run python -c "import reverse_text_v1"
```
First, let's start a `tmux` session which we will use throughout the experiment.
@@ -27,7 +27,7 @@ uv run inference --model.name Qwen/Qwen3-0.6B
```bash
# Run this in the `Trainer` pane
uv run vf-eval reverse-text -m Qwen/Qwen3-0.6B -b http://localhost:8000/v1 -n 20 --max-tokens 1024
uv run vf-eval reverse-text-v1 -m Qwen/Qwen3-0.6B -b http://localhost:8000/v1 -n 20 --max-tokens 1024
```
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
@@ -102,7 +102,7 @@ uv run inference --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```bash
# Run this in the `Trainer` pane
uv run vf-eval reverse-text -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL -b http://localhost:8000/v1 -n 20 --max-tokens 1024
uv run vf-eval reverse-text-v1 -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL -b http://localhost:8000/v1 -n 20 --max-tokens 1024
```
Way better! Now we get an **average reward of ~0.8**.
@@ -215,7 +215,7 @@ kubectl exec -it my-exp-inference-0 -- bash
uv run inference --model.name /data/outputs/weights/step_20
# Back in trainer pod, run evaluation
uv run vf-eval reverse-text \
uv run vf-eval reverse-text-v1 \
-m /data/outputs/weights/step_20 \
-b $INFERENCE_URL \
-n 20 --max-tokens 1024
@@ -236,4 +236,4 @@ kubectl delete pvc prime-rl-shared-data
- Kubernetes services for component communication
- Auto-start capability with proper networking configured
See the [K8s deployment guide](../../k8s/README.md) for more details on scaling, distributed training, and advanced configurations.
See the [K8s deployment guide](../../k8s/README.md) for more details on scaling, distributed training, and advanced configurations.
+3 -1
View File
@@ -16,7 +16,9 @@ group_size = 16
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+23 -48
View File
@@ -4,8 +4,8 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to answer
- **Single-file configuration**: All training settings (trainer, orchestrator, and inference) are specified in a single `rl.toml` file
- **LoRA training**: Efficient fine-tuning using LoRA (Low-Rank Adaptation) on attention and MLP layers
- **Multi-turn tool use**: The model learns to use tools across multiple turns via `ToolEnv` via native function calling
- **Locally-hosted storage**: Uses ChromaDB for vector search and OpenAI embeddings for retrieval
- **Multi-turn tool use**: The model learns to use V1 tools across multiple turns through native function calling
- **Locally-hosted storage**: Uses ChromaDB and its local embedding model for retrieval
- **LLM judges**: Uses an LLM judge to evaluate answer quality alongside tool execution metrics
- **Online difficulty buffer**: Uses difficulty-based sampling to ensure rollouts have strictly non-zero advantages
@@ -13,19 +13,13 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to answer
## Setup
Install the environment:
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
prime env install primeintellect/wiki-search
uv run python -c "import wiki_search_v1"
```
Verify installation:
```bash
uv run python -c "import wiki_search"
```
Set up your OpenAI API key for the judge and embedding models:
Set up the credentials for the configured reference judge:
```bash
export OPENAI_API_KEY=your_api_key_here
@@ -46,19 +40,16 @@ The wiki-search environment requires the model to answer trivia questions by:
3. **Reading** specific sections to extract answers
4. **Answering** the question correctly and coherently
The environment provides three tools:
- `search_pages(query)`: Performs embedding-based search over Wikipedia page titles, returning the top 10 relevant pages
- `view_sections(page_id)`: Lists all sections available in a Wikipedia page
- `read_section(section_id)`: Retrieves the content of a specific section
The taskset provides three tools:
- `wiki_search_pages(query)`: Performs embedding-based search over Wikipedia page titles, returning the top 10 relevant pages
- `wiki_view_sections(page_id)`: Lists all sections available in a Wikipedia page
- `wiki_read_section(section_id)`: Retrieves the content of a specific section
The corpus is indexed in ChromaDB using OpenAI embeddings (`text-embedding-3-small` by default). On first run, the environment automatically builds the index from the `willcb/rare-wiki-pages` dataset, storing it locally in `.chroma_db`.
The corpus is indexed in ChromaDB using its local embedding model. On first run, the taskset builds the index from `willcb/rare-wiki-pages` and stores it under `~/.cache/wiki_search` by default.
## Scoring
The environment uses a composite rubric combining:
1. **ToolRubric**: Evaluates tool execution success and format adherence
2. **JudgeRubric**: An LLM judge (default: `gpt-4.1-mini`) evaluates whether the final answer is both correct and coherent
The taskset uses a reference-answer judge (default: `openai/gpt-5.4-nano`) to evaluate whether the final answer is both correct and coherent.
The judge compares the model's response against the ground truth answer and returns a binary score (1.0 for correct and coherent, 0.0 otherwise).
@@ -70,7 +61,7 @@ Key configuration highlights:
- **LoRA training**: Rank 8, alpha 32 for efficient fine-tuning
- **Tool calling**: Uses Hermes parser for automatic tool selection with Qwen3-4B-Instruct-2507
- **Multi-turn**: Up to 10 turns per episode (configurable via environment args)
- **Multi-turn**: Tool calls and results are carried across turns by the V1 harness
- **Online difficulty buffer**: Uses difficulty-based sampling with 2x oversampling
## Baseline Evaluation
@@ -86,12 +77,11 @@ Evaluate the base model:
```bash
# In the `Trainer` pane
uv run vf-eval wiki-search \
uv run vf-eval wiki-search-v1 \
-m Qwen/Qwen3-4B-Instruct-2507 \
-b http://localhost:8000/v1 \
-n 20 \
--max-tokens 512 \
--env-args '{"judge_model": "gpt-4.1-mini", "judge_base_url": "https://api.openai.com/v1", "judge_api_key_var": "OPENAI_API_KEY", "embed_model": "text-embedding-3-small", "embed_base_url": "https://api.openai.com/v1", "embed_api_key_var": "OPENAI_API_KEY"}'
--max-tokens 512
```
## RL Training
@@ -127,42 +117,27 @@ uv run inference --enable-lora --model.name <user>/Qwen3-4B-Instruct-WikiSearch-
```bash
# In the `Trainer` pane
uv run vf-eval wiki-search \
uv run vf-eval wiki-search-v1 \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
-b http://localhost:8000/v1 \
-n 20 \
--max-tokens 512 \
--env-args '{"judge_model": "gpt-4.1-mini", "judge_base_url": "https://api.openai.com/v1", "judge_api_key_var": "OPENAI_API_KEY", "embed_model": "text-embedding-3-small", "embed_base_url": "https://api.openai.com/v1", "embed_api_key_var": "OPENAI_API_KEY"}'
--max-tokens 512
```
## Environment Arguments
## Taskset Configuration
The wiki-search environment supports several configuration options:
| Argument | Type | Default | Description |
| --- | ---- | ------- | ----------- |
| `max_turns` | int | `10` | Maximum number of tool-use turns per episode |
| `judge_model` | str | `"gpt-4.1-mini"` | Judge model name |
| `judge_base_url` | str | `"https://api.openai.com/v1"` | Judge provider base URL |
| `judge_api_key_var` | str | `"OPENAI_API_KEY"` | Environment variable for judge API key |
| `embed_model` | str | `"text-embedding-3-small"` | Embedding model name |
| `embed_base_url` | str | `"https://api.openai.com/v1"` | Embedding provider base URL |
| `embed_api_key_var` | str | `"OPENAI_API_KEY"` | Environment variable for embedding API key |
| `corpus_dataset` | str | `"willcb/rare-wiki-pages"` | HuggingFace dataset ID containing Wikipedia pages |
| `corpus_split` | str | `"train"` | Dataset split to load |
| `chroma_db_dir` | str | `".chroma_db"` | Path to ChromaDB index directory |
You can pass these via the `--env-args` flag in `vf-eval` or configure them in your `rl.toml`:
The V1 taskset fixes the question bank and searchable corpus. You can replace its reference judge in `rl.toml`:
```toml
[[orchestrator.train.env]]
id = "primeintellect/wiki-search"
args = { max_turns = 5, judge_model = "gpt-4.1" }
name = "wiki-search"
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null", runtime = { type = "subprocess" } }
```
## Notes
- The first run will build the ChromaDB index, which may take a minute or two
- Ensure `OPENAI_API_KEY` is set in your environment for both judge and embedding calls
- The ChromaDB index is stored locally in `.chroma_db` and persists across runs
- Ensure the selected judge's API credentials are available in your environment
- The ChromaDB index persists under `~/.cache/wiki_search`; set `WIKI_SEARCH_CACHE` to move it
- Tool calling requires `enable_auto_tool_choice = true` and a compatible parser (Hermes is recommended)
+3 -1
View File
@@ -45,7 +45,9 @@ type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
id = "wiki-search"
name = "wiki-search"
taskset = { id = "wiki-search-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt] # Checkpoint at the end of training
+5 -11
View File
@@ -1,21 +1,15 @@
# Wordle
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format of the environment and, finally, multi-turn RL against the [`wordle`](https://app.primeintellect.ai/dashboard/environments/will/wordle) environment to improve performance.
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle-v1` taskset to improve performance.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
## Setup
First, let's install the environment using the `prime` (`uv tool install prime`)
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
prime env install will/wordle
```
Verify your installation by trying to import the environment.
```bash
uv run python -c "import wordle"
uv run python -c "import wordle_v1"
```
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
@@ -35,7 +29,7 @@ Then, use the `vf-eval` entrypoint to evaluate the model in the `wordle` environ
```bash
# Run this in the `Trainer` pane
uv run vf-eval wordle -m Qwen/Qwen3-1.7B -b http://localhost:8000/v1 -n 20 -t 1024
uv run vf-eval wordle-v1 -m Qwen/Qwen3-1.7B -b http://localhost:8000/v1 -n 20 -t 1024
```
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
@@ -111,7 +105,7 @@ uv run inference --model.name PrimeIntellect/Qwen3-1.7B-Wordle-RL
```bash
# Run this in the `Trainer` pane
uv run vf-eval wordle -m PrimeIntellect/Qwen3-1.7B-Wordle-RL -b http://localhost:8000/v1 -n 20 --max-tokens 1024
uv run vf-eval wordle-v1 -m PrimeIntellect/Qwen3-1.7B-Wordle-RL -b http://localhost:8000/v1 -n 20 --max-tokens 1024
```
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
+2 -1
View File
@@ -19,8 +19,9 @@ batch_size = 1024
group_size = 16
[[orchestrator.train.env]]
id = "wordle"
name = "wordle"
taskset = { id = "wordle-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 1024
@@ -221,9 +221,6 @@ class SFTConfig(BaseConfig):
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
"""Cross-entropy loss implementation. ``liger_fused`` fuses the lm_head projection with the CE loss to avoid materializing full logits. ``quack_fused`` uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -361,11 +358,6 @@ class SFTConfig(BaseConfig):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_and_disable_chunked_loss(self):
self.model.fused_lm_head_token_chunk_size = "disabled"
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
@@ -18,15 +18,9 @@ from prime_rl.utils.config import BaseConfig
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["eager", "sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4"]
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
# User-facing name -> internal name. Users set `flash_attention_4` in configs,
# which gets rewritten to `fa4` before pydantic validation.
# We use `fa4` internally because `flash_attention_*` triggers transformers
# to attempt installing a kernel from hub.
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
class GCConfig(BaseConfig):
interval: int = Field(50, ge=1)
@@ -116,6 +110,42 @@ class DebugModelConfig(BaseConfig):
"""Replace MoE token-choice routing with a round-robin assignment so every expert sees an equal share. Intended for fake-data smoke tests where untrained routing would otherwise OOM under severe imbalance. Gating scores are still gathered from the override indices so the forward pass stays consistent."""
MXFP8Recipe: TypeAlias = Literal["mxfp8_rceil", "mxfp8_rceil_wgrad_with_hp"]
_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",
]
class FP8Config(BaseConfig):
type: Literal["fp8"] = "fp8"
enable_grouped_gemm: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
class MXFP8Config(BaseConfig):
type: Literal["mxfp8"] = "mxfp8"
recipe: MXFP8Recipe = "mxfp8_rceil"
enable_grouped_gemm: bool = True
enable_a2a: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
class ModelConfig(BaseModelConfig):
conversion_dir: Path | None = None
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
@@ -123,7 +153,7 @@ class ModelConfig(BaseModelConfig):
seq_len: int = 2048
"""Sequence length the model is trained on."""
attn: AttnImplementation = "flash_attention_2"
attn: AttnImplementation = "flash_attention_3"
"""Attention implementation. With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
compile: CompileConfig | None = CompileConfig()
@@ -180,8 +210,7 @@ class ModelConfig(BaseModelConfig):
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
fp8: bool = False
"""FP8 training via DeepGEMM. Replaces ``nn.Linear`` with FP8 blockwise linear and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and ``model.impl='custom'``."""
quantization: QuantizationConfig | None = None
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
@@ -198,14 +227,6 @@ class ModelConfig(BaseModelConfig):
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
@model_validator(mode="before")
@classmethod
def _normalize_attn_alias(cls, data):
"""Rewrite user-facing `flash_attention_4` to internal `fa4` before validation."""
if isinstance(data, dict) and data.get("attn") in _ATTN_ALIASES:
data["attn"] = _ATTN_ALIASES[data["attn"]]
return data
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
@@ -216,15 +237,19 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "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":
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4"]:
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
if (
self.cp > 1
and self.attn in ("flash_attention_3", "flash_attention_4")
and self.impl not in ("custom", "auto")
):
# 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' "
f"CP with {self.attn} requires model.impl='custom' or 'auto' "
"(FA3/FA4 paths are only implemented for the custom model attention class)"
)
return self
@@ -250,14 +275,14 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
if self.attn == "fa4" and self.impl != "custom":
raise ValueError("Flash attention 4 is only supported with the custom implementation")
if self.attn == "flash_attention_4" and self.impl not in ("custom", "auto"):
raise ValueError("Flash attention 4 is only supported with model.impl='custom' or 'auto'")
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'.")
def quantization_only_with_custom_impl(self):
if self.quantization is not None and self.impl not in ("custom", "auto"):
raise ValueError(f"{self.quantization.type} training is only supported with model.impl='custom' or 'auto'.")
return self
@model_validator(mode="after")
@@ -270,6 +295,12 @@ class ModelConfig(BaseModelConfig):
return self
@model_validator(mode="after")
def mxfp8_only_with_torch_ep_backend(self):
if isinstance(self.quantization, MXFP8Config) and self.ep_comm_backend != "torch":
raise ValueError("MXFP8 quantization requires model.ep_comm_backend='torch'.")
return self
class TokenizerConfig(BaseConfig):
name: str | None = None
+3 -1
View File
@@ -10,7 +10,6 @@ dependencies = [
"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",
"numpy>=2.2.6",
@@ -44,6 +43,7 @@ dependencies = [
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
"torchao>=0.17.0",
]
[project.scripts]
@@ -179,6 +179,7 @@ dion = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
torchao = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
@@ -193,6 +194,7 @@ torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
vllm-router = [
+5 -3
View File
@@ -41,11 +41,13 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
```toml
[[orchestrator.env]]
id = "reverse-text"
[[orchestrator.train.env]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
```
CLI: `--env.0.id reverse-text --env.1.id math-env`.
CLI: `--orchestrator.train.env.0.taskset.id reverse-text-v1`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
@@ -15,15 +15,21 @@ def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, A
array = np.asarray(routed_experts)
assert array.ndim == 3
assert np.issubdtype(array.dtype, np.integer)
dtype = np.uint8
if array.size:
assert array.min() >= 0
assert array.max() <= np.iinfo(np.uint8).max
if array.max() > np.iinfo(np.uint8).max:
# Models with >256 experts (e.g. NemotronH Super/Ultra: 512) need wider
# indices. The payload self-describes via "dtype" so consumers pick it up.
assert array.max() <= np.iinfo(np.uint16).max
dtype = np.uint16
compact = np.ascontiguousarray(array.astype(np.uint8, copy=False))
compact = np.ascontiguousarray(array.astype(dtype, copy=False))
return {
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
"shape": list(compact.shape),
"start": start,
"dtype": np.dtype(dtype).name,
}
+1 -7
View File
@@ -7,12 +7,6 @@ import numpy as np
from prime_rl.trainer.utils import balanced_partition
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
"uint8": 1,
"int16": 2,
"int32": 4,
}
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
# means no component (weight 0.0).
@@ -28,7 +22,7 @@ def _copy_routed_experts(routed_experts: RoutedExperts) -> RoutedExperts:
def _routed_experts_row_size(routed_experts: RoutedExperts) -> int:
return routed_experts.shape[1] * routed_experts.shape[2] * ROUTED_EXPERTS_DTYPE_ITEMSIZE[routed_experts.dtype]
return routed_experts.shape[1] * routed_experts.shape[2] * np.dtype(routed_experts.dtype).itemsize
def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> RoutedExperts:
+2 -2
View File
@@ -1,3 +1,3 @@
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, get_ep_group
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, MXFP8AllToAllExpertParallel, get_ep_group
__all__ = ["DeepEPExpertParallel", "get_ep_group"]
__all__ = ["DeepEPExpertParallel", "MXFP8AllToAllExpertParallel", "get_ep_group"]
@@ -1,7 +1,67 @@
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.distributed import ProcessGroup
from torch.distributed.distributed_c10d import _resolve_process_group
from torch.distributed.tensor import DeviceMesh, Shard, distribute_module, distribute_tensor
from torch.distributed.tensor.parallel import ParallelStyle
from torchao.prototype.moe_training.ep import a2a_combine_hp_fwd_mxfp8_bwd, a2a_dispatch_mxfp8_fwd_hp_bwd
from torchao.prototype.mx_formats.mx_tensor import MXTensor
from torchtitan.distributed.expert_parallel import ExpertParallel
class _MXFP8Dispatch(torch.autograd.Function):
@staticmethod
def forward(ctx, routed_input, output_splits, input_splits, group_name):
mx_routed_input = a2a_dispatch_mxfp8_fwd_hp_bwd(routed_input, output_splits, input_splits, group_name)
ctx.input_splits = input_splits
ctx.output_splits = output_splits
ctx.group = _resolve_process_group(group_name)
return mx_routed_input.dequantize(routed_input.dtype)
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.new_empty((sum(ctx.input_splits),) + tuple(grad_output.shape[1:]))
dist.all_to_all_single(
grad_input, grad_output.contiguous(), ctx.input_splits, ctx.output_splits, group=ctx.group
)
return grad_input, None, None, None
class _DequantMXGradInBwd(torch.autograd.Function):
@staticmethod
def forward(ctx, x, hp_dtype):
ctx.hp_dtype = hp_dtype
return x
@staticmethod
def backward(ctx, grad_output):
if isinstance(grad_output, MXTensor):
grad_output = grad_output.dequantize(ctx.hp_dtype)
return grad_output, None
class MXFP8AllToAllExpertParallel(ExpertParallel):
def _token_dispatch(self, mod, inputs, device_mesh):
routed_input, num_tokens_per_expert = inputs
with torch.no_grad():
num_tokens_per_expert_group = num_tokens_per_expert.new_empty(num_tokens_per_expert.shape[0])
dist.all_to_all_single(num_tokens_per_expert_group, num_tokens_per_expert, group=device_mesh.get_group())
self.input_splits = num_tokens_per_expert.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
self.output_splits = num_tokens_per_expert_group.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
routed_input = _MXFP8Dispatch.apply(
routed_input, self.output_splits, self.input_splits, device_mesh.get_group().group_name
)
return routed_input, num_tokens_per_expert_group
def _token_combine(self, mod, routed_output, device_mesh):
routed_output = _DequantMXGradInBwd.apply(routed_output, routed_output.dtype)
return a2a_combine_hp_fwd_mxfp8_bwd(
routed_output,
self.input_splits,
self.output_splits,
device_mesh.get_group().group_name,
)
class DeepEPExpertParallel(ParallelStyle):
+57 -36
View File
@@ -26,8 +26,15 @@ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, Genera
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
from prime_rl.configs.trainer import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
from prime_rl.trainer.distributed import DeepEPExpertParallel
from prime_rl.configs.trainer import (
ActivationCheckpointConfig,
CompileConfig,
FP8Config,
ModelConfig,
MXFP8Config,
TokenizerConfig,
)
from prime_rl.trainer.distributed import DeepEPExpertParallel, MXFP8AllToAllExpertParallel
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
from prime_rl.trainer.models import (
AutoModelForCausalLMPrimeRL,
@@ -46,6 +53,8 @@ from prime_rl.trainer.models.layers.checkpointing import (
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, TokenChoiceTopKRouter
from prime_rl.trainer.models.layers.mxfp8_grouped_gemm import apply_mxfp8_moe_grouped_gemm
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.weights import (
load_state_dict,
@@ -273,7 +282,7 @@ def _patch_qwen3_5_linear_attn_varlen():
):
attn_impl = getattr(self.config, "_attn_implementation", None)
cu_seqlens = None
if attn_impl in ("flash_attention_2", "flash_attention_3", "fa4") and position_ids is not None:
if attn_impl in ("flash_attention_2", "flash_attention_3", "flash_attention_4") and position_ids is not None:
pids = position_ids
if pids.ndim == 3:
pids = pids[0]
@@ -501,17 +510,14 @@ def get_model(
)
# GPT-OSS only supports FlashAttention via kernels-community/vllm-flash-attn3, which requires Hopper (SM 90).
# On other architectures (e.g. Blackwell), users must fall back to eager attention.
HOPPER_MAJOR = 9
if getattr(model_config, "model_type", "") == "gpt_oss":
if config.attn != "eager":
major, minor = torch.cuda.get_device_capability()
if major != HOPPER_MAJOR:
raise ValueError(
f"GPT-OSS requires 'attn = \"eager\"' on non-Hopper GPUs (detected SM {major}{minor}). "
f"The only flash attention kernel supported by GPT-OSS (kernels-community/vllm-flash-attn3) is Hopper-only. "
f'Set [trainer.model] attn = "eager" in your config.'
)
major, minor = torch.cuda.get_device_capability()
if major != HOPPER_MAJOR:
raise ValueError(
f"GPT-OSS requires Hopper (SM 90) for flash attention, detected SM {major}{minor}. "
f"GPT-OSS is not supported on non-Hopper GPUs."
)
# Enable hub kernels for GPT-OSS (disabled by default to avoid interfering with other models).
import transformers.integrations.hub_kernels as _hub_kernels
@@ -527,7 +533,11 @@ 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
# MoEArgs.fp8 (read via getattr(config, "fp8") in the modeling files) gates the
# DeepGEMM FP8 grouped GEMM. MXFP8 grouped GEMM is applied by wrapping the expert
# weights with torchao (see apply_quantization), so it leaves this flag False and
# the experts keep calling torch._grouped_mm — which the wrapper tensor intercepts.
model_config.fp8 = isinstance(config.quantization, FP8Config) and config.quantization.enable_grouped_gemm
if config.index_cache is not None:
model_config.use_index_cache = True
@@ -1037,13 +1047,43 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
get_logger().info(f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph})")
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
"""Swap dense linears and MoE expert GEMMs to the configured low-precision path.
Runs after the LM head is injected but before LoRA / EP / FSDP so the swapped
modules and wrapped parameters are picked up by the later parallelisms. The
FP8 grouped GEMM (DeepGEMM) is gated separately via ``model_config.fp8`` since
it lives inside the modeling code; here we only handle the dense-linear swap
and the torchao MXFP8 expert-weight wrapping.
"""
quant = config.quantization
if quant is None:
return
if isinstance(quant, FP8Config):
replace_linear_with_fp8_blockwise_linear(model, ignore_modules=quant.ignore_patterns)
elif isinstance(quant, MXFP8Config):
capability = torch.cuda.get_device_capability()
if capability < (10, 0):
raise ValueError(
f"MXFP8 quantization requires SM100 (Blackwell) or newer, but device is SM{capability[0]}{capability[1]}."
)
replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=quant.ignore_patterns)
if quant.enable_grouped_gemm:
apply_mxfp8_moe_grouped_gemm(model, recipe=quant.recipe)
def apply_ep(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
language_model = get_language_model(model)
for transformer_block in language_model.layers:
block_mlp = getattr(transformer_block, "mlp", None)
if block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
if config.ep_comm_backend == "torch":
parallelize_plan = ExpertParallel()
quant = config.quantization
if isinstance(quant, MXFP8Config) and quant.enable_a2a:
parallelize_plan = MXFP8AllToAllExpertParallel()
else:
parallelize_plan = ExpertParallel()
else:
parallelize_plan = DeepEPExpertParallel()
parallelize_module(
@@ -1088,36 +1128,18 @@ def _validate_flash_attn_4_installed() -> None:
)
def _register_fa4_attention_interface() -> None:
"""Register a dummy `fa4` attention with transformers so AutoConfig accepts it.
The `flash_attention_*` naming pattern triggers transformers to attempt
installing a kernel from the hub, so we use the short name `fa4` internally.
This dummy is never called because fa4 is only supported with our custom
model implementation.
"""
from transformers import AttentionInterface
def _noop(*args, **kwargs) -> None:
pass
AttentionInterface.register("fa4", _noop)
def setup_model(
config: ModelConfig,
parallel_dims: ParallelDims,
loading_from_checkpoint_later: bool = False,
fused_cross_entropy: bool | str = False,
) -> nn.Module:
if config.attn == "flash_attention_3" and not is_flash_attn_3_available():
raise ValueError(
"Flash attention 3 is only supported if the flash_attn_3 package is installed. Install with `uv pip install 'flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper' --no-build-isolation`"
)
if config.attn == "fa4":
if config.attn == "flash_attention_4":
_validate_flash_attn_4_installed()
_register_fa4_attention_interface()
logger = get_logger()
@@ -1142,10 +1164,9 @@ def setup_model(
if isinstance(config.fused_lm_head_token_chunk_size, int):
lm_head_chunk_size = config.fused_lm_head_token_chunk_size
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size)
if config.fp8:
replace_linear_with_fp8_blockwise_linear(model)
apply_quantization(model, config)
# Apply LoRA before FSDP setup
if config.lora is not None:
@@ -3,7 +3,6 @@ from dataclasses import dataclass
from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
@@ -105,78 +104,6 @@ class AfmoeAttentionBase(nn.Module):
return self.o_proj(attn_output)
class AfmoeSDPAAttention(AfmoeAttentionBase):
"""AFMoE attention using PyTorch's scaled_dot_product_attention."""
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape)
key_states = self.k_proj(hidden_states).view(hidden_shape)
value_states = self.v_proj(hidden_states).view(hidden_shape)
gate_states = self.gate_proj(hidden_states)
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
if self.is_local_attention:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
return query_states, key_states, value_states, gate_states
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
dropout_p: float = 0.0,
) -> torch.Tensor:
return F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
dropout_p=dropout_p,
is_causal=attention_mask is None,
scale=self.scaling,
)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate_states = self.attn_projections(hidden_states, position_embeddings)
dropout_p = self.attention_dropout if self.training else 0.0
attn_output = self._attention_core(
query_states,
key_states,
value_states,
attention_mask=attention_mask,
dropout_p=dropout_p,
)
return self.output_proj(attn_output, gate_states), None
class AfmoeFlashAttention(AfmoeAttentionBase):
"""AFMoE attention using Flash Attention varlen functions."""
@@ -263,10 +190,9 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
AFMOE_ATTN_IMPL2CLASS = {
"sdpa": AfmoeSDPAAttention,
"flash_attention_2": functools.partial(AfmoeFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(AfmoeFlashAttention, flash_attn_version=3),
"fa4": functools.partial(AfmoeFlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(AfmoeFlashAttention, flash_attn_version=4),
}
@@ -299,8 +225,6 @@ def _get_afmoe_attention(config: AfmoeConfig, layer_idx: int) -> nn.Module:
)
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
if attn_impl not in AFMOE_ATTN_IMPL2CLASS:
supported = list(AFMOE_ATTN_IMPL2CLASS.keys())
@@ -394,7 +318,7 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
"k_norm",
"norm",
]
_supports_sdpa = True
_supports_sdpa = False
_supports_flash_attn = True
_supports_flex_attn = False
_supports_attention_backend = True
@@ -478,7 +402,7 @@ class AfmoeModel(AfmoePreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4")
if use_flash:
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
+16
View File
@@ -21,6 +21,22 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
"""PrimeRL models use custom MoE implementations and don't support dynamic experts implementation."""
return False
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
"""Bypass transformers' flash attention availability checks.
PrimeRL custom models dispatch attention through their own ``ATTN_IMPL2CLASS``
dictionaries, not through transformers' ``ALL_ATTENTION_FUNCTIONS``. The default
``_check_and_adjust_attn_implementation`` validates that the requested flash
attention package is installed and the device is supported, which fails on
CPU-only machines and is unnecessary because we never call transformers'
attention dispatch for custom models.
"""
if attn_implementation is None:
attn_implementation = "flash_attention_3"
return attn_implementation
def get_correct_experts_implementation(self, requested_experts: str | None) -> str:
"""PrimeRL models always use eager experts implementation."""
return "eager"
@@ -121,7 +121,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Glm4MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -216,7 +216,7 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -126,7 +126,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["GlmMoeDsaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -22,7 +22,7 @@ from prime_rl.trainer.models.laguna.converting_laguna import (
convert_prime_layer_to_hf,
convert_prime_to_hf,
)
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention, SDPAAttention
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
@@ -138,70 +138,16 @@ class LagunaFlashAttention(FlashAttention):
return self.o_proj(attn_output), None
class LagunaSDPAAttention(SDPAAttention):
def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int):
super().__init__(_laguna_attention_config(config, num_heads))
self.num_heads = num_heads
self.config = config
self.layer_idx = layer_idx
self.attention_dropout = config.attention_dropout
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
self.sliding_window = config.sliding_window if self.is_local_attention else None
self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
) -> torch.Tensor:
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
dropout_p = 0.0 if not self.training else self.attention_dropout
out = F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
dropout_p=dropout_p,
is_causal=attention_mask is None,
)
out = out.transpose(1, 2).contiguous()
return out.view(out.shape[0], out.shape[1], -1)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
attention_mask: torch.Tensor | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(query_states, key_states, value_states, attention_mask=attention_mask)
input_shape = hidden_states.shape[:-1]
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
return self.o_proj(attn_output), None
def _get_laguna_attention(config: LagunaConfig, layer_idx: int):
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
num_heads = config.num_attention_heads_per_layer[layer_idx]
match attn_impl:
case "flash_attention_2":
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=2)
case "flash_attention_3":
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=3)
case "fa4":
case "flash_attention_4":
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=4)
case "sdpa":
return LagunaSDPAAttention(config, layer_idx, num_heads)
case _:
raise ValueError(f"Laguna attention does not support '{config._attn_implementation}'.")
@@ -286,7 +232,7 @@ class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["LagunaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = False
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -354,7 +300,7 @@ class LagunaModel(LagunaPreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
causal_mask_mapping = dict.fromkeys(set(self.config.layer_types), None)
+3 -102
View File
@@ -3,7 +3,6 @@ from dataclasses import dataclass
from typing import Literal
import torch
import torch.nn.functional as F
from torch import nn
from .norms import RMSNorm, RMSNormConfig
@@ -42,7 +41,7 @@ class AttentionConfig:
# TODO: Does torch compile support config._attn_implementation forking?
# If so, we can combine FlashAttention and SDPAAttention into one class
# If so, we can combine FlashAttention variants into one class
# Otherwise, do ABC or something to make the signatures match
@@ -183,108 +182,10 @@ class FlashAttention(nn.Module):
return attn_output, None
class SDPAAttention(nn.Module):
"""SDPA Attention"""
def __init__(self, config: AttentionConfig):
super().__init__()
self.head_dim = config.head_dim
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.is_causal = config.is_causal
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
if self.use_qk_norm:
if self.qk_norm_type == "per_layer":
self.q_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
)
self.k_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
)
else:
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.view(hidden_shape)
key_states = key_states.view(hidden_shape)
value_states = value_states.view(hidden_shape)
if self.use_qk_norm and self.qk_norm_type == "per_head":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
if position_embeddings is not None:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
return query_states, key_states, value_states
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
) -> torch.Tensor:
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
out = F.scaled_dot_product_attention(query_states, key_states, value_states, is_causal=True)
out = out.transpose(1, 2).contiguous()
return out.view(out.shape[0], out.shape[1], -1)
def output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
return self.o_proj(attn_output)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(query_states, key_states, value_states)
attn_output = self.output_proj(attn_output)
return attn_output, None
ATTN_IMPL2CLASS = {
"flash_attention_2": functools.partial(FlashAttention, flash_attn_version=2),
"sdpa": SDPAAttention,
"flash_attention_3": functools.partial(FlashAttention, flash_attn_version=3),
"fa4": functools.partial(FlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(FlashAttention, flash_attn_version=4),
}
@@ -298,7 +199,7 @@ def substitute_ring_attn(
from .ring_attn import ring_fa3_varlen_func, ring_fa4_varlen_func
if attn_impl == "fa4":
if attn_impl == "flash_attention_4":
ring_func = ring_fa4_varlen_func
elif attn_impl == "flash_attention_3":
ring_func = ring_fa3_varlen_func
@@ -110,24 +110,7 @@ class Float8BlockwiseLinear(nn.Linear):
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:
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str]) -> None:
"""Replace nn.Linear in `model` with Float8BlockwiseLinear, skipping any
module whose qualified name matches an ignore pattern (substring or regex).
@@ -147,8 +130,6 @@ def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: l
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 = []
+5 -103
View File
@@ -10,8 +10,6 @@ from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
FUSED_CE_IGNORE_INDEX = -100
class PrimeLmOutput(TypedDict, total=False):
"""Output from LM head - a TypedDict so pytree can find tensors for FSDP2 hooks."""
@@ -75,78 +73,6 @@ class VanillaOutputLinear(torch.nn.Linear):
return PrimeLmOutput(logits=super().forward(hidden_states))
class FusedCrossEntropyOutputLinear(torch.nn.Linear):
"""Fused lm_head + cross-entropy loss using Liger kernel.
Avoids materializing the full [N, V] logits tensor by fusing the linear
projection with the cross-entropy loss computation.
"""
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
def __init__(self, in_features: int, out_features: int, softcap: float | None = None):
super().__init__(in_features, out_features, bias=False)
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
self.fused_ce = LigerFusedLinearCrossEntropyLoss(
ignore_index=self.IGNORE_INDEX, reduction="mean", softcap=softcap
)
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
) -> PrimeLmOutput:
if labels is None:
return PrimeLmOutput(logits=super().forward(hidden_states))
b, s, h = hidden_states.shape
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
labels_flat = labels.reshape(b * s).contiguous()
loss = self.fused_ce(self.weight, hidden_flat, labels_flat)
return PrimeLmOutput(loss=loss)
class QuackFusedCrossEntropyOutputLinear(torch.nn.Linear):
"""Fused lm_head + cross-entropy loss using quack-kernels.
Chunks the linear projection and cross-entropy computation to avoid
materializing the full [N, V] logits tensor, using quack's optimized
CuTe DSL kernels for CE and GEMM.
"""
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
def __init__(self, in_features: int, out_features: int, chunk_size: int = 4096):
super().__init__(in_features, out_features, bias=False)
self.chunk_size = chunk_size
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
) -> PrimeLmOutput:
if labels is None:
return PrimeLmOutput(logits=super().forward(hidden_states))
from quack.linear_cross_entropy import chunked_linear_cross_entropy
b, s, h = hidden_states.shape
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
labels_flat = labels.reshape(b * s).contiguous()
loss = chunked_linear_cross_entropy(
hidden_flat,
self.weight,
labels_flat,
chunk_size=self.chunk_size,
ignore_index=self.IGNORE_INDEX,
reduction="mean",
)
return PrimeLmOutput(loss=loss)
def _online_logsumexp_and_weighted_update(
m: torch.Tensor, s: torch.Tensor, t: torch.Tensor, chunk_logits: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
@@ -275,7 +201,6 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
def inject_prime_lm_head(
model: nn.Module,
chunk_size: int | None = None,
fused_cross_entropy: bool | str = False,
) -> None:
"""
Inject a PrimeRL LM head into a model.
@@ -286,11 +211,7 @@ def inject_prime_lm_head(
Args:
model: The model to wrap.
chunk_size: When set to an int, uses FusedOutputLinear with sequence-token chunked
logprob/entropy computation (for RL).
fused_cross_entropy: Controls fused lm_head + CE loss. Accepts:
- False: no fusion
- True or "liger": Liger kernel fusion
- "quack": quack-kernels fusion (chunked linear + CE with CuTe DSL kernels)
logprob/entropy computation.
"""
# Guards so we have nicer error messages when a non-standard model is used
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
@@ -306,33 +227,14 @@ def inject_prime_lm_head(
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
if fused_cross_entropy == "quack":
raise ValueError(
"quack_fused does not support Gemma logit softcapping. "
"Use loss_impl='liger_fused' or loss_impl='torch' instead."
)
if not fused_cross_entropy:
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
return
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
return
# Replace the lm_head with the appropriate wrapper
old_lm_head = model.lm_head
if fused_cross_entropy == "quack":
logger.info("Injecting fused cross-entropy LM head (quack-kernels)")
model.lm_head = QuackFusedCrossEntropyOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
)
elif fused_cross_entropy:
logger.info("Injecting fused cross-entropy LM head (Liger kernel)")
model.lm_head = FusedCrossEntropyOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
softcap=final_logit_softcapping,
)
elif isinstance(chunk_size, int):
if isinstance(chunk_size, int):
logger.info(f"Injecting chunked LM head with chunk size {chunk_size}")
model.lm_head = FusedOutputLinear(
in_features=old_lm_head.in_features, out_features=old_lm_head.out_features, chunk_size=chunk_size
@@ -798,6 +798,7 @@ class MoE(nn.Module):
self.expert_bias = torch.zeros(self.experts.num_experts, dtype=torch.float32)
@torch.compile(dynamic=True)
def relu2(x: torch.Tensor) -> torch.Tensor:
return F.relu(x).square()
@@ -0,0 +1,88 @@
from __future__ import annotations
import torch
from torch import nn
from torchao.prototype.moe_training import conversion_utils as cu
from torchao.prototype.moe_training import mxfp8_grouped_mm as tao_mxfp8_gmm
from torchao.prototype.moe_training.config import MXFP8TrainingOpConfig, MXFP8TrainingRecipe
from torchao.prototype.moe_training.kernels.mxfp8 import triton_mx_block_rearrange_2d_M_groups
from torchao.prototype.moe_training.tensor import MXFP8TrainingWeightWrapperTensor
from torchao.quantization.quant_api import quantize_
from torchtitan.distributed.expert_parallel import set_token_group_alignment_size_m
from torchtitan.experiments.kernels.moe import indices as tt_indices
from prime_rl.configs.trainer import MXFP8Recipe
from prime_rl.trainer.models.layers.moe import GroupedExperts, NonGatedGroupedExperts
from prime_rl.utils.logger import get_logger
_MXFP8_TOKEN_GROUP_ALIGN: int = 32
# torchao CUDA scale rearrange kernel supports at most 32 token groups,
# the Triton variant has no such cap and produces the same swizzled layout, so fall back to it for wider MoEs
_CUDA_REARRANGE_MAX_GROUPS: int = 32
def _fallback_to_triton_rearrange_for_wide_moes() -> None:
if getattr(tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda, "_prime_rl_wide_moe", False):
return
original = tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda
def mx_block_rearrange_2d_M_groups(
scales_tensor: torch.Tensor, input_group_end_offsets: torch.Tensor, chunks_per_tb: int = 4
) -> torch.Tensor:
if input_group_end_offsets.shape[0] > _CUDA_REARRANGE_MAX_GROUPS:
return triton_mx_block_rearrange_2d_M_groups(scales_tensor, input_group_end_offsets)
return original(scales_tensor, input_group_end_offsets, chunks_per_tb)
mx_block_rearrange_2d_M_groups._prime_rl_wide_moe = True
tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda = mx_block_rearrange_2d_M_groups
def _relax_torchao_mxfp8_version_gate() -> None:
if getattr(cu._get_tensor_cls_for_config, "_prime_rl_relaxed", False):
return
original = cu._get_tensor_cls_for_config
def _get_tensor_cls_for_config(config):
if isinstance(config, MXFP8TrainingOpConfig):
return MXFP8TrainingWeightWrapperTensor
return original(config)
_get_tensor_cls_for_config._prime_rl_relaxed = True
cu._get_tensor_cls_for_config = _get_tensor_cls_for_config
def _align_permute_indices_buffer() -> None:
"""
Align the permuted index buffer to a multiple of alignment as the kernel requires rows % 32 = 0 and cols % 32 = 0.
"""
if getattr(tt_indices.generate_permute_indices, "_prime_rl_aligned", False):
return
original = tt_indices.generate_permute_indices
def generate_permute_indices(
tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=False
):
al_mask = alignment - 1
assert alignment > 0 and (alignment & al_mask) == 0
max_len = (max_len + al_mask) & ~al_mask
return original(tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=use_cpu)
generate_permute_indices._prime_rl_aligned = True
tt_indices.generate_permute_indices = generate_permute_indices
def apply_mxfp8_moe_grouped_gemm(model: nn.Module, recipe: MXFP8Recipe) -> None:
_relax_torchao_mxfp8_version_gate()
_align_permute_indices_buffer()
_fallback_to_triton_rearrange_for_wide_moes()
set_token_group_alignment_size_m(_MXFP8_TOKEN_GROUP_ALIGN)
op_config = MXFP8TrainingOpConfig.from_recipe(MXFP8TrainingRecipe(recipe))
def filter_fn(module: nn.Module, fqn: str) -> bool:
return isinstance(module, (GroupedExperts, NonGatedGroupedExperts))
quantize_(model, config=op_config, filter_fn=filter_fn)
get_logger().info(
f"Wrapped MoE expert weights with MXFP8 grouped GEMM (recipe={recipe}, "
f"token_group_align={_MXFP8_TOKEN_GROUP_ALIGN})"
)
@@ -0,0 +1,99 @@
from __future__ import annotations
import re
import torch
from torch import nn
from torchao.prototype.mx_formats import ScaleCalculationMode
from torchao.prototype.mx_formats.mx_linear import _to_mxfp8_then_scaled_mm
from torchao.quantization.quantize_.common import KernelPreference
from prime_rl.configs.trainer import MXFP8Recipe
from prime_rl.utils.logger import get_logger
class MXFP8Linear(nn.Linear):
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
*,
kernel_preference: KernelPreference = KernelPreference.AUTO,
wgrad_with_hp: bool = False,
scale_calculation_mode: ScaleCalculationMode = ScaleCalculationMode.RCEIL,
device=None,
dtype=None,
) -> None:
super().__init__(in_features, out_features, bias, device=device, dtype=dtype)
self.kernel_preference = kernel_preference
self.wgrad_with_hp = wgrad_with_hp
self.scale_calculation_mode = scale_calculation_mode
def forward(self, input: torch.Tensor) -> torch.Tensor:
output = _to_mxfp8_then_scaled_mm(
input,
self.weight,
self.kernel_preference,
self.scale_calculation_mode,
wgrad_with_hp=self.wgrad_with_hp,
)
if self.bias is not None:
output = output + self.bias
return output
@classmethod
def from_linear(
cls,
mod: nn.Linear,
*,
kernel_preference: KernelPreference = KernelPreference.AUTO,
wgrad_with_hp: bool = False,
scale_calculation_mode: ScaleCalculationMode = ScaleCalculationMode.RCEIL,
) -> "MXFP8Linear":
with torch.device("meta"):
new_mod = cls(
mod.in_features,
mod.out_features,
bias=mod.bias is not None,
kernel_preference=kernel_preference,
wgrad_with_hp=wgrad_with_hp,
scale_calculation_mode=scale_calculation_mode,
)
new_mod.weight = mod.weight
new_mod.bias = mod.bias
return new_mod
def replace_linear_with_mxfp8_linear(model: nn.Module, recipe: MXFP8Recipe, ignore_modules: list[str]) -> None:
wgrad_with_hp = recipe == "mxfp8_rceil_wgrad_with_hp"
logger = get_logger()
logger.info(f"Replacing linear layers with MXFP8 linear layers (recipe={recipe}, ignore={ignore_modules})")
replaced_modules: list[str] = []
skipped_modules: list[str] = []
skipped_unaligned: list[str] = []
for name, module in dict(model.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 & 31) != 0 or (module.out_features & 31) != 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,
MXFP8Linear.from_linear(module, kernel_preference=KernelPreference.AUTO, wgrad_with_hp=wgrad_with_hp),
)
replaced_modules.append(name)
logger.info(
f"Replaced {len(replaced_modules)} linear layers with MXFP8 linear "
f"(skipped {len(skipped_modules)} by name, {len(skipped_unaligned)} by 32-div); "
f"first replaced={replaced_modules[:3]}, "
f"first skipped(name)={skipped_modules[:3]}, "
f"first skipped(unaligned)={skipped_unaligned[:3]}"
)
@@ -19,8 +19,17 @@ 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.
GQA models with fewer KV heads than cp_size (e.g. NemotronH: 32 query heads, 2
KV heads) are handled by replicating each KV head cp_size / num_key_value_heads
times before the seq->head all-to-all. Query heads are grouped contiguously in
GQA, so the replicated layout lands every rank on exactly the KV head its local
query-head slice attends to; the backward of the replication sums gradients
over replicas, which is the exact GQA KV gradient.
Constraints:
- cp_size must divide both num_attention_heads and num_key_value_heads.
- cp_size must divide num_attention_heads.
- cp_size must divide num_key_value_heads, OR num_key_value_heads must divide
cp_size (the KV-replication path).
- Sequence length must be divisible by cp_size.
"""
@@ -41,6 +50,24 @@ def update_ulysses_params(cu_seqlens: torch.Tensor, max_seqlen: int) -> None:
ULYSSES_PARAMS["max_seqlen"] = int(max_seqlen)
def _replicate_kv_heads(t: torch.Tensor, cp_size: int) -> torch.Tensor:
"""Replicate KV heads so a GQA tensor with fewer heads than cp_size can be
head-sharded: [S_local, H_kv, D] -> [S_local, cp_size, D].
Each KV head is repeated cp_size / H_kv times. GQA groups query heads
contiguously (query head j attends KV head j // (H_q / H_kv)), so after the
seq->head all-to-all rank r holds query heads [r * H_q/cp, (r+1) * H_q/cp)
— all attending KV head floor(r * H_kv / cp) — and replica index r maps to
the same head: floor(r / (cp / H_kv)). The backward sums gradients over
replicas, which is exactly the GQA KV gradient.
"""
s_local, h, d = t.shape
assert cp_size % h == 0, (
f"num_key_value_heads ({h}) must divide cp_size ({cp_size}) for the ulysses KV-replication path"
)
return t.repeat_interleave(cp_size // h, dim=1)
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].
@@ -48,7 +75,10 @@ def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
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})"
assert h % cp_size == 0, (
f"num_heads ({h}) must be divisible by cp_size ({cp_size}); "
"for GQA KV tensors with fewer heads than cp_size, replicate first via _replicate_kv_heads"
)
h_local = h // cp_size
# [S_local, cp_size, H_local, D] -> [cp_size, S_local, H_local, D]
@@ -96,8 +126,15 @@ def ulysses_flash_attn_varlen_func(
`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.
GQA with num_key_value_heads < cp_size: K/V heads are replicated up to
cp_size before the all-to-all (see `_replicate_kv_heads`), so each rank runs
grouped attention on its query-head slice with the single matching KV head.
"""
q = _all_to_all_seq_to_head(q, cp_size, cp_group)
if k.shape[1] < cp_size:
k = _replicate_kv_heads(k, cp_size)
v = _replicate_kv_heads(v, cp_size)
k = _all_to_all_seq_to_head(k, cp_size, cp_group)
v = _all_to_all_seq_to_head(v, cp_size, cp_group)
@@ -136,7 +173,7 @@ def substitute_ulysses_attn(
cp_size = dist.get_world_size(group=process_group)
# Resolve flash kernel + version from attn_impl.
if attn_impl == "fa4":
if attn_impl == "flash_attention_4":
from flash_attn.cute import flash_attn_varlen_func as flash_fn
flash_attn_version = 4
@@ -107,7 +107,7 @@ class LlamaPreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["LlamaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = True
@@ -188,7 +188,7 @@ class LlamaModel(LlamaPreTrainedModel):
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -95,7 +95,7 @@ class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["MiniMaxM2DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -177,7 +177,7 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -342,7 +342,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
supports_gradient_checkpointing = True
_no_split_modules = ["NemotronHMambaLayer", "NemotronHMoELayer", "NemotronHAttentionLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_can_compile_fullgraph = False
def _init_weights(self, module):
@@ -522,7 +522,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
inputs_embeds = self.embed_tokens(input_ids)
# Compute cu_seqlens and max_seqlen for flash attention
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -50,8 +50,6 @@ class Qwen3DecoderLayer(GradientCheckpointingLayer):
)
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
if self.layer_type == "sliding_attention":
if config._attn_implementation == "sdpa":
raise ValueError("Qwen3 sliding attention is only supported by the custom model with flash attention.")
self.self_attn.sliding_window = config.sliding_window
mlp_config = MLPConfig(
@@ -95,7 +93,7 @@ class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Qwen3DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = True
_supports_attention_backend = True
@@ -165,7 +163,7 @@ class Qwen3Model(Qwen3PreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -21,7 +21,6 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeGatedAttentionConfig,
Qwen3_5MoeGatedDeltaNet,
Qwen3_5MoeGatedFlashAttention,
Qwen3_5MoeGatedSDPAAttention,
Qwen3_5MoeRMSNorm,
Qwen3_5MoeRotaryEmbedding,
normalize_qwen3_5_attn_implementation,
@@ -29,19 +28,14 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
class Qwen3_5GatedSDPAAttention(Qwen3_5MoeGatedSDPAAttention):
pass
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
pass
QWEN35_ATTN_IMPL2CLASS = {
"sdpa": Qwen3_5GatedSDPAAttention,
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
"fa4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
}
@@ -130,7 +124,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
_no_split_modules = ["Qwen3_5DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
@@ -141,7 +135,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "flash_attention_3")
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
raise ValueError(
@@ -206,7 +200,11 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
flash_attn_enabled = self.config._attn_implementation in (
"flash_attention_2",
"flash_attention_3",
"flash_attention_4",
)
if flash_attn_enabled:
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -4,6 +4,10 @@ from typing import Optional, Union
import torch
import torch.nn.functional as F
from fla.modules import FusedRMSNormGated
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.cp import FLACPContext, build_cp_context
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.configuration_utils import PretrainedConfig
@@ -36,24 +40,6 @@ from .converting_qwen3_5_moe import (
)
from .mrope import build_qwen3_5_mrope_position_ids
# Flash linear attention imports (for GatedDeltaNet fast path)
try:
from causal_conv1d import causal_conv1d_fn
except ImportError:
causal_conv1d_fn = None # type: ignore
try:
from fla.modules import FusedRMSNormGated
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.cp import FLACPContext, build_cp_context
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
except ImportError:
chunk_gated_delta_rule = None # type: ignore
FusedRMSNormGated = None # type: ignore
FLACPContext = None # type: ignore
build_cp_context = None # type: ignore
fla_causal_conv1d = None # type: ignore
logger = logging.get_logger(__name__)
@@ -79,112 +65,11 @@ class Qwen3_5MoeRMSNorm(nn.Module):
return output.type_as(x)
class Qwen3_5MoeRMSNormGated(nn.Module):
"""RMSNorm with SiLU gating for GatedDeltaNet output."""
def __init__(self, hidden_size, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states, gate=None):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
hidden_states = self.weight * hidden_states.to(input_dtype)
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
return hidden_states.to(input_dtype)
# ---------------------------------------------------------------------------
# GatedDeltaNet linear attention
# ---------------------------------------------------------------------------
def l2norm(x: torch.FloatTensor, dim: int = -1, eps: float = 1e-6):
inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
return x * inv_norm
def torch_chunk_gated_delta_rule(
query,
key,
value,
g,
beta,
chunk_size=64,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=False,
):
"""Pure-PyTorch fallback for chunk_gated_delta_rule."""
initial_dtype = query.dtype
if use_qk_l2norm_in_kernel:
query = l2norm(query, dim=-1, eps=1e-6)
key = l2norm(key, dim=-1, eps=1e-6)
query, key, value, beta, g = [
x.transpose(1, 2).contiguous().to(torch.float32) for x in (query, key, value, beta, g)
]
batch_size, num_heads, sequence_length, k_head_dim = key.shape
v_head_dim = value.shape[-1]
pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size
query = F.pad(query, (0, 0, 0, pad_size))
key = F.pad(key, (0, 0, 0, pad_size))
value = F.pad(value, (0, 0, 0, pad_size))
beta = F.pad(beta, (0, pad_size))
g = F.pad(g, (0, pad_size))
total_sequence_length = sequence_length + pad_size
scale = 1 / (query.shape[-1] ** 0.5)
query = query * scale
v_beta = value * beta.unsqueeze(-1)
k_beta = key * beta.unsqueeze(-1)
query, key, value, k_beta, v_beta = [
x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
]
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
g = g.cumsum(dim=-1)
decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
for i in range(1, chunk_size):
row = attn[..., i, :i].clone()
sub = attn[..., :i, :i].clone()
attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
value = attn @ v_beta
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
last_recurrent_state = (
torch.zeros(batch_size, num_heads, k_head_dim, v_head_dim).to(value)
if initial_state is None
else initial_state.to(value)
)
core_attn_out = torch.zeros_like(value)
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=1)
for i in range(0, total_sequence_length // chunk_size):
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
attn = (q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]).masked_fill_(mask, 0)
v_prime = (k_cumdecay[:, :, i]) @ last_recurrent_state
v_new = v_i - v_prime
attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state
core_attn_out[:, :, i] = attn_inter + attn @ v_new
last_recurrent_state = (
last_recurrent_state * g[:, :, i, -1, None, None].exp()
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
)
if not output_final_state:
last_recurrent_state = None
core_attn_out = core_attn_out.reshape(core_attn_out.shape[0], core_attn_out.shape[1], -1, core_attn_out.shape[-1])
core_attn_out = core_attn_out[:, :, :sequence_length]
core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
return core_attn_out, last_recurrent_state
class Qwen3_5MoeGatedDeltaNet(nn.Module):
"""GatedDeltaNet linear attention with Conv1d, beta/gamma gates, and chunk delta rule."""
@@ -218,11 +103,7 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
A = torch.empty(self.num_v_heads).uniform_(0, 16)
self.A_log = nn.Parameter(torch.log(A))
# Gated RMSNorm on output (per-head)
if FusedRMSNormGated is not None:
self.norm = FusedRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
else:
self.norm = Qwen3_5MoeRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
self.norm = FusedRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
@@ -232,14 +113,10 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
# Select best available kernel
self._causal_conv1d_fn = causal_conv1d_fn
self._chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
def _build_cp_context(self) -> "FLACPContext | None":
"""Build fla CP context from the full pre-shard document boundaries."""
cp_group = getattr(self, "cp_group", None)
if cp_group is None or build_cp_context is None:
if cp_group is None:
return None
# Local cu_seqlens cannot describe documents straddling shard boundaries;
# use the full (un-sharded) cu_seqlens published by setup_cp_params. fla
@@ -266,46 +143,14 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
# Causal conv1d — must reset at sequence boundaries for packed batches,
# otherwise the kernel-1 left pad leaks state across sequences.
if cp_context is not None:
# fla's CP conv resets at the true document boundaries and exchanges
# tail tokens with the previous rank for documents straddling the
# shard boundary; the local cu_seqlens can express neither.
conv_out, _ = fla_causal_conv1d(
x=mixed_qkv.transpose(1, 2),
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cp_context=cp_context,
)
mixed_qkv = conv_out.transpose(1, 2)
elif self._causal_conv1d_fn is not None:
seq_idx = None
if cu_seqlens is not None:
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
seq_idx = torch.repeat_interleave(
torch.arange(seg_lens.numel(), dtype=torch.int32, device=hidden_states.device),
seg_lens,
).unsqueeze(0)
mixed_qkv = self._causal_conv1d_fn(
x=mixed_qkv,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
seq_idx=seq_idx,
)
elif cu_seqlens is not None:
cu = cu_seqlens.tolist()
conv_outs = []
for i in range(len(cu) - 1):
s, e = cu[i], cu[i + 1]
if s == e:
continue
conv_outs.append(self.conv1d(mixed_qkv[:, :, s:e])[:, :, : e - s])
mixed_qkv = F.silu(torch.cat(conv_outs, dim=-1))
else:
mixed_qkv = F.silu(self.conv1d(mixed_qkv)[:, :, :seq_len])
mixed_qkv = mixed_qkv.transpose(1, 2)
mixed_qkv, _ = fla_causal_conv1d(
x=mixed_qkv.transpose(1, 2),
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cu_seqlens=cu_seqlens if cp_context is None else None,
cp_context=cp_context,
)
query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
@@ -319,10 +164,9 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
# Use fla's native CP when available, otherwise fall back to PyTorch kernel
if cp_context is not None:
cu_seqlens = cp_context.cu_seqlens
core_attn_out, _ = self._chunk_gated_delta_rule(
core_attn_out, _ = chunk_gated_delta_rule(
query,
key,
value,
@@ -333,7 +177,7 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
cp_context=cp_context,
)
else:
core_attn_out, _ = self._chunk_gated_delta_rule(
core_attn_out, _ = chunk_gated_delta_rule(
query,
key,
value,
@@ -417,59 +261,6 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
return self.o_proj(attn_output)
class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using PyTorch's scaled_dot_product_attention."""
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
return query_states, key_states, value_states, gate
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
) -> torch.Tensor:
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
return F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
is_causal=True,
scale=self.scaling,
)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(query_states, key_states, value_states)
return self.output_proj(attn_output, gate), None
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using Flash Attention varlen functions."""
@@ -560,16 +351,13 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
QWEN35MOE_ATTN_IMPL2CLASS = {
"sdpa": Qwen3_5MoeGatedSDPAAttention,
"flash_attention_2": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=3),
"fa4": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=4),
}
def normalize_qwen3_5_attn_implementation(attn_impl: str) -> str:
if attn_impl == "eager":
return "sdpa"
if attn_impl == "kernels-community/vllm-flash-attn3":
return "flash_attention_3"
return attn_impl
@@ -798,7 +586,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Qwen3_5MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
@@ -809,7 +597,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "flash_attention_3")
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
raise ValueError(
@@ -885,7 +673,11 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
flash_attn_enabled = self.config._attn_implementation in (
"flash_attention_2",
"flash_attention_3",
"flash_attention_4",
)
if flash_attn_enabled:
if position_ids.ndim == 3:
if inputs_embeds.shape[0] != 1:
@@ -127,7 +127,7 @@ class Qwen3MoePreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Qwen3MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
_supports_attention_backend = True
@@ -217,7 +217,7 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
+9 -21
View File
@@ -51,8 +51,6 @@ from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, to_col_format
import torch.distributed as dist
from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss
from prime_rl.trainer.models.layers.lm_head import FUSED_CE_IGNORE_INDEX
from torchtitan.distributed.utils import clip_grad_norm_
@@ -138,8 +136,7 @@ def train(config: SFTConfig):
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
loading_from_ckpt_later = config.ckpt and checkpoint_step is not None
fused_cross_entropy: bool | str = {"liger_fused": "liger", "quack_fused": "quack"}.get(config.loss_impl, False)
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=fused_cross_entropy)
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
if parallel_dims.cp_enabled:
from prime_rl.utils.cp import assert_cp_style_supports_model
@@ -225,17 +222,6 @@ def train(config: SFTConfig):
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
cp_size = parallel_dims.cp
ce_loss = None
match config.loss_impl:
case "liger":
ce_loss = LigerCrossEntropyLoss(reduction="none")
case "torch":
ce_loss = CrossEntropyLoss(reduction="none")
case "liger_fused" | "quack_fused":
pass # loss is computed inside the fused lm_head
case _:
raise ValueError(f"Invalid loss implementation: {config.loss_impl}")
def compute_loss(micro_batch: dict) -> tuple[torch.Tensor, torch.Tensor]:
"""Forward pass returning (loss_sum, token_count) over unmasked tokens."""
input_ids = micro_batch["input_ids"].to("cuda")
@@ -256,16 +242,18 @@ def train(config: SFTConfig):
token_count = loss_mask.sum(dtype=torch.int64)
with maybe_activation_offloading(config.model.ac_offloading):
if config.loss_impl in ("liger_fused", "quack_fused"):
masked_target_ids = target_ids.clone()
masked_target_ids[~loss_mask] = FUSED_CE_IGNORE_INDEX
out = forward(model, input_ids, position_ids, labels=masked_target_ids)
loss_sum = out["loss"] * token_count
if isinstance(config.model.fused_lm_head_token_chunk_size, int):
# Same path as the RL trainer: the chunked LM head computes per-token
# logprobs without materializing the [N, V] logits, and per-token
# cross-entropy is the negative target logprob.
temperature = torch.ones_like(target_ids, dtype=torch.float32)
out = forward(model, input_ids, position_ids, labels=target_ids, temperature=temperature)
loss_sum = -out["logprobs"][loss_mask].sum()
else:
out = forward(model, input_ids, position_ids)
logits = out["logits"]
B, L, V = logits.shape
token_loss = ce_loss(logits.view(-1, V), target_ids.view(-1)).view(B, L)
token_loss = CrossEntropyLoss(reduction="none")(logits.view(-1, V), target_ids.view(-1)).view(B, L)
loss_sum = token_loss[loss_mask].sum()
del logits
@@ -55,8 +55,15 @@ def _build_rollout(
)
parent = len(nodes) - 1
# Trace token counts are usage-based, so carry provider usage on the final sampled turn:
# every model-generated token as completion, the leading prompt + tool observations as the
# fed-in context (num_input_tokens = num_total_tokens - num_output_tokens).
output_tokens = sum(sampled_lengths)
input_tokens = 1 + sum(obs_lengths)
for i, n_sampled in enumerate(sampled_lengths):
ids = _take(n_sampled)
is_last = i == len(sampled_lengths) - 1
nodes.append(
vf.MessageNode(
message=vf.AssistantMessage(content="a"),
@@ -65,6 +72,7 @@ def _build_rollout(
logprobs=[-0.1] * n_sampled,
sampled=True,
parent=parent,
usage=vf.Usage(prompt_tokens=input_tokens, completion_tokens=output_tokens) if is_last else None,
)
)
parent = len(nodes) - 1
+1 -1
View File
@@ -56,7 +56,7 @@ def get_model_pairs():
use_grouped_mm=False,
vocab_size=256,
)
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_config)
+1 -1
View File
@@ -32,7 +32,7 @@ def get_model_pairs() -> tuple[HFGlm4MoeForCausalLM, PrimeRLGlm4MoeForCausalLM]:
# TODO: We should test this path because it's the most performant
# But the grad seems to be off in attn because of precision
# hf_config._attn_implementation = "flash_attention_2"
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFGlm4MoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLGlm4MoeForCausalLM._from_config(hf_config)
+1 -1
View File
@@ -25,7 +25,7 @@ def get_model_pairs():
attention_bias=False,
mlp_bias=False,
)
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFLlamaForCausalLM._from_config(hf_config)
prime_model = PrimeRLLlamaForCausalLM._from_config(hf_config)
+4 -4
View File
@@ -47,14 +47,14 @@ _BASE = dict(
def get_model_pairs():
"""Create an HF model and a PrimeRL model with shared weights."""
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
prime_config = NemotronHConfig(
**_BASE,
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
prime_config._attn_implementation = "sdpa"
prime_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFNemotronHForCausalLM._from_config(hf_config)
@@ -110,10 +110,10 @@ def test_nemotron_h_reverse():
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
prime_config._attn_implementation = "sdpa"
prime_config._attn_implementation = "flash_attention_2"
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
prime_model = NemotronHForCausalLM._from_config(prime_config)
@@ -55,7 +55,7 @@ def _make_model(device="cuda"):
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
config._attn_implementation = "flash_attention_2"
with torch.device(device), default_dtype(torch.float32):
model = NemotronHForCausalLM._from_config(config)
inject_prime_lm_head(model, chunk_size=None)
@@ -186,7 +186,7 @@ def test_kl_with_fused_lm_head():
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
model = NemotronHForCausalLM._from_config(config)
+3 -2
View File
@@ -12,7 +12,7 @@ from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAt
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig:
config = Qwen3_5TextConfig(
vocab_size=128,
hidden_size=64,
@@ -33,7 +33,7 @@ def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
return config
def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
def _tiny_moe_config(attn_impl: str = "flash_attention_2") -> Qwen3_5MoeConfig:
config = Qwen3_5MoeConfig(
vocab_size=128,
hidden_size=64,
@@ -58,6 +58,7 @@ def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
return config
@pytest.mark.gpu
def test_qwen3_5_dense_matches_hf_state_keys_on_meta():
config = _tiny_text_config()
with torch.device("meta"):
+1 -1
View File
@@ -31,7 +31,7 @@ def get_model_pairs():
linear_num_value_heads=8,
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeForCausalLM._from_config(config)
prime_model = PrimeRLQwen3_5MoeForCausalLM._from_config(config)
@@ -15,7 +15,9 @@ pytestmark = [pytest.mark.gpu]
def _tiny_vlm_config():
"""HF composite config shrunk for unit testing."""
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
config = AutoConfig.from_pretrained(
"Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="flash_attention_2"
)
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
+1 -1
View File
@@ -31,7 +31,7 @@ def get_model_pairs():
# TODO: We should test this path because it's the most performant
# But the grad seems to be off in attn because of precision
# hf_config._attn_implementation = "flash_attention_2"
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3MoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLQwen3MoeForCausalLM._from_config(hf_config)
+5 -3
View File
@@ -14,7 +14,7 @@ pytestmark = [
]
@pytest.fixture(params=["sdpa", "flash_attention_2"])
@pytest.fixture(params=["flash_attention_2"])
def attn(request) -> AttnImplementation:
"""
Fixture to test different attention implementations.
@@ -117,7 +117,9 @@ def test_model_with_sequence_packing(model, correct_position_ids):
def test_moe_custom_impl():
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="sdpa", impl="custom", moe_use_grouped_mm=False)
config = ModelConfig(
name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2", impl="custom", moe_use_grouped_mm=False
)
model = get_model(config)
model = model.to("cuda")
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
@@ -133,7 +135,7 @@ def test_moe_custom_impl():
@pytest.mark.skip(reason="need special token for meta stuff in ci")
@pytest.mark.parametrize("model_name", ["meta-llama/Llama-3.2-1B-Instruct"])
def test_model_forward_custom_impl(model_name):
config = ModelConfig(name=model_name, impl="custom", attn="sdpa")
config = ModelConfig(name=model_name, impl="custom", attn="flash_attention_2")
model = get_model(config)
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
inject_prime_lm_head(model, chunk_size=None)
Generated
+159 -20
View File
@@ -26,6 +26,7 @@ flash-attn-3 = false
prime-tunnel = false
deep-gemm = false
prime-evals = false
torchao = false
tokenspeed-mla = false
deep-ep = false
prime-sandboxes = false
@@ -41,7 +42,9 @@ members = [
"alphabet-sort-v1",
"apex-shortlist-v1",
"arxivmath-v1",
"automationbench-v1",
"bfcl-v3-v1",
"browsecomp-plus-v1",
"browsecomp-v1",
"browser-cua-example",
"browser-dom-example",
@@ -107,6 +110,7 @@ members = [
"scicode-v1",
"scratchpad-v1",
"self-reward",
"senior-swe-bench-v1",
"sentence-repeater",
"simpleqa-v1",
"simpleqa-verified-v1",
@@ -457,6 +461,40 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" },
]
[[package]]
name = "automation-bench"
version = "1.0.5"
source = { git = "https://github.com/mikasenghaas/AutomationBench.git?rev=6f0e683#6f0e6834930cf6906ed932e9c5b716206def40d7" }
dependencies = [
{ name = "anthropic" },
{ name = "httpx" },
{ name = "pydantic" },
{ name = "python-dotenv" },
{ name = "rich" },
{ name = "verifiers" },
]
[[package]]
name = "automationbench-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/tool_use/automationbench_v1" }
dependencies = [
{ name = "automation-bench" },
{ name = "datasets" },
{ name = "mcp" },
{ name = "openai" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "automation-bench", git = "https://github.com/mikasenghaas/AutomationBench.git?rev=6f0e683" },
{ name = "datasets" },
{ name = "mcp", specifier = "<2" },
{ name = "openai" },
{ name = "verifiers", specifier = ">=0.2.1.dev42" },
]
[[package]]
name = "backoff"
version = "2.2.1"
@@ -634,6 +672,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1e/e2/0e93b865f648b5519360846669a35f28ee8f4e1d93d054f6850d8afbabde/blis-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8177879fd3590b5eecdd377f9deafb5dc8af6d684f065bd01553302fb3fcf9a7", size = 14250939, upload-time = "2025-11-17T12:27:53.847Z" },
]
[[package]]
name = "bm25s"
version = "0.3.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "numpy" },
]
sdist = { url = "https://files.pythonhosted.org/packages/7c/ab/39d08d4589dad6f5735a6b03ee083088dc37fba57fa45d4a0749393b9295/bm25s-0.3.9.tar.gz", hash = "sha256:895c679d952b7de8355edb5f3e1a620a1e2f294d1d42b919bf0821cce2e2f597", size = 80528, upload-time = "2026-05-13T23:08:20.952Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/48/83/06582913e2af0cf498cc478350070490b019c6f6b523cb8b6cfafd32f009/bm25s-0.3.9-py3-none-any.whl", hash = "sha256:db997475e82c9e81262b83fefe6a71304f2fdd0dafd037c8929828865fa6d465", size = 74475, upload-time = "2026-05-13T23:08:19.557Z" },
]
[[package]]
name = "boto3"
version = "1.43.40"
@@ -662,6 +712,31 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/dc/8c/5f7e73fd66b28f0705bc55d7060d41ef72328b656b86ca53e75765b3ba2c/botocore-1.43.40-py3-none-any.whl", hash = "sha256:0bc9d352267c9e48415c5d7bb61ff05c3f193eac2fc7e69cfd229a05fbab67d6", size = 15323870, upload-time = "2026-07-03T00:28:12.56Z" },
]
[[package]]
name = "browsecomp-plus-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/search/browsecomp_plus_v1" }
dependencies = [
{ name = "bm25s" },
{ name = "datasets" },
{ name = "mcp" },
{ name = "openai" },
{ name = "pystemmer" },
{ name = "tokenizers" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "bm25s", specifier = ">=0.2.0" },
{ name = "datasets" },
{ name = "mcp", specifier = ">=1,<2" },
{ name = "openai" },
{ name = "pystemmer" },
{ name = "tokenizers" },
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "browsecomp-v1"
version = "0.1.0"
@@ -3001,19 +3076,6 @@ requires-dist = [
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "liger-kernel"
version = "0.8.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "torch" },
{ name = "triton" },
]
sdist = { url = "https://files.pythonhosted.org/packages/41/d6/85f032b40fc30c969e817f9f3527f987b508171b46d9958befd0868855fd/liger_kernel-0.8.0.tar.gz", hash = "sha256:f98b94faf018814a0757e7b72bb8ebaaf12a78782cd09b157732acca2791e72c", size = 3989670, upload-time = "2026-04-30T23:02:15.183Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/7c/6b/eb29b56f128a819e2cded552e293212c57daa949481206b82490b207deac/liger_kernel-0.8.0-py3-none-any.whl", hash = "sha256:e1f03eeb4ba6a6a413d585dacf92c4c15d164bab5844fa4ead2fede6bcac469c", size = 403120, upload-time = "2026-04-30T23:02:13.443Z" },
]
[[package]]
name = "linkify-it-py"
version = "2.1.0"
@@ -4853,7 +4915,6 @@ dependencies = [
{ name = "dion" },
{ name = "flash-linear-attention" },
{ name = "jaxtyping" },
{ name = "liger-kernel" },
{ name = "loguru" },
{ name = "mooncake-transfer-engine" },
{ name = "msgspec" },
@@ -4875,6 +4936,8 @@ dependencies = [
{ name = "tenacity" },
{ name = "tilelang" },
{ name = "torch" },
{ name = "torchao", version = "0.17.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64'" },
{ name = "torchao", version = "0.17.0+git02105d46c", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "torchaudio" },
{ name = "torchdata" },
{ name = "torchtitan" },
@@ -4890,8 +4953,8 @@ dependencies = [
[package.optional-dependencies]
all = [
{ name = "deep-ep", version = "1.1.0+1fd57b0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine == 'aarch64' and sys_platform == 'linux'" },
{ name = "deep-ep", version = "1.2.1+29d31c0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "deep-ep", version = "1.1.0+1fd57b0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
{ name = "deep-ep", version = "1.2.1+29d31c0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "flash-attn", marker = "platform_machine == 'x86_64'" },
@@ -4904,8 +4967,8 @@ all = [
{ name = "vllm-router", version = "0.1.26", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
]
disagg = [
{ name = "deep-ep", version = "1.1.0+1fd57b0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine == 'aarch64' and sys_platform == 'linux'" },
{ name = "deep-ep", version = "1.2.1+29d31c0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "deep-ep", version = "1.1.0+1fd57b0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
{ name = "deep-ep", version = "1.2.1+29d31c0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "nixl" },
@@ -4962,7 +5025,6 @@ requires-dist = [
{ name = "flash-linear-attention", git = "https://github.com/fla-org/flash-linear-attention" },
{ name = "jaxtyping", specifier = ">=0.3.2" },
{ name = "kernels", marker = "extra == 'gpt-oss'" },
{ name = "liger-kernel", specifier = ">=0.5.10" },
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "modelexpress", marker = "extra == 'modelexpress'", specifier = "==0.3.0" },
{ name = "mooncake-transfer-engine", specifier = ">=0.3.10.post2" },
@@ -4994,6 +5056,8 @@ requires-dist = [
{ name = "tenacity", specifier = ">=8.2.0" },
{ name = "tilelang", specifier = ">=0.1.8" },
{ name = "torch", specifier = ">=2.9.0", index = "https://download.pytorch.org/whl/cu128" },
{ name = "torchao", marker = "platform_machine != 'x86_64'", specifier = ">=0.17.0" },
{ name = "torchao", marker = "platform_machine == 'x86_64'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl" },
{ name = "torchaudio", index = "https://download.pytorch.org/whl/cu128" },
{ name = "torchdata", specifier = ">=0.11.0" },
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=23e4dfc" },
@@ -5499,6 +5563,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0c/34/c110ecc14814be490f258549192579ec02a9f3792587e933b254bcd24aa7/pyqwest-0.6.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8de70fc18b524e09883b161f79fe21a647302a0c9950ecefeb34a1c1f27269a9", size = 5764873, upload-time = "2026-05-19T03:20:17.61Z" },
]
[[package]]
name = "pystemmer"
version = "3.1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/78/95/bb893462b08db211b248f6b1aaa0dc07d068dc86f180178bc9072fef86bb/pystemmer-3.1.0.tar.gz", hash = "sha256:083cc3ed90f4c3b0668f8e31c2925cbb4db3bf0fd6d710e0ad0914f33685f7df", size = 302551, upload-time = "2026-05-22T11:23:44.581Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/06/55/78699a2621a472be98bae7fb36bdda610b7d1c8bcd8ff448301230260cf9/pystemmer-3.1.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:550bd609aa8dc324033eb1c8d34bfd68649183bbdab871ff534332dcafdc5e5a", size = 752410, upload-time = "2026-05-22T11:14:12.075Z" },
{ url = "https://files.pythonhosted.org/packages/67/63/e3937ac1df5243e94bde11fc1e57584480de419587f46a4badf5088e7ca6/pystemmer-3.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c6db50dd5e92a2a0acf2b2cec55fddcff3928bf490e26d0c45bc0483272a46c", size = 761062, upload-time = "2026-05-22T11:14:13.78Z" },
{ url = "https://files.pythonhosted.org/packages/e7/63/1f7ef438e19029025fc73fe95480d0dbb2ff323f1aec9c087ad9eb952afb/pystemmer-3.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b86b0b14634788060cab98ad0cae023620aa7b29f9155e8b474632fc80793405", size = 756304, upload-time = "2026-05-22T11:14:15.419Z" },
{ url = "https://files.pythonhosted.org/packages/ad/5e/816d59b780aa552c87a7e25148005f41be18193482b122d67c6235741b31/pystemmer-3.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6a1289aa31f5f613a31916e7d4e6eaf6b0e6e70a3d494bf08b1d999a0aaf458e", size = 754520, upload-time = "2026-05-22T11:14:16.754Z" },
]
[[package]]
name = "pytest"
version = "9.0.3"
@@ -6138,6 +6214,17 @@ requires-dist = [
{ name = "verifiers", specifier = ">=0.1.4" },
]
[[package]]
name = "senior-swe-bench-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/swe/senior_swe_bench_v1" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
]
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.1.dev40" }]
[[package]]
name = "sentence-repeater"
version = "0.1.1"
@@ -7086,6 +7173,58 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e2/79/a914539b4785f3e44f891aa012a886edb8bc10fe081c440981c57543ce21/torch_c_dlpack_ext-0.1.5-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e6f9da4bb9af70e27facc777458be62e10dbbbddda7672d16138db0553c5a524", size = 897846, upload-time = "2026-01-12T11:24:48.168Z" },
]
[[package]]
name = "torchao"
version = "0.17.0"
source = { registry = "https://pypi.org/simple" }
resolution-markers = [
"platform_machine == 'aarch64' and sys_platform == 'linux'",
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/c9/37/ef37ca885265e5f79a168616767dd416a3cea1cc3b28bb6b503ce4a5b652/torchao-0.17.0-py3-none-any.whl", hash = "sha256:02eba449036715b9ae784fbaa1a6f97994bb7b0421ce92d1d5d1c08e5bd6d349", size = 1200680, upload-time = "2026-03-30T22:25:54.457Z" },
]
[[package]]
name = "torchao"
version = "0.17.0+git02105d46c"
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", hash = "sha256:899ee5ac05292a5ffac1e44817c524b63fff850c6d5f679d3087f6770ba628c6" },
]
[package.metadata]
requires-dist = [
{ name = "bitsandbytes", marker = "extra == 'dev'" },
{ name = "blobfile", marker = "extra == 'dev'" },
{ name = "cmake", marker = "extra == 'dev'", specifier = ">=3.19.0,<4.0.0" },
{ name = "diskcache", marker = "extra == 'dev'" },
{ name = "expecttest", marker = "extra == 'dev'" },
{ name = "fire", marker = "extra == 'dev'" },
{ name = "hypothesis", marker = "extra == 'dev'" },
{ name = "importlib-metadata", marker = "extra == 'dev'" },
{ name = "lm-eval", marker = "extra == 'dev'" },
{ name = "matplotlib", marker = "extra == 'dev'" },
{ name = "ninja", marker = "extra == 'dev'" },
{ name = "packaging", marker = "extra == 'dev'" },
{ name = "pandas", marker = "extra == 'dev'" },
{ name = "parameterized", marker = "extra == 'dev'" },
{ name = "pre-commit", marker = "extra == 'dev'" },
{ name = "pycocotools", marker = "extra == 'dev'" },
{ name = "pytest", marker = "extra == 'dev'", specifier = "==8.4.2" },
{ name = "pyyaml", marker = "extra == 'dev'" },
{ name = "ruff", marker = "extra == 'dev'", specifier = "==0.11.6" },
{ name = "sentencepiece", marker = "extra == 'dev'" },
{ name = "tabulate", marker = "extra == 'dev'" },
{ name = "tiktoken", marker = "extra == 'dev'" },
{ name = "tqdm", marker = "extra == 'dev'" },
{ name = "transformers", marker = "extra == 'dev'" },
{ name = "unittest-xml-reporting", marker = "extra == 'dev'" },
]
provides-extras = ["dev"]
[[package]]
name = "torchaudio"
version = "2.11.0+cu128"
@@ -7534,7 +7673,7 @@ requires-dist = [
{ name = "python-dotenv", marker = "extra == 'browser'", specifier = ">=1.0.0" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "reasoning-gym", marker = "extra == 'rg'" },
{ name = "renderers", specifier = ">=0.1.8.dev40" },
{ name = "renderers", specifier = ">=0.1.8" },
{ name = "requests" },
{ name = "requests", marker = "extra == 'rl'" },
{ name = "rich" },