Compare commits

...
Author SHA1 Message Date
Matej SirovatkaandGitHub 534888b77d feat(models): add native Qwen3.5 family implementation (#3429)
## Summary

Unify Qwen3.5 dense, MoE, and VLM training under a native
implementation, including the Qwen3.8 checkpoint that uses this
architecture. Remove the separate MoE package and global Transformers
model patches.

- Keep `Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL)` shared by the
backbone and causal LM; remove unused Transformers TP/PP plans,
split-module metadata, cache arguments, and redundant initialization.
Modules own their initialization, including zero-centered RMSNorm.
- Use Prime's shared attention and MoE runtime. Gated full attention
consumes the fused QKV projection with the correct doubled query width;
configured MoE load balancing allocates its router selection bias.
- Own packed DeltaNet, zero-centered RMSNorm, MRoPE, and the vision
encoder. Hybrid layers support Ulysses CP through FLA boundary-state
exchange; full attention uses common attention dispatch.
- Convert official fused MoE expert weights to Prime's split projections
and back, excluding MTP weights.
- Keep the narrow compiler boundary for FLA CP convolution, whose
collective layout fails Dynamo tracing. Vision FlashAttention has no
compiler disable and uses each backend's declared return format
directly.

Qwen tests live under `tests/unit/train/models/qwen3_5/`:
`test_model.py` parametrizes initialization, context-parallel setup, and
forward/backward/packing checks over dense and MoE configs;
`test_vlm.py` groups vision tests with CPU MRoPE checks. MoE router
replay remains a dedicated check. Tests use native configs and models
without Transformers reference models, HF weight comparisons, or Hub
downloads. Public model helpers use
`AutoModelForCausalLMPrimeRL.from_config` with the trainer's shared
auto-attention resolver, without hardcoded backends or private attention
config writes. Remove the class/source-introspection test and duplicate
shared-attention checks. Remove the blanket BF16 optimizer/reduction
restriction for RL VLMs; FP32 defaults remain unchanged and FSDP still
computes in BF16.

Text and vision consume Prime's resolved `model.attn` configuration
directly, including under Ulysses CP. Remove Qwen constructor
fallback/propagation logic, the forced vision SDPA override, and its
unused vision branch.

MTP and video training are outside this runtime's scope.
`scripts/mini_moe.py` is unchanged from main and is outside this PR's
validation.

## Math KL validation

Both checkpoints completed 20 steps on `math-env`
(`PrimeIntellect/Hendrycks-Math`, train split), with **batch size 64**.
Every step-mean KL is below **0.015**.

| Checkpoint | Steps | Mean KL over 20 steps | Highest step-mean KL |
|---|---:|---:|---:|
| `Qwen/Qwen3.8-27B` | 20 | 0.000359685 | 0.000953884 |
| `Qwen/Qwen3.5-35B-A3B` | 20 | 0.000208713 | 0.000462048 |

Runs executed concurrently on separate H200 nodes using `uv run rl @
<config>`, with four trainer and four inference GPUs per model. Both
Slurm jobs completed with exit code 0: dense job 387, MoE job 386.
Tested commit: `9983e7bed`.

Settings: main's `debug` algorithm with constant per-token advantage
1.0; original task sampler; math-verify scoring without the optional LLM
judge; Prime VM runtime enforcing the task network policy; sequence
length 4096, maximum completion length 2048, group size 8, learning rate
1e-6, compilation, selective activation checkpointing, FlashAttention 3,
and NCCL weight updates. MoE additionally uses EP=4 and router replay.
Inference uses `max_num_seqs=64`. Optimization and reduction dtypes
retain their FP32 defaults.

All 20 batches per model contained 64 trainable episodes, and all
gradient norms were finite. These are asynchronous E2E measurements of
`mismatch_kl/all/mean`; the summary averages the 20 step means and
includes normal policy staleness. The debug algorithm exercises training
with synthetic advantages, so this is a correctness check, not a
learning-quality benchmark. These 20-step runs use text inputs; packed
image-conditioned validation is recorded below.

<details>
<summary>All 20 step-mean KL values</summary>

| Step | Dense mean KL | MoE mean KL |
|---:|---:|---:|
| 1 | 0.000087817 | 0.000103068 |
| 2 | 0.000133938 | 0.000132430 |
| 3 | 0.000112734 | 0.000115124 |
| 4 | 0.000193951 | 0.000099179 |
| 5 | 0.000205668 | 0.000214333 |
| 6 | 0.000359477 | 0.000348763 |
| 7 | 0.000838096 | 0.000161281 |
| 8 | 0.000150568 | 0.000207813 |
| 9 | 0.000190916 | 0.000158351 |
| 10 | 0.000246897 | 0.000258552 |
| 11 | 0.000492465 | 0.000462048 |
| 12 | 0.000236148 | 0.000177551 |
| 13 | 0.000311170 | 0.000316216 |
| 14 | 0.000953884 | 0.000286797 |
| 15 | 0.000817523 | 0.000233271 |
| 16 | 0.000320892 | 0.000184788 |
| 17 | 0.000567697 | 0.000175972 |
| 18 | 0.000280278 | 0.000164684 |
| 19 | 0.000264224 | 0.000196673 |
| 20 | 0.000429352 | 0.000177372 |

</details>

## Packed VLM validation

Both models completed five packed image RL updates on MMMU Math dev,
with batch size 32 and an 8192-token trainer packing limit. All 160
samples per model included images.

| Model | Steps | Mean KL | Maximum step-mean KL | Images per packed
microbatch |
|---|---:|---:|---:|---:|
| Qwen/Qwen3.8-27B | 5 | 0.000501153 | 0.000729994 | 5–6 |
| Qwen/Qwen3.5-35B-A3B | 5 | 0.000346154 | 0.000458347 | 5–6 |

| Step | Dense KL | MoE KL |
|---:|---:|---:|
| 1 | 0.000231250 | 0.000167199 |
| 2 | 0.000387219 | 0.000343682 |
| 3 | 0.000553381 | 0.000360291 |
| 4 | 0.000729994 | 0.000401253 |
| 5 | 0.000603919 | 0.000458347 |

Native models; trainable vision encoder; FA3; compiled decoder blocks
and selective activation checkpointing; FP32 optimization and gradient
reduction; CP1; MoE EP4 and router replay; debug advantages; group size
8; maximum completion length 1024; inference context 4096; NCCL weight
broadcasts. These are correctness smokes on four repeated diagram
questions, not learning-quality benchmarks.

Packed MRoPE exactly matched individual-document MRoPE for all 320
training samples, and image-grid/pixel-patch counts matched each
document’s image-token spans. Both Slurm jobs exited 0 (dense 400, MoE
399). MoE needed allocator retries at the H200 memory limit.

Image+CP+compile remains separately unresolved; these E2E runs use CP1.

Tested runtime contents: `dcdf770df` (subsequent commits only change
tests). Run configs and detailed batch/position evidence are under
`/home/matej/prime-rl-verify/pr3429-20260910/`.

## Other validation

- Attention cleanup at `a2173601f`: H200 Qwen suite 24 passed, one
skipped; official dense/MoE model loading preserves configured attention
for text and vision at CP sizes 1 and 2. An additional compiled image/CP
backward check exposed `Autograd not support dtype: Int` with selective
activation checkpointing; the same error reproduces using the previous
SDPA vision path. Compiled image/CP validation remains unresolved. The
completed math runs above use CP=1.

- Native-only H200 Qwen suite: **20 passed, one expected single-rank CP
skip**, with `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1` (Slurm 407;
consolidated dense/MoE suite). Existing config suite: **175 passed**.
Ruff check/format pass. Both dense and MoE run the shared
packed-versus-unpacked comparison. MoE replays identical expert
selections to isolate document boundaries; ordinary routing
forward/backward remains covered.
- CI at `9983e7bed`: CPU unit tests, Ruff, slim install, and CodeQL
pass. GPU CI passes the Qwen tests; its five failures are in unchanged
DeepSeek V4 tests (three packed-batch assertions reproduced on
unmodified main `bad80b1a3`, two FP8 architecture failures). GPU CI: 66
passed, 82 skipped, 599 deselected, five failed.
- Two-rank H200 compiled packed DeltaNet output and input-gradient
checks passed with the CP convolution compiler boundary.
- Exact official checkpoint key/shape conversion and reverse conversion
passed: dense 1,199 source keys to 1,184 runtime keys; MoE 1,811 source
keys to 1,066 runtime keys after excluding MTP.
- Full H200 unit suite: 737 passed, 12 skipped, three DeepSeek V4
failures also reproduced on unmodified main. The weight-transfer test
imports the unified model.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large change to core training models (hybrid attention, MoE weight
conversion, packed multimodal RL) with removed Transformers workarounds;
regressions would affect Qwen3.5/3.8 RL and VLM correctness rather than
peripheral code.
> 
> **Overview**
> Replaces the split **Qwen3.5 dense + MoE packages** and **Transformers
runtime monkey-patches** with one **native PrimeRL implementation**
under `models/qwen3_5/`. Dense text, MoE text, and composite VLMs all
dispatch to **`Qwen3_5ForCausalLM`**, driven by local configs
(`Qwen3_5TextConfig`, `Qwen3_5MoeTextConfig`, vision/composite configs)
and updated **`AutoConfig` / VLM registration**.
> 
> The rewrite drops the HF-backed text stack in favor of **Prime
`FlashAttention`**, **packed varlen GatedDeltaNet** (FLA + Ulysses CP),
**zero-centered RMSNorm**, **MRoPE**, a **custom vision encoder**, and
**MoE layers** with HF↔Prime **expert weight conversion** (MTP dropped).
VLM prep keeps dummy vision runs for FSDP symmetry and shards
**`routed_experts`** under CP. **`model.py`** no longer applies Qwen3.5
checkpoint/MRoPE/varlen patches or forces vision SDPA under CP.
> 
> **Trainer/config cleanup:** removes the **VLM must use bfloat16**
validator and the duplicate check at model load; **`parallel_dims`**
treats MoE on nested **`text_config`**. Ring/Ulysses patching no longer
lists Qwen-specific attention classes because **`Qwen3_5Attention`
subclasses `FlashAttention`**.
> 
> **Tests/docs:** deletes HF-comparison tests and the old `qwen3_5_moe`
tree; adds **`tests/unit/train/models/qwen3_5/`**
(forward/pack/CP/VLM/MRoPE). **`development.md`** points VLM authors at
the unified package.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d9162ce07425b56e01f6b62d3b24b141a8ff4a51. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-12 17:08:22 +02:00
43b4e2bd13 feat(deepseek_v4): support context parallelism (#3508)
Adds `ring` style CP support to deepseek v4.

The comms requirements are a bit different than those of other models
currently supported. As a point of comparison, for GLM which also has
key/value compression, the key/value creation is embarrassingly parallel
along the seq dim and the compressed key/values can be created from
cp-rank-local data. Comms are of the form `gather_for_cp(kv_cp_shard)`.

For deepseek v4 attention layers there are two general components:
sliding-window parts and compressed attention parts. The SWA treatment
is embarrassingly parallel and handled analogously to GLM. The
compressor components are not embarrassingly parallel and require
different handling. The compression step involves pooling along seq
dimension, which is what removes the embarrassingly parallel property
and necessitates cross cp-rank communication prior to kv formation. This
means that the `gather_for_cp` needs to occur at a comparatively earlier
step than in GLM, say: we never create a sharded version of `kv` (for
the compressed component) and instead use `gather_for_cp` to gather the
tensors required to create the unsharded `kv` directly.

A more memory optimized approach would only pass small windows of tokens
across CP ranks and then all-gather the small, post-compression tensors,
but we re-use `gather_for_cp` and go for simplicity here.

---------

Signed-off-by: Garrett Goon <44747910+garrett361@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-09-11 09:03:10 -04:00
550beb6f43 chore(deepseek_v4): production attention path cleanup (#3517)
Moves the eager-model helpers off the production path and into the eager
impl file for cleaner prod code. Also fixes a previous CI breakage where
we asserted on batch size == 1 which broke packing equivalence tests,
and performs other minor cleanup.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 12:39:44 -04:00
Matej SirovatkaandGitHub bad80b1a30 feat(models): add native Nemotron-H implementation (#3426)
Nemotron-H now runs as a native PyTorch module through PrimeRL Mamba-2,
shared attention, and unified MoE layers. Both Nano (regular MoE) and
Super (latent MoE) layouts are retained. Packed convolution and SSD
reset at document boundaries, and Mamba owns the full-sequence/head
redistribution required by Ulysses context parallelism. Checkpoint
conversion maps official per-expert and latent-expert weights into the
canonical runtime layout.

Updated against main (`daa72a91d`), retaining current fusion,
normalization, and CP interfaces. Restored LoRA adapter `mixer` names
and installed Mamba SSD through the GPU extra. The pinned upstream
source uses Triton without requiring the optional selective-scan CUDA
extension. Configuration guards and HF execution comparisons were
removed; existing packed-boundary tests exercise real GPU kernels.
Router compute follows `trainer.model.moe_router_dtype` (`float32` by
default, optionally `bfloat16`); the model does not force an override.

`NemotronHModel` and `NemotronHForCausalLM` both inherit
`NemotronHPreTrainedModel`, following the existing pattern used by other
architectures. The shared Nemotron base retains the config type and
architecture-specific conversion/CP hooks. Unused TP/PP plans, no-split
metadata, checkpointing flags, redundant attributes, and obsolete
`use_mamba_kernels` handling are removed. Shared model construction,
LoRA, LM-head patching, and weight-transfer code remain unchanged.
Broader removal of the model abstractions is deferred to a follow-up PR.

Garrett's config-docstring and unused-HF-attribute comments are
addressed. The broader context-parallel setter refactor and additional
gradient tests remain deferred.

## Validation

All GPU validation used Slurm-allocated Hopper H200s. Current revision
`f6d7a4033` restores the shared Nemotron base while retaining the
attribute cleanup. Ruff lint/format checks, factory
construction/dtype/inherited-hook checks, and all **15 existing model
tests** passed (Slurm job 343).

- Full unit suite: **699 passed, 11 skipped**, rerun after the nn.Module
cleanup (Slurm job 336).
- Targeted Nemotron, packed-boundary, and KL tests: **15 passed**, rerun
after removing the router override.
- H200 checks verified gate GEMM and weight-gradient dtypes for both
BF16 and FP32 router settings.
- Compiled two-GPU Mamba Ulysses: output, input-gradient, and reduced
parameter-gradient checks passed.
- Fused QKV + compiled selective activation checkpointing:
forward/backward and meta-buffer initialization passed.
- Eight two-GPU checkpoint-resume combinations: exact weights,
CPU-offloaded AdamW state, and next update across fused/unfused QKV and
FSDP shard placements.
- Official Nano checkpoint: exact key/shape conversion round trip,
**6,243 → 401 → 6,243 tensors**.
- `uv sync --all-extras --all-packages`, Ruff lint, and format checks
passed.

The 20-step run below was completed at `a7f798048` (Slurm job 339),
before restoring the original shared base. The preceding revision
`00746d6d2` was also validated: direct inheritance and the original
factory passed construction checks; compiled two-GPU Mamba and fused-QKV
selective-AC checks passed again (job 341). All 15 targeted unit tests
passed (job 340). The two-step end-to-end Nano run completed (job 342),
with mismatch KL **0.00475226** and **0.00522814**, finite gradients,
and three successful NCCL weight updates including startup. Compiled
Mamba/selective-AC and eight checkpoint-resume probes also passed again
on this code (jobs 337–338). The end-to-end run used
`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16` on eight Slurm-allocated
H200s: four trainer GPUs with EP=4 and four inference replicas. The
native trainer used FlashAttention 3, compilation, selective activation
checkpointing, and NCCL weight updates. Reverse-text used batch size 64,
group size 8, sequence length 1024, and maximum completion length 512.
Optimization and reduction dtypes retained their defaults.

Launched with `uv run rl @ rl-module-cleanup.toml`. The config sets
`trainer.env_vars.TRITON_CACHE_DIR` to node-local `/tmp` to avoid
shared-home artifact read failures; no diagnostic hooks are present in
this run.

The automated review requests a math-environment table. This run uses
reverse-text and does not satisfy that environment-specific requirement:
the current math task requires a policy-aware container runtime, which
is unavailable on the validation nodes.

**20/20 steps completed**, with **21 successful NCCL weight reloads**
(startup plus every update). Mismatch KL: mean **0.0059826873**, maximum
**0.0076148757**, final **0.0071559078**. All step KL values and
gradient norms were finite. Super latent behavior was exercised by small
model tests and distributed probes; no full-size Super run was
performed.

| Step | Mean mismatch KL |
| ---: | ---: |
| 1 | 0.0061262716 |
| 2 | 0.0044362689 |
| 3 | 0.0046579577 |
| 4 | 0.0057872585 |
| 5 | 0.0052399668 |
| 6 | 0.0067561148 |
| 7 | 0.0045683677 |
| 8 | 0.0047115656 |
| 9 | 0.0063753380 |
| 10 | 0.0065832101 |
| 11 | 0.0062584030 |
| 12 | 0.0072330278 |
| 13 | 0.0066353143 |
| 14 | 0.0060227909 |
| 15 | 0.0053012762 |
| 16 | 0.0066529727 |
| 17 | 0.0055223401 |
| 18 | 0.0060145170 |
| 19 | 0.0076148757 |
| 20 | 0.0071559078 |

CI at `a7f798048`: Ruff, slim install, and CodeQL passed; remaining jobs
were running or queued at the last check. On the previous commit
(`a60d27578`): all 15 Nemotron tests passed. The GPU unit job had five
failures in unchanged DeepSeek-V4 tests (packed-batch assertions and
unsupported FP8 kernels on that runner); CPU unit tests, Ruff, slim
install, and CodeQL passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large rewrite of a hybrid MoE/Mamba training path, checkpoint layout,
and distributed Mamba CP, with dependency pins that affect the whole GPU
stack.
> 
> **Overview**
> Replaces the Hugging Face–wrapped Nemotron-H stack with a **native
hybrid model**: one `NemotronHDecoderLayer` per block type (Mamba,
attention, MoE), a first-party **`NemotronHMamba2`** that uses FLA
packed causal conv plus **`mamba_ssm` Triton SSD**, and Ulysses CP via
**sequence↔head all-to-all inside the Mamba module** (the shared
`cp_mamba` helper is deleted).
> 
> **Checkpoint and config:** `NemotronHConfig` is realigned to current
HF field names and `layer_types`; conversion is **explicit per layer
type** instead of inferring from key presence (the old router-bias
`MapValue` shift is gone). Install/docs now pull **`mamba-ssm` from a
pinned git rev** through the **gpu** extra, with **`tilelang==0.1.12`**
pinned for vLLM compatibility; trainer init no longer disables
`use_mamba_kernels` or monkey-patches HF Mamba.
> 
> Tests drop HF parity checks and instead exercise native packed
boundaries, CP wiring on `NemotronHMamba2`, and existing KL/conversion
coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f6d7a403332bd90d26efa3dcb4c8358a5e95f92e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 14:04:38 +02:00
samsjaandGitHub aa3a6522b4 feat(algo): add debug advantage algorithm (#3521)
## What

Adds a `debug` algorithm (`[orchestrator.algo] type = "debug"`) that
assigns the same constant advantage (default `advantage = 1.0`) to every
sampled token of every clean trainable trace, ignoring rewards entirely.

## Why

Purely a debugging feature for infra work: with constant advantages
every admitted rollout is trainable and every action token carries
gradient signal, so the full RL path — advantage transport, importance
ratios, trust region, trainer loss, optimizer, weight update — can be
exercised regardless of the reward function (e.g. to rule out "all-zero
advantages / nothing trainable" when smoke-testing a pipeline). The
config validator rejects `advantage = 0`, the exact failure this tool
exists to rule out.

## How

Follows the existing "a new credit-assignment scheme is a new named
class" pattern:

- `DebugAlgoConfig` in `prime_rl.configs.algorithm` (discriminated-union
member, `action_loss_type = "rl"`, nonzero-advantage validator)
- `DebugAlgorithm` (`score_episode` — the signal is rollout-local, no
group-relative work needed) registered in `ALGORITHM_CLASSES`

Intentionally not documented in `docs/` or the skills — it is a debug
tool, and the code docstrings are the reference.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Opt-in debug algorithm only; no changes to existing algo behavior or
production defaults.
> 
> **Overview**
> Adds a **`debug`** training algorithm for pipeline smoke tests: set
`[orchestrator.algo] type = "debug"` to assign the same constant
per-token advantage (default **1.0**) on every clean trainable trace,
**ignoring rewards**, so admitted rollouts always produce RL gradient
through the full stack (advantage transport, ratios, trust region,
trainer, optimizer).
> 
> **Config:** `DebugAlgoConfig` joins the `AlgoConfig` discriminated
union with `action_loss_type = "rl"` and a validator that rejects
`advantage = 0` (the “nothing trainable” case this mode is meant to rule
out). **Runtime:** `DebugAlgorithm` implements `score_episode` via
`iter_trainable_traces` + `assign_advantages`, registered in
`ALGORITHM_CLASSES` like other algorithms. Docstrings mark it as
infra-only—not a real training signal.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ce6ca60585b3f259780492b892157b356b0569cf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 00:19:14 +02:00
3f0c2e3b5a feat(trainer): select MoE compute by layer (#3518)
Select the model layers that use the configured MoE compute backend with
`model.moe.compute.apply_to`:

- `"all"` (default): all routed-expert groups.
- `"85%"`: the first 85% of model layers, rounded down; 48 layers
selects indices 0–39.
- `[0, 1, 2, 3]`: explicit zero-based model layer indices. `[]` selects
none.

Non-MoE blocks in hybrid models count toward indices and percentages.
Other expert groups use BF16 compute and transport while retaining the
configured dispatch backend and expert parallelism. Out-of-range indices
and invalid percentages fail early. Dense linear quantization is
unchanged.

```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = "85%"
```

BF16, DeepGEMM FP8 and MXFP8 configs inherit the common selector. NVFP4
inherits it in #3511. Inference precision remains configured separately.

First PR in the stack: main → #3518 → #3515 (filter flag) → #3513 (vLLM
upgrade) → #3511 (NVFP4).

Validation: 62 focused MoE/config tests passed on this main-based
branch, including all three forms through CLI/config round trips,
percentage rounding, hybrid-layer indexing, and invalid indices. Ruff
lint/format and whitespace checks passed. GB200 mixed DeepGEMM-FP8/BF16
forward/backward passed with an exact BF16 fallback output and unchanged
parameters/checkpoint keys. EP2 with layer-index selection verified
MXFP8 transport for the selected group, BF16 transport for the excluded
group, both forwards, and BF16 fallback backward. MXFP8 backward has a
separately reproduced CuTe TMA-alignment compiler failure in the
existing kernel; that kernel is unchanged here.

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Per-layer MoE precision and transport wiring affects forward/backward
numerics and expert-parallel paths; misaligned trainer vs inference
precision could skew RL logprobs if rollout config is not matched
manually.
> 
> **Overview**
> Adds **`model.moe.compute.apply_to`** so BF16, DeepGEMM FP8, and MXFP8
routed-expert backends can target **all layers**, a **leading
percentage** (e.g. `"85%"`, rounded down), or **explicit zero-based
layer indices** (including `[]` for none). Shared
**`MoEComputeConfigBase`** validates inputs and **`resolve_layers`**
maps selections to layer sets; out-of-range indices fail at resolve
time.
> 
> **`configure_moe_runtime`** maps selection onto language-model
**`layers`** (including VLM via **`get_language_model`**): selected MoE
modules get the configured grouped GEMM; others **fall back to BF16**
compute and matching token dispatch alignment. **MXFP8 torch transport**
is used only when that layer’s grouped GEMM is actually
**`MXFP8GroupedGemm`**, so excluded layers no longer take MXFP8
all-to-all when compute is partial. Startup logging reports selected vs
total MoE layers.
> 
> Docs describe hybrid-layer counting, dense-quant independence, and RL
rollout/inference precision alignment. Unit tests cover config/CLI
round-trips and BF16 fallback without loading MXFP8 backends when
nothing is selected.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f367d4866ddcc0debd53faebe8944f096eb3ba44. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: matejsirovatka <matejsirovatka@users.noreply.github.com>
2026-09-10 00:11:35 +02:00
6b0d9e504b fix(deepseek_v4): hardware guards for unrunnable gpu CI tests (#3512)
Custom deepseek v4 flash attention requires more SMEM than some gpus
(like the current CI runners) have. Skip the tests in those cases.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:06:46 -04:00
57 changed files with 3175 additions and 4150 deletions
+21
View File
@@ -35,6 +35,7 @@ impl = "custom" # or "hf" to force the HF path
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
@@ -68,6 +69,26 @@ type = "torch"
transport = "mxfp8"
```
All MoE compute backends accept `apply_to`:
- `"all"` (default) applies the backend to all expert groups.
- `"85%"` applies it to the first 85% of model layers, rounded down. For a 48-layer model, this selects layers 0–39.
- `[0, 1, 2, 3]` selects explicit zero-based model layer indices; `[]` selects none.
Percentages must be between 0% and 100%; explicit indices must be within the model's layer count. Non-MoE blocks in hybrid models count toward layer indices and percentages. Each selected layer uses the backend for all its routed experts. Other expert groups use BF16 compute and BF16 token transport while retaining the configured dispatch backend and expert parallelism. Dense linear quantization is configured separately.
For example, this selects routed experts in Qwen3's first four model layers:
```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = [0, 1, 2, 3]
```
Backend shape checks and token alignment apply only to the selected compute path.
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
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`).
### Expert Parallelism Backends
+2 -2
View File
@@ -141,10 +141,10 @@ In the PR that adds the new model, you also need to provide a table covering the
## Adding a Custom VLM Implementation
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in `models/qwen3_5/` is the reference. The pieces, in dependency order:
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
+2 -2
View File
@@ -110,9 +110,9 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all (DeepSeek V4, GPT-OSS), is rejected at setup.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all, is rejected at setup.
`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`.
`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`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
```toml
[trainer.model]
@@ -1,7 +1,8 @@
"""Algorithm abstraction: sampling and the per-token training signal.
An algorithm is a named, self-contained config — a discriminated union keyed
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
on ``type`` (``grpo``, ``max_rl``, ``rae``, ``hierarchical_grpo``, ``opd``,
``opsd``, ``sft``, ``echo``, ``debug``).
The bundle *is* the algorithm: each variant carries
its sampling component and its credit-assignment / loss-routing parameters,
and its class defaults are the vetted setting — ``type = "opd"`` with a
@@ -364,6 +365,32 @@ class SFTAlgoConfig(BaseAlgoConfig):
return self
class DebugAlgoConfig(BaseAlgoConfig):
type: Literal["debug"] = "debug"
"""Debugging algorithm for infra work: every sampled token of every clean
trainable trace gets the same constant ``advantage`` (default 1.0),
ignoring rewards entirely. Every admitted rollout is trainable and every
action token carries gradient signal, so the full RL path (advantage
transport, importance ratios, trust region, optimizer, weight update)
can be exercised regardless of the reward function. Not a real training
signal — a policy pushed by it drifts monotonically."""
action_loss_type: ClassVar[ActionLossType] = "rl"
advantage: float = Field(1.0, allow_inf_nan=False)
"""The constant per-token advantage. Must be nonzero: a zero advantage
makes nothing trainable, the exact failure this debug tool exists to
rule out."""
@model_validator(mode="after")
def require_nonzero_advantage(self):
if self.advantage == 0.0:
raise ValueError(
"the 'debug' algorithm needs a nonzero advantage — a zero advantage leaves nothing trainable."
)
return self
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig
| EchoAlgoConfig
@@ -372,7 +399,8 @@ AlgoConfig: TypeAlias = Annotated[
| HierarchicalGRPOAlgoConfig
| OPDAlgoConfig
| OPSDAlgoConfig
| SFTAlgoConfig,
| SFTAlgoConfig
| DebugAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
@@ -387,6 +415,8 @@ its class defaults are the vetted setting.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
- ``debug`` — the same constant advantage on every sampled token, ignoring
rewards. Debugging only: for infra work that needs every token trainable.
A new credit-assignment scheme is a new named algorithm in code (subclass
``Algorithm``, register it), not a config that points at an import path.
@@ -1,8 +1,9 @@
import re
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BeforeValidator, Field, model_validator
from pydantic import BeforeValidator, Field, field_validator, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -180,19 +181,46 @@ class MXFP8Config(BaseConfig):
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
class BF16MoEComputeConfig(BaseConfig):
class MoEComputeConfigBase(BaseConfig):
apply_to: str | list[Annotated[int, Field(ge=0, strict=True)]] = "all"
"""Model layers to use this backend for: ``"all"``, a percentage such as ``"85%"``,
or zero-based layer indices such as ``[0, 1, 2]``. Percentages select the first fraction
of model layers, rounded down. Other expert groups use BF16 compute and transport.
"""
@field_validator("apply_to")
@classmethod
def validate_apply_to(cls, value: str | list[int]) -> str | list[int]:
if isinstance(value, str) and value != "all":
if re.fullmatch(r"\d+(?:\.\d+)?%", value) is None or float(value[:-1]) > 100:
raise ValueError('apply_to must be "all", a percentage from "0%" to "100%", or a list of layer indices')
return value
def resolve_layers(self, num_layers: int) -> set[int]:
if isinstance(self.apply_to, list):
invalid = [index for index in self.apply_to if index >= num_layers]
if invalid:
raise ValueError(
f"apply_to layer indices {invalid} are out of range for a model with {num_layers} layers"
)
return set(self.apply_to)
count = num_layers if self.apply_to == "all" else int(num_layers * float(self.apply_to[:-1]) / 100)
return set(range(count))
class BF16MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs in bfloat16."""
type: Literal["bf16"] = "bf16"
class DeepGemmFP8MoEComputeConfig(BaseConfig):
class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
class MXFP8MoEComputeConfig(BaseConfig):
class MXFP8MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
type: Literal["mxfp8"] = "mxfp8"
@@ -713,16 +741,6 @@ class TrainerConfig(BaseConfig):
self.optim.max_norm = None
return self
@model_validator(mode="after")
def vlms_require_bfloat16(self):
if self.model.vlm is not None and (
self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16"
):
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
return self
@model_validator(mode="after")
def vlm_freeze_incompatible_with_lora(self):
if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None:
+5 -1
View File
@@ -62,6 +62,7 @@ gpu = [
"dion ; sys_platform == 'linux'",
"tilelang>=0.1.8 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
"torchao>=0.18.0 ; sys_platform == 'linux'",
"modelexpress==0.3.0 ; sys_platform == 'linux'",
@@ -139,6 +140,8 @@ environments = [
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
# Keep vLLM's TileLang version; Nemotron uses Mamba-2's Triton kernels.
"tilelang==0.1.12",
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
@@ -285,12 +288,13 @@ prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
flash_attn_3 = { index = "pytorch-cu130-test" }
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
mamba-ssm = ["torch>=2.13.0"]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
+2 -2
View File
@@ -59,10 +59,10 @@ See the `kernels` skill.
### NemotronH (Mamba SSD kernels)
```bash
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
uv sync --extra gpu
```
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
Native NemotronH uses Mamba2 Triton SSD kernels and FLA's packed causal convolution. The pinned `mamba-ssm` source installs without `nvcc`; no separate `causal-conv1d` installation is needed. `uv sync --all-extras` includes these dependencies.
### Trainer DeepEP backend
+1 -2
View File
@@ -47,8 +47,7 @@ if _hub_kernels is not None:
try:
return _original_lazy_load_kernel(kernel_name, mapping)
except OfflineModeIsEnabled:
# Return None so NemotronH skips hub kernels; prime-rl's
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
# Return None so callers can use their non-hub implementation.
mapping[kernel_name] = None
return None
+5 -2
View File
@@ -6,8 +6,8 @@ turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``) — each named class owns
its scoring hooks
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
class owns its scoring hooks
(``score_episode`` / ``score_group``) and declares what it needs (loss
component, a "teacher", ...). One instance per env, built by
:func:`build_algorithm`. A new credit-assignment scheme is a new named class:
@@ -23,6 +23,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.hierarchical_grpo import HierarchicalGRPOAlgorithm
@@ -48,6 +49,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
"opd": OPDAlgorithm,
"opsd": OPSDAlgorithm,
"sft": SFTDistillAlgorithm,
"debug": DebugAlgorithm,
}
@@ -64,6 +66,7 @@ def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
__all__ = [
"Algorithm",
"DebugAlgorithm",
"EchoAlgorithm",
"GRPOAlgorithm",
"HierarchicalGRPOAlgorithm",
+30
View File
@@ -0,0 +1,30 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import DebugAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
if TYPE_CHECKING:
from prime_rl.orchestrator.clients import InferenceClient
class DebugAlgorithm(Algorithm):
"""Debugging credit assignment: the same constant advantage (default 1.0)
on every sampled token of every clean trainable trace, ignoring rewards
entirely. For infra work — every rollout is trainable and every action
token carries gradient signal, so the full RL path (advantage transport,
importance ratios, trust region, optimizer, weight update) can be exercised
regardless of the reward function. Not a real training signal: a policy
pushed by it drifts monotonically."""
def __init__(self, config: DebugAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.advantage = config.advantage
async def score_episode(self, episode: vf.Episode) -> None:
for _, trace in iter_trainable_traces([episode]):
assign_advantages(trace, self.advantage)
-297
View File
@@ -56,7 +56,6 @@ from prime_rl.trainer.moe_runtime import configure_moe_runtime
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
from prime_rl.utils.utils import format_time
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
from prime_rl.utils.weights import (
@@ -88,277 +87,6 @@ def pre_download_model(model_name: str, *, skip_weights: bool = False) -> None:
)
def _patch_qwen3_5_moe_conversion_mapping():
"""Fix Qwen3.5 MoE conversion mapping incorrectly applying qwen2_moe expert weight splitting.
Qwen3.5 MoE stores expert weights as fused 3D tensors natively in the checkpoint
(e.g. experts.gate_up_proj [num_experts, 2*intermediate, hidden]). The upstream mapping
incorrectly maps qwen3_5_moe → qwen2_moe, which assumes per-expert 2D checkpoint weights,
causing revert_weight_conversion to produce wrong shapes during weight broadcasting.
Remove once an official Transformers release fixes this.
"""
from transformers.conversion_mapping import (
get_checkpoint_conversion_mapping,
register_checkpoint_conversion_mapping,
)
# qwen3_5_moe_text: keep only the qwen3_5_text renaming, remove qwen2_moe expert conversion
qwen3_5_text_mapping = get_checkpoint_conversion_mapping("qwen3_5_text")
if qwen3_5_text_mapping is not None:
register_checkpoint_conversion_mapping("qwen3_5_moe_text", qwen3_5_text_mapping, overwrite=True)
# qwen3_5_moe: remove the qwen2_moe fallback entirely
register_checkpoint_conversion_mapping("qwen3_5_moe", [], overwrite=True)
def _patch_qwen3_5_text_position_ids():
"""Fix Qwen3.5 passing 3D MRoPE position_ids to decoder layers instead of 2D text_position_ids.
Upstream fix: https://github.com/huggingface/transformers/pull/44399
Remove once an official Transformers release includes this fix.
"""
import inspect
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5DecoderLayer, Qwen3_5TextModel
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeDecoderLayer, Qwen3_5MoeTextModel
for text_model_cls, decoder_layer_cls in [
(Qwen3_5TextModel, Qwen3_5DecoderLayer),
(Qwen3_5MoeTextModel, Qwen3_5MoeDecoderLayer),
]:
source = inspect.getsource(text_model_cls.forward)
if "decoder_layer" in source and "position_ids=text_position_ids" in source.split("decoder_layer")[-1]:
continue # already fixed upstream
_original_forward = decoder_layer_cls.forward
def _make_patched_forward(original):
def _patched_forward(self, hidden_states, position_ids=None, **kwargs):
if position_ids is not None and position_ids.ndim == 3:
position_ids = position_ids[0]
return original(self, hidden_states, position_ids=position_ids, **kwargs)
return _patched_forward
decoder_layer_cls.forward = _make_patched_forward(_original_forward)
def _patch_qwen3_5_linear_attn_varlen():
"""Thread cu_seqlens through Qwen3.5 GatedDeltaNet so packed batches don't
leak conv/SSM state across sequences.
HF's forward hardcodes seq_idx=None for causal_conv1d and omits cu_seqlens
for chunk_gated_delta_rule, so packed RL training sees ~0.23 Mismatch KL vs
vLLM (target <0.01). Mirrors the NemotronH mamba fix.
"""
import torch.nn.functional as F
from transformers.models.qwen3_5.modeling_qwen3_5 import (
Qwen3_5DecoderLayer,
Qwen3_5GatedDeltaNet,
Qwen3_5TextModel,
apply_mask_to_padding_states,
)
try:
from fla.modules.convolution import causal_conv1d as fla_causal_conv1d
from fla.ops.cp import build_cp_context
except ImportError:
build_cp_context = None
fla_causal_conv1d = None
if fla_causal_conv1d is not None:
# The CP boundary-state exchange inside fla's conv is not dynamo-traceable;
# graph-break deliberately so the rest of the layer still compiles.
fla_causal_conv1d = torch.compiler.disable(fla_causal_conv1d)
if getattr(Qwen3_5GatedDeltaNet.forward, "_prl_varlen_patched", False):
return
_gdn_orig = Qwen3_5GatedDeltaNet.forward
def _build_cp_context(self, local_seq_len: int, device: torch.device, cu_seqlens=None):
cp_group = getattr(self, "cp_group", None)
if cp_group is None or build_cp_context is None:
return None
global_seq_len = local_seq_len * self.cp_world_size
if cu_seqlens is not None and int(cu_seqlens[-1].item()) == global_seq_len:
global_cu_seqlens = cu_seqlens.to(device=device, dtype=torch.int32)
else:
global_cu_seqlens = torch.tensor([0, global_seq_len], dtype=torch.int32, device=device)
return build_cp_context(
cu_seqlens=global_cu_seqlens,
group=cp_group,
conv1d_kernel_size=self.conv_kernel_size,
)
def _gdn_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
if cu_seqlens is None or cache_params is not None:
return _gdn_orig(self, hidden_states, cache_params=cache_params, attention_mask=attention_mask)
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
batch_size, seq_len, _ = hidden_states.shape
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
z = self.in_proj_z(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim)
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
cp_context = _build_cp_context(self, seq_len, hidden_states.device, cu_seqlens)
if cp_context is not None and fla_causal_conv1d is not None:
mixed_qkv, _ = 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 = mixed_qkv.transpose(1, 2)
elif self.causal_conv1d_fn 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,
)
else:
# Per-segment conv1d so the kernel-1 left pad only draws from within each sequence.
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))
mixed_qkv = mixed_qkv.transpose(1, 2)
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)
key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
beta = b.sigmoid()
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
if self.num_v_heads // self.num_k_heads > 1:
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)
if cp_context is not None:
core_attn_out, _ = self.chunk_gated_delta_rule(
query,
key,
value,
g=g,
beta=beta,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cp_context.cu_seqlens,
cp_context=cp_context,
)
else:
core_attn_out, _ = self.chunk_gated_delta_rule(
query,
key,
value,
g=g,
beta=beta,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cu_seqlens,
)
core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
z = z.reshape(-1, self.head_v_dim)
core_attn_out = self.norm(core_attn_out, z)
core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
return self.out_proj(core_attn_out)
_gdn_forward._prl_varlen_patched = True
Qwen3_5GatedDeltaNet.forward = _gdn_forward
_dec_orig = Qwen3_5DecoderLayer.forward
def _dec_forward(
self,
hidden_states,
position_embeddings,
attention_mask=None,
position_ids=None,
past_key_values=None,
cu_seqlens=None,
**kwargs,
):
if position_ids is not None and position_ids.ndim == 3:
position_ids = position_ids[0]
if self.layer_type != "linear_attention":
return _dec_orig(
self,
hidden_states,
position_embeddings=position_embeddings,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
**kwargs,
)
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.linear_attn(
hidden_states=hidden_states,
cache_params=past_key_values,
attention_mask=attention_mask,
cu_seqlens=cu_seqlens,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
return residual + hidden_states
Qwen3_5DecoderLayer.forward = _dec_forward
_text_orig = Qwen3_5TextModel.forward
def _text_forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
past_key_values=None,
inputs_embeds=None,
use_cache=None,
**kwargs,
):
attn_impl = getattr(self.config, "_attn_implementation", None)
cu_seqlens = 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]
cu_seqlens, _ = get_cu_seqlens_from_position_ids(pids)
kwargs["cu_seqlens"] = cu_seqlens
return _text_orig(
self,
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
**kwargs,
)
Qwen3_5TextModel.forward = _text_forward
# Add filter to the standard logging module for transformers.modeling_utils to supress the
# flash attention dtype warnings since FSDP is used to handle mixed precision.
transformers_modeling_utils_logger = logging.getLogger("transformers.modeling_utils")
@@ -564,23 +292,7 @@ def get_model(
if is_vlm_training:
logger.info(f"Detected vision-language model: {config.name}")
if config.optimization_dtype != "bfloat16" or config.reduce_dtype != "bfloat16":
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
# Qwen3.6 and Qwen3.8 reuse the Qwen3.5 architecture, so match on model_type, not repo name.
if getattr(model_config, "model_type", "").startswith("qwen3_5"):
_patch_qwen3_5_text_position_ids()
_patch_qwen3_5_moe_conversion_mapping()
_patch_qwen3_5_linear_attn_varlen()
if is_vlm_arch and config.cp > 1 and config.cp_style == "ulysses":
vision_config = getattr(model_config, "vision_config", None)
if vision_config is not None:
logger.info("Using SDPA for VLM vision encoder under CP")
vision_config._attn_implementation = "sdpa"
if hasattr(vision_config, "_attn_implementation_internal"):
vision_config._attn_implementation_internal = "sdpa"
for subconfig_key in getattr(model_config, "sub_configs", {}):
subconfig = getattr(model_config, subconfig_key, None)
if subconfig is not None and hasattr(subconfig, "use_cache"):
@@ -633,15 +345,6 @@ def get_model(
logger.debug(f"Loaded model config ({model_config.to_dict()})")
# NemotronH: transformers' Mamba2 mixer __init__ calls lazy_load_kernel("mamba-ssm" /
# "causal-conv1d") whenever config.use_mamba_kernels is set. That hub-kernel path is gated only
# by whether the `kernels` package is importable (NOT by USE_HUB_KERNELS) and resolves from the
# HF Hub, which hard-crashes under HF_HUB_OFFLINE=1. prime-rl swaps in its own mamba_ssm Triton
# SSD kernels via _patch_mamba2_use_triton_ssd, so the hub kernels are redundant; disable them
# to keep model init offline-safe.
if getattr(model_config, "model_type", "") == "nemotron_h":
model_config.use_mamba_kernels = False
if config.debug.num_layers is not None:
# VLM configs nest num_hidden_layers under text_config
target_config = getattr(model_config, "text_config", model_config)
+16 -6
View File
@@ -8,7 +8,6 @@ from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAuto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
from transformers.models.llama.configuration_llama import LlamaConfig
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
@@ -22,8 +21,14 @@ from prime_rl.trainer.models.llama import LlamaForCausalLM
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
from prime_rl.trainer.models.qwen3_5 import (
Qwen3_5Config,
Qwen3_5ForCausalLM,
Qwen3_5MoeConfig,
Qwen3_5MoeTextConfig,
Qwen3_5TextConfig,
Qwen3_5VisionConfig,
)
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
# Make custom config discoverable by AutoConfig
@@ -36,8 +41,11 @@ AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_5", Qwen3_5Config, exist_ok=True)
AutoConfig.register("qwen3_5_text", Qwen3_5TextConfig, exist_ok=True)
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_5_moe", Qwen3_5MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeTextConfig, exist_ok=True)
AutoConfig.register("qwen3_5_vision", Qwen3_5VisionConfig, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
_CUSTOM_CAUSAL_LM_MODELS: tuple[
@@ -55,7 +63,9 @@ _CUSTOM_CAUSAL_LM_MODELS: tuple[
(NemotronHConfig, NemotronHForCausalLM),
(Qwen3MoeConfig, Qwen3MoeForCausalLM),
(Qwen3_5TextConfig, Qwen3_5ForCausalLM),
(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM),
(Qwen3_5MoeTextConfig, Qwen3_5ForCausalLM),
(Qwen3_5Config, Qwen3_5ForCausalLM),
(Qwen3_5MoeConfig, Qwen3_5ForCausalLM),
(GptOssConfig, GptOssForCausalLM),
)
for config_cls, model_cls in _CUSTOM_CAUSAL_LM_MODELS:
@@ -95,7 +105,7 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
# Points to the same unified class — the config drives text-only vs VLM behavior.
_CUSTOM_VLM_MAPPING: dict[str, type] = {
"qwen3_5": Qwen3_5ForCausalLM,
"qwen3_5_moe": Qwen3_5MoeForCausalLM,
"qwen3_5_moe": Qwen3_5ForCausalLM,
}
+2 -1
View File
@@ -44,8 +44,9 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
return False
@classmethod
def from_config(cls, config, **kwargs):
def from_config(cls, config, trust_remote_code: bool = False, **kwargs):
"""Public from_config that mirrors the Auto class API."""
del trust_remote_code
return cls._from_config(config, **kwargs)
@classmethod
@@ -27,10 +27,9 @@ Design constraints:
* **Every op is present-guarded** — it no-ops when its inputs are absent — so
the same per-layer op list can be emitted for every layer and simply skips
dense / non-matching layers, exactly as the imperative loops did.
* **"Backward" means "what the imperative ``*_to_hf`` did"**, not a strict
mathematical inverse: a few conversions are intentionally lossy (e.g.
NemotronH shifts a router bias one way and does not undo it). Such ops carry
an explicit backward (see :class:`MapValue`).
* **"Backward" means "what the imperative ``*_to_hf`` did"**, not necessarily
a strict mathematical inverse. Value transforms can provide an explicit
backward through :class:`MapValue`.
"""
from __future__ import annotations
@@ -105,6 +105,11 @@ an input, so a position that disagrees with a document boundary, a window slot t
RoPE table evaluated at positions other than the ones the causal thresholds count in, cannot be
constructed. It runs once per model forward.
Context parallelism splits the queries across ranks and leaves everything else alone: every field
above has one entry per query token and so covers this rank's `n_queries` tokens, while
`compression_layouts` covers all `total_tokens` of the sequence. Token indices always count from
the start of the whole sequence.
[The Index Contract]
All three layer types reach their keys the same way. `SparseAttnInputs` lays out one KV buffer,
@@ -122,15 +127,16 @@ surplus pick cost only their loads.
from dataclasses import dataclass
import torch
import torch.distributed as dist
from torch import Tensor, nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4UnweightedRMSNorm
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.utils.cp import gather_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
# Guarded because tilelang ships in the linux-gated `gpu` extra, so some installs lack it.
@@ -235,26 +241,19 @@ class PackedContext:
per-document `entry_local_idx` cannot be compared against, and a RoPE table evaluated at one
set of positions rotates queries the thresholds were not counted at. `build` derives every
field from one `seq_lens`, so none of those is reachable. It runs once per model forward.
Context parallelism gives each rank a contiguous run of `n_queries` tokens to use as queries
and a full copy of the keys, so every field but `compression_layouts` has one entry per query
token and covers this rank's run alone, while `compression_layouts` covers the whole sequence.
Token indices always count from the start of the whole sequence, never from this rank's run.
"""
position_ids: Tensor # (1, seq_len) int64 - token position within its own document
tok_doc_idx: Tensor # (seq_len,) int64 - which document each packed token belongs to
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type
window_indices: Tensor # (seq_len, sliding_window) int32 - packed token per window slot, IGNORE_SLOT where unused
position_ids: Tensor # (1, n_queries) int64 - token position within its own document
tok_doc_idx: Tensor # (n_queries,) int64 - which document each query token belongs to
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type, at `position_ids`
window_indices: Tensor # (n_queries, sliding_window) int32 - global token per window slot, IGNORE_SLOT if unused
compression_layouts: dict[int, CompressionLayout] # keyed by compress rate
def __post_init__(self) -> None:
# Only reachable by constructing the dataclass directly; `build` cannot violate it.
total_tokens = self.tok_doc_idx.shape[0]
if self.position_ids.shape[-1] != total_tokens:
raise ValueError(
f"position_ids covers {self.position_ids.shape[-1]} tokens, but the row has {total_tokens}"
)
if self.window_indices.shape[0] != total_tokens:
raise ValueError(
f"window_indices covers {self.window_indices.shape[0]} query rows, but the row has {total_tokens}"
)
@classmethod
def build(
cls,
@@ -263,30 +262,48 @@ class PackedContext:
seq_lens: Tensor,
dtype: torch.dtype,
device: torch.device,
cp_rank: int = 0,
cp_world_size: int = 1,
) -> "PackedContext":
"""Derive every field from one `seq_lens`, ensuring mutual consistency.
`rotary_emb` supplies the RoPE tables and, through the config it was built from, the
sliding window and the compress rates in use. Taking the config from it rather than
alongside it keeps them from naming different architectures. `dtype` must be the dtype
attention runs at, since it types the RoPE tables. The row is as wide as `seq_lens` says,
attention runs at, since it types the RoPE tables. The sequence is as long as `seq_lens` says,
padding included: both packers fold their padding into the last document.
`seq_lens` always describes the whole sequence. `cp_rank` and `cp_world_size` say which
contiguous shard of it this rank holds the queries of; the keys, the entries and the index
values addressing them stay global, so only the query side narrows.
"""
config = rotary_emb.config
# Read the width before `seq_lens` moves: on a CPU `seq_lens` that costs no device sync.
total_tokens = int(seq_lens.sum())
assert total_tokens % cp_world_size == 0, (
f"{total_tokens} tokens do not split evenly across {cp_world_size} CP ranks"
)
n_queries = total_tokens // cp_world_size
q_start = cp_rank * n_queries
cu_seqlens, _ = get_cu_seqlens_from_seq_lens(seq_lens.to(device=device))
tok_idx = torch.arange(total_tokens, device=device)
tok_doc_idx = torch.searchsorted(cu_seqlens[1:].to(tok_idx.dtype), tok_idx, right=True)
# Document-local by construction: a token's position is its distance from its own
# document's start, which is what `causal_threshold` and the entry rotation count in.
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
compress_rates = {
config.compress_rates[layer_type]
for layer_type in set(config.layer_types)
if layer_type in config.compress_rates
}
# These fields have one entry per query token, so they cover this rank's tokens only.
# `cu_seqlens` still spans the whole sequence, so document boundaries stay available.
tok_idx = torch.arange(q_start, q_start + n_queries, device=device)
tok_doc_idx = torch.searchsorted(cu_seqlens[1:].to(tok_idx.dtype), tok_idx, right=True)
# Document-local by construction: a token's position is its distance from its own
# document's start, which is what `causal_threshold` and the entry rotation count in.
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
position_embeddings = {
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
}
# A token attends the last `sliding_window` positions (itself included), clipped to its own
# document.
window_base = torch.maximum(tok_idx - position_ids[0], tok_idx - config.sliding_window + 1)
@@ -296,9 +313,7 @@ class PackedContext:
return cls(
position_ids=position_ids,
tok_doc_idx=tok_doc_idx,
position_embeddings={
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
},
position_embeddings=position_embeddings,
compression_layouts={
rate: CompressionLayout.build(cu_seqlens=cu_seqlens, compress_rate=rate) for rate in compress_rates
},
@@ -312,7 +327,9 @@ class PackedContext:
caller's positions vanish there too. A padded micro-batch restarts `position_ids` at 0
inside its last document, which this permits: padding sits mid-document, never at a start.
A sequence-global `arange` over a packed row never restarts, and a 1-based one never
reaches zero at all; both are rejected.
reaches zero at all; both are rejected. Under CP the comparison is against this rank's
queries alone, which lines up because the trainer shards the caller's `position_ids` the
same way.
"""
disagrees = (self.position_ids == 0) & (position_ids != 0)
if disagrees.any():
@@ -339,51 +356,51 @@ class SparseAttnInputs:
Every index must be a real key in `[0, n_positions)` or `IGNORE_SLOT` (-1), which marks an absent
key, which `build` enforces.
Under context parallelism the token half of `kv_buf` is still the whole global stream, `S`
being every token of the packed row, while `indices` has one entry per query token this rank
holds.
"""
kv_buf: Tensor # (batch, n_positions, 1, head_dim)
indices: Tensor # (batch, seq_len, 1, n_slots) int32 into kv_buf's position axis
def __post_init__(self) -> None:
# Shape invariants only. Asserting on index values would read the device, and this runs
# once per layer per step.
if self.kv_buf.ndim != 4 or self.kv_buf.shape[2] != 1:
raise ValueError(f"kv_buf must be (batch, n_positions, 1, head_dim), got {tuple(self.kv_buf.shape)}")
if self.indices.ndim != 4 or self.indices.shape[2] != 1:
raise ValueError(f"indices must be (batch, seq_len, 1, n_slots), got {tuple(self.indices.shape)}")
if self.indices.shape[0] != self.kv_buf.shape[0]:
raise ValueError(f"kv_buf covers {self.kv_buf.shape[0]} batch entries and indices {self.indices.shape[0]}")
indices: Tensor # (batch, n_queries, 1, n_slots) int32 into kv_buf's position axis
@classmethod
def build(
cls,
*,
kv: Tensor, # (batch, 1, seq_len, head_dim), the rotated local token stream
kv: Tensor, # (batch, 1, n_tokens, head_dim), the rotated token stream
compressed_kv: Tensor | None = None, # (batch, 1, n_entries, head_dim)
top_k_indices: Tensor | None = None, # (batch, seq_len, n_picks) int64, IGNORE_SLOT (-1) marks a surplus pick
window_indices: Tensor, # (seq_len, sliding_window) int32, IGNORE_SLOT marks an invalid slot
top_k_indices: Tensor | None = None, # (batch, n_queries, n_picks) int64, IGNORE_SLOT (-1) marks a surplus pick
window_indices: Tensor, # (n_queries, sliding_window) int32, IGNORE_SLOT marks an invalid slot
) -> "SparseAttnInputs":
"""Lay out one layer's gather slots: the local window first, then any compressed picks.
A layer with no entries passes neither `compressed_kv` nor `top_k_indices`, receiving only
the local sliding window.
"""
if (compressed_kv is None) != (top_k_indices is None):
raise ValueError("compressed_kv and top_k_indices describe the same entries: pass both or neither")
batch, _, seq_len, _ = kv.shape
assert (compressed_kv is None) == (top_k_indices is None), (
"compressed_kv and top_k_indices describe the same entries: pass both or neither"
)
# The two counts differ under CP: the keys are global and the queries are this rank's.
batch, _, n_tokens, _ = kv.shape
n_queries = window_indices.shape[0]
assert top_k_indices is None or top_k_indices.shape[1] == n_queries, (
f"top_k_indices covers {top_k_indices.shape[1]} query tokens and window_indices {n_queries}"
)
positions = kv if compressed_kv is None else torch.cat([kv, compressed_kv], dim=2)
kv_buf = positions.transpose(1, 2).contiguous() # (b, S + E, 1, d)
window = window_indices[None, :, None, :].expand(batch, seq_len, 1, -1)
window = window_indices[None, :, None, :].expand(batch, n_queries, 1, -1)
if top_k_indices is None:
return cls(kv_buf=kv_buf, indices=window.contiguous())
# A surplus pick is `IGNORE_SLOT` (-1) and stays `IGNORE_SLOT`; a real one names an entry,
# which sits past the token stream in `kv_buf`, hence the shift by `seq_len`.
# which sits past the token stream in `kv_buf`, hence the shift by `n_tokens`.
# NOTE: the attention kernel recompiles for every unique `indices.shape[-1]` value. If
# recompilation becomes a bottleneck, consider padding to fixed length with `IGNORE_SLOT` values.
picks = torch.where(top_k_indices >= 0, top_k_indices + seq_len, IGNORE_SLOT)
picks = torch.where(top_k_indices >= 0, top_k_indices + n_tokens, IGNORE_SLOT)
indices = torch.cat([window, picks[:, :, None, :].to(torch.int32)], dim=-1)
return cls(kv_buf=kv_buf, indices=indices)
@@ -443,16 +460,25 @@ class DeepseekV4Compressor(nn.Module):
torch.cat([previous_gate, gate[..., self.head_dim :]], dim=2),
)
def compress(self, hidden_states: torch.Tensor, packed: PackedContext) -> torch.Tensor:
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`.
The layout at this compressor's own rate decides which source tokens each entry pools.
"""
def compress(
self,
hidden_states: torch.Tensor,
packed: PackedContext,
cp_group: dist.ProcessGroup | None = None,
cp_world_size: int = 1,
) -> torch.Tensor:
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`."""
batch = hidden_states.shape[0]
layout = packed.compression_layouts[self.compress_rate]
kv = self.kv_proj(hidden_states)[:, layout.entry_tok_idx]
gate = self.gate_proj(hidden_states)[:, layout.entry_tok_idx] + self.position_bias
width = self.n_series * self.head_dim
proj = torch.cat([self.kv_proj(hidden_states), self.gate_proj(hidden_states)], dim=-1)
if cp_world_size > 1:
proj = gather_for_cp(proj, cp_group)
kv, gate = proj.split(width, dim=-1)
kv = kv[:, layout.entry_tok_idx]
gate = gate[:, layout.entry_tok_idx] + self.position_bias
if self.n_series == 2:
kv, gate = self._overlap_with_previous_window(kv, gate, layout)
@@ -500,10 +526,17 @@ class DeepseekV4Indexer(nn.Module):
self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
@torch.no_grad() # Returns non-differentiable integer indices.
def forward(self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext) -> torch.Tensor:
def forward(
self,
hidden_states: torch.Tensor,
q_residual: torch.Tensor,
packed: PackedContext,
cp_group: dist.ProcessGroup | None = None,
cp_world_size: int = 1,
) -> torch.Tensor:
batch, seq_len, _ = hidden_states.shape
assert batch == 1, f"the indexer needs a packed batch of size 1, got {batch}"
compressed_kv = self.compressor.compress(hidden_states, packed)
compressed_kv = self.compressor.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
n_entries = compressed_kv.shape[1]
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
@@ -541,12 +574,18 @@ class DeepseekV4CSACompressor(DeepseekV4Compressor):
self.indexer = DeepseekV4Indexer(config)
def forward(
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
self,
hidden_states: torch.Tensor,
q_residual: torch.Tensor,
packed: PackedContext,
cp_group: dist.ProcessGroup | None = None,
cp_world_size: int = 1,
) -> tuple[torch.Tensor, torch.Tensor]:
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
compressed_kv = self.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
# The indexer reads the same layout: it compresses the same source windows at a narrower
# head dim, so its entry `e` and this compressor's entry `e` are the same window.
return compressed_kv, self.indexer(hidden_states, q_residual, packed)
picks = self.indexer(hidden_states, q_residual, packed, cp_group=cp_group, cp_world_size=cp_world_size)
return compressed_kv.unsqueeze(1), picks
def init_weights(self, init_std: float) -> None:
super().init_weights(init_std)
@@ -568,11 +607,16 @@ class DeepseekV4HCACompressor(DeepseekV4Compressor):
super().__init__(config, config.head_dim, config.compress_rates["heavily_compressed_attention"], n_series=1)
def forward(
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
self,
hidden_states: torch.Tensor,
q_residual: torch.Tensor,
packed: PackedContext,
cp_group: dist.ProcessGroup | None = None,
cp_world_size: int = 1,
) -> tuple[torch.Tensor, torch.Tensor]:
"""`q_residual` is part of the compressor contract but unused: HCA has no indexer."""
batch = hidden_states.shape[0]
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
compressed_kv = self.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
layout = packed.compression_layouts[self.compress_rate]
# `threshold` counts entries within the query's own document, so it selects how far into
@@ -581,7 +625,7 @@ class DeepseekV4HCACompressor(DeepseekV4Compressor):
base = layout.first_entry_of_doc[packed.tok_doc_idx][None, :, None] # (1, seq_len, 1)
offsets = torch.arange(layout.max_entries_per_doc, device=hidden_states.device)
picks = torch.where(offsets < threshold, base + offsets, IGNORE_SLOT)
return compressed_kv, picks.expand(batch, -1, -1)
return compressed_kv.unsqueeze(1), picks.expand(batch, -1, -1)
COMPRESSOR_CLASSES = {
@@ -637,63 +681,35 @@ class DeepseekV4Attention(nn.Module):
)
self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
self.sinks = nn.Parameter(torch.zeros(self.num_heads))
self.attn_impl = config._attn_impl
# Raised here rather than from the first forward, where it would surface as an ImportError
# or a tilelang compile failure a long way from the config that caused it.
blocker = _kernel_blocker(self.num_heads, self.head_dim) if self.attn_impl == "kernel" else None
blocker = _kernel_blocker(self.num_heads, self.head_dim)
if blocker is not None:
raise ValueError(f"DeepSeek V4 cannot run the fused sparse-attention kernel: {blocker}")
assert config.attention_dropout == 0.0, "the fused sparse attention kernel implements no dropout"
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
self.compressor = compressor_class(config) if compressor_class is not None else None
def _eager(self, q: Tensor, kv: Tensor, attention_mask: Tensor) -> Tensor:
return eager_attention_with_sinks(
q,
kv,
kv,
self.sinks,
attention_mask,
scaling=self.scaling,
dropout=self.attention_dropout,
training=self.training,
)
self._cp_group: dist.ProcessGroup | None = None
self._cp_rank: int = 0
self._cp_world_size: int = 1
def _attend(self, q: Tensor, kv: Tensor, compressed: tuple[Tensor, Tensor] | None, packed: PackedContext) -> Tensor:
"""Attend `q` (b, h, t, d) over the local KV `kv` (b, 1, t, d), plus any compressed entries.
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
Returns (b, t, h, d). A sliding layer sees only its window and passes `compressed` as
`None`; a compressed layer reaches further through its compressor's output, the entries
paired with the per-query indices selecting among them.
Every layer lays its slots out once, in `SparseAttnInputs`, and then differs only in the
attention core it hands them to, so the eager consumer is an oracle for the kernel rather
than a second answer to which keys a query reads.
"""
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
inputs = SparseAttnInputs.build(
kv=kv,
compressed_kv=compressed_kv,
top_k_indices=top_k_indices,
window_indices=packed.window_indices,
)
if self.attn_impl == "eager":
n_positions = inputs.kv_buf.shape[1]
attention_mask = dense_mask_from_indices(inputs.indices, n_positions, q.dtype)
return self._eager(q, inputs.kv_buf.transpose(1, 2), attention_mask)
# `eager_attention_with_sinks` drops attention weights and the kernel does not, so the
# two only agree at zero. The default is 0.0 but a config may set it.
assert self.attention_dropout == 0.0, "the fused sparse attention kernel implements no dropout"
q = q.transpose(1, 2).contiguous() # the kernel asserts contiguity
out, _ = dsv4_sparse_attn(q, inputs.kv_buf, inputs.indices, self.sinks, self.scaling)
return out
@property
def cp_enabled(self) -> bool:
return self._cp_world_size > 1
def forward(self, hidden_states: torch.Tensor, packed: PackedContext) -> tuple[torch.Tensor, None]:
"""`packed` carries the document boundaries every pathway below is clipped at."""
# Shape keys in the comments below:
#
# - `b`: batch
# - `t`: token in the packed row
# - `t`: token in this rank's query shard
# - `T`: token in the whole packed row, which is `t` unless CP is on
# - `h`: attention head
# - `d`: head_dim
# - `e`: compressed entry
@@ -704,18 +720,41 @@ class DeepseekV4Attention(nn.Module):
# `hidden_states` is (b, t, hidden_size).
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, -1, d): the -1 is h for q, 1 for kv
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, h, d), the query view
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2) # (b, h, t, d)
q = apply_rotary_pos_emb_interleaved(self.q_b_norm(q), cos, sin)
kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2) # (b, 1, t, d)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin)
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
if self.cp_enabled:
kv = gather_for_cp(kv, self._cp_group) # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
compressed = self.compressor(hidden_states, q_residual, packed) if self.compressor is not None else None
attn_output = self._attend(q, kv, compressed, packed) # (b, t, h, d)
compressed = (
self.compressor(
hidden_states, q_residual, packed, cp_group=self._cp_group, cp_world_size=self._cp_world_size
)
if self.compressor is not None
else None
)
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
inputs = SparseAttnInputs.build(
kv=kv,
compressed_kv=compressed_kv,
top_k_indices=top_k_indices,
window_indices=packed.window_indices,
)
attn_output, _ = dsv4_sparse_attn(
q.transpose(1, 2).contiguous(),
inputs.kv_buf,
inputs.indices,
self.sinks,
self.scaling,
) # (b, t, h, d)
# The value stream is the key stream, so it arrived rotated. Rotating the output
# by the conjugate angle at the query position cancels that out.
@@ -742,6 +781,4 @@ __all__ = [
"DeepseekV4Indexer",
"PackedContext",
"SparseAttnInputs",
"dense_mask_from_indices",
"eager_attention_with_sinks",
]
@@ -1,4 +1,4 @@
from typing import Any, Literal
from typing import Any
from huggingface_hub.dataclasses import strict
from transformers.configuration_utils import PretrainedConfig
@@ -125,7 +125,6 @@ class DeepseekV4Config(PretrainedConfig):
index_n_heads: int = 64,
index_head_dim: int = 128,
index_topk: int = 512,
_attn_impl: Literal["kernel", "eager"] = "kernel",
num_experts_per_tok: int = 6,
n_routed_experts: int = 256,
n_shared_experts: int = 1,
@@ -182,9 +181,6 @@ class DeepseekV4Config(PretrainedConfig):
self.index_n_heads = index_n_heads
self.index_head_dim = index_head_dim
self.index_topk = index_topk
# Exists so tests can run toy shapes the kernel rejects; no shipped config may set it,
# and `to_dict` drops it so it never reaches disk.
self._attn_impl = _attn_impl
self.partial_rotary_factor = (
partial_rotary_factor
@@ -324,18 +320,15 @@ class DeepseekV4Config(PretrainedConfig):
self.rope_parameters = rope_parameters_dict
def to_dict(self) -> dict[str, Any]:
"""Drop the in-memory-only fields before serializing.
"""Drop the in-memory-only field before serializing.
`num_hash_layers` is the on-disk source of truth (matching the real checkpoint);
`mlp_layer_types` only exists in memory so HF's real `DeepseekV4SparseMoeBlock`
(which reads `config.mlp_layer_types[layer_idx]` directly) still works when this
config is handed to it, e.g. in HF-parity tests. `_attn_impl` is a test knob: an
underscore prefix alone would not keep it out, since the base method strips an
explicit list of names.
config is handed to it, e.g. in HF-parity tests.
"""
output = super().to_dict()
output.pop("mlp_layer_types", None)
output.pop("_attn_impl", None)
return output
def validate_layer_type(self) -> None:
@@ -1,13 +1,20 @@
"""Naive DeepSeek V4 attention reference.
Nothing in the production path calls these. They exist for the tests, where a dense, obviously
correct implementation is the standard the fused kernel is measured against. They take plain
tensors, so this module imports nothing from `attention.py` and the dependency runs one way only.
correct implementation is the standard the fused kernel is measured against, and where it is the
only implementation that runs at shapes the kernel cannot tile. The dependency runs one way only:
this module reads `attention.py`, which is kernel-only and never reads back.
"""
import types
import torch
import torch.nn.functional as F
from torch import Tensor
from torch import Tensor, nn
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext, SparseAttnInputs
from prime_rl.trainer.models.deepseek_v4.rotary import apply_rotary_pos_emb_interleaved
def eager_attention_with_sinks(
@@ -91,3 +98,71 @@ def dense_mask_from_indices(indices: Tensor, n_positions: int, dtype: torch.dtyp
mask = torch.full((batch, 1, seq_len, n_positions + 1), float("-inf"), dtype=dtype, device=indices.device)
mask.scatter_(-1, safe, 0.0)
return mask[..., :n_positions].contiguous()
def eager_attention_forward(
module: DeepseekV4Attention, hidden_states: Tensor, packed: PackedContext
) -> tuple[Tensor, None]:
"""`DeepseekV4Attention.forward` with a dense softmax where the fused kernel goes.
The projections and the RoPE are reimplemented rather than called through, so a change to that
method has to be mirrored here. The slot layout is not: both consumers read the same
`SparseAttnInputs`, which is what makes a disagreement between them one about attention math.
"""
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, module.head_dim)
cos, sin = packed.position_embeddings[module.rope_layer_type]
q_residual = module.q_a_norm(module.q_a_proj(hidden_states))
q = module.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2)
q = apply_rotary_pos_emb_interleaved(module.q_b_norm(q), cos, sin)
kv = module.kv_norm(module.kv_proj(hidden_states))
kv = kv.view(*kv.shape[:2], 1, module.head_dim)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
if module.cp_enabled:
kv = dsv4_attention.gather_for_cp(kv, module._cp_group)
kv = kv.transpose(1, 2)
compressed = (
module.compressor(
hidden_states, q_residual, packed, cp_group=module._cp_group, cp_world_size=module._cp_world_size
)
if module.compressor is not None
else None
)
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
inputs = SparseAttnInputs.build(
kv=kv,
compressed_kv=compressed_kv,
top_k_indices=top_k_indices,
window_indices=packed.window_indices,
)
attention_mask = dense_mask_from_indices(inputs.indices, inputs.kv_buf.shape[1], q.dtype)
keys = inputs.kv_buf.transpose(1, 2)
attn_output = eager_attention_with_sinks(
q,
keys,
keys,
module.sinks,
attention_mask,
scaling=module.scaling,
dropout=module.attention_dropout,
training=module.training,
)
attn_output = apply_rotary_pos_emb_interleaved(attn_output, cos, -sin, unsqueeze_dim=2)
grouped = module.o_a_proj(attn_output.reshape(*input_shape, module.config.o_groups, -1)).flatten(2)
return module.o_b_proj(grouped), None
def use_eager_attention(module: nn.Module) -> None:
"""Rebind every `DeepseekV4Attention` under `module` to the dense reference consumer.
`modules()` yields `module` itself, so this covers a lone attention layer as well as a model
holding several of them.
"""
for submodule in module.modules():
if isinstance(submodule, DeepseekV4Attention):
submodule.forward = types.MethodType(eager_attention_forward, submodule)
@@ -9,6 +9,7 @@ embedding all the way to `hc_head`, which collapses them back before the final n
from __future__ import annotations
import torch
import torch.distributed as dist
from torch import Tensor, nn
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
@@ -50,6 +51,12 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
self.attn_hc = DeepseekV4HyperConnection(config)
self.ffn_hc = DeepseekV4HyperConnection(config)
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def forward(
self,
hidden_states: torch.Tensor,
@@ -112,9 +119,9 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def cp_support(cls, config) -> CPSupport:
return CPSupport(
frozenset(),
"its sliding window is built from post-shard document boundaries, "
"which CP's global (pre-shard) boundaries cannot address",
frozenset({"ring"}),
"currently only supporting the minimal ring strategy where all keys, or tensors "
"required to form the keys are all-gathered in the CP region.",
)
def _init_weights(self, module: nn.Module) -> None:
@@ -194,6 +201,13 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
self.post_init()
def get_cp_rank_and_world_size(self) -> tuple[int, int]:
if len(self.layers) == 0:
return 0, 1
layer = self.layers[0]
return getattr(layer, "_cp_rank", 0), getattr(layer, "_cp_world_size", 1)
def forward(
self,
input_ids: torch.LongTensor | None = None,
@@ -229,20 +243,27 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
sliding window at document boundaries and lays out the compressors' entries per
document, so a packed row gives every document what running it alone would.
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
Whether `seq_lens` holds pre-CP-shard (global) document boundaries. V4 shards the
queries alone and keeps every key, entry and index value global, so it needs the
whole row's boundaries: this must be set exactly when context parallelism is on.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if seq_lens_are_pre_shard:
raise NotImplementedError(
"DeepSeek V4 does not support context parallelism: the sliding window and the "
"compressors' entry layout become indices into this shard's own KV buffer, and "
"boundaries for the whole row would put them past its end."
)
assert (input_ids is None) != (inputs_embeds is None), "pass exactly one of input_ids or inputs_embeds"
cp_rank, cp_world_size = self.get_cp_rank_and_world_size()
assert seq_lens_are_pre_shard == (cp_world_size > 1), (
f"seq_lens_are_pre_shard={seq_lens_are_pre_shard} disagrees with cp_world_size={cp_world_size}"
)
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# `seq_lens` describes the whole row and `inputs_embeds` carries this rank's shard of it.
total_tokens = int(seq_lens.sum())
assert total_tokens == inputs_embeds.shape[1] * cp_world_size, (
f"seq_lens covers {total_tokens} tokens, but {cp_world_size} CP rank(s) holding "
f"{inputs_embeds.shape[1]} tokens each"
)
# Every layer type attends over the same local window; the compressed variants add their
# own out-of-window entries and the per-query bias that gates them. One layout per distinct
# compress rate, shared by every layer that pools at that rate; sliding layers own no
@@ -252,6 +273,8 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
seq_lens=seq_lens,
dtype=inputs_embeds.dtype,
device=inputs_embeds.device,
cp_rank=cp_rank,
cp_world_size=cp_world_size,
)
if position_ids is not None:
packed.check_position_ids(position_ids)
@@ -203,14 +203,6 @@ def substitute_ring_attn(
AfmoeFlashAttention._compute_attention = _ring_compute_attention
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
Qwen3_5MoeGatedFlashAttention._compute_attention = _ring_compute_attention
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
Qwen3_5GatedFlashAttention._compute_attention = _ring_compute_attention
from prime_rl.trainer.models.gpt_oss.attention import substitute_gpt_oss_ring_attention
substitute_gpt_oss_ring_attention(process_group, heads_k_stride)
@@ -1,221 +0,0 @@
"""All-to-all context parallelism for Mamba-2 SSM layers.
Transposes between sequence-parallel and head-parallel layouts so that each
CP rank processes the full sequence on a subset of heads, then transposes
back. This avoids materializing the full [S, full_heads] tensor on any GPU.
Communication pattern per Mamba layer:
1. in_proj (token-parallel, no comm)
2. all-to-all: [B, S/cp, D] -> [B, S, D/cp] (seq-to-head)
3. conv1d + SSM on full sequence, local heads
4. all-to-all: [B, S, D/cp] -> [B, S/cp, D] (head-to-seq)
5. out_proj (token-parallel, no comm)
"""
from __future__ import annotations
import torch
import torch.distributed as dist
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.utils import prepare_sequence_ids
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""Transpose [B, S_local, D] -> [B, S_global, D_local] via all-to-all.
Each rank sends its S_local tokens split into cp_size chunks along D,
and receives one D_local chunk from each of the cp_size ranks.
"""
B, S_local, D = x.shape
D_local = D // cp_size
# Split D into cp_size chunks, put cp dim first for all_to_all scatter
# [B, S_local, D] -> [B, S_local, cp, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, S_local, cp_size, D_local).permute(2, 0, 1, 3).contiguous()
output = all_to_all_single_equal(x, cp_group)
# output[i] = data from rank i (its S_local tokens, our D_local slice)
# [cp, B, S_local, D_local] -> [B, cp, S_local, D_local] -> [B, cp*S_local, D_local]
return output.permute(1, 0, 2, 3).reshape(B, cp_size * S_local, D_local).contiguous()
def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""Transpose [B, S_global, D_local] -> [B, S_local, D] via all-to-all.
Inverse of _all_to_all_seq_to_head.
"""
B, S_global, D_local = x.shape
S_local = S_global // cp_size
# Split S_global into cp_size chunks (one per rank), put cp dim first for scatter
# [B, S_global, D_local] -> [B, cp, S_local, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, cp_size, S_local, D_local).permute(1, 0, 2, 3).contiguous()
output = all_to_all_single_equal(x, cp_group)
# Each rank now has cp chunks of [B, S_local, D_local] — one D_local slice from each rank
# [cp, B, S_local, D_local] -> [B, S_local, cp, D_local] -> [B, S_local, D]
return output.permute(1, 2, 0, 3).reshape(B, S_local, cp_size * D_local).contiguous()
def seq_to_head_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S/cp, D] -> [B, S, D/cp] with correct backward."""
return _all_to_all_seq_to_head(x, cp_group, cp_size)
def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S, D/cp] -> [B, S/cp, D] with correct backward."""
return _all_to_all_head_to_seq(x, cp_group, cp_size)
def mamba_cp_forward(
mixer,
hidden_states: torch.Tensor,
cp_group: dist.ProcessGroup,
cp_rank: int,
cp_size: int,
cu_seqlens: torch.Tensor,
):
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
sliced at runtime so FSDP / checkpoint shapes are unchanged.
"""
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
batch_size, seq_len, _ = hidden_states.shape # seq_len = S/cp here
# ── 1. in_proj (token-parallel, no communication needed) ──
projected_states = mixer.in_proj(hidden_states)
A = -torch.exp(mixer.A_log.float())
gate, hidden_states_B_C, time_step = torch.split(
projected_states,
[mixer.intermediate_size, mixer.conv_dim, mixer.num_heads],
dim=-1,
)
# ── 2. All-to-all: seq-parallel -> head-parallel ──
# gate: [B, S/cp, nheads * hdim] -> [B, S, (nheads/cp) * hdim]
# hidden_states_B_C: [B, S/cp, nheads*hdim + 2*ngroups*dstate] -> [B, S, ...]
# time_step: [B, S/cp, nheads] -> [B, S, nheads/cp]
gate = seq_to_head_parallel(gate, cp_group, cp_size)
time_step = seq_to_head_parallel(time_step, cp_group, cp_size)
# hidden_states_B_C needs special handling: x part shards by heads, B/C parts shard by groups
# conv_dim = intermediate_size + 2 * ngroups * dstate
groups_time_state_size = mixer.n_groups * mixer.ssm_state_size
x_part, B_part, C_part = torch.split(
hidden_states_B_C,
[mixer.intermediate_size, groups_time_state_size, groups_time_state_size],
dim=-1,
)
x_part = seq_to_head_parallel(x_part, cp_group, cp_size)
B_part = seq_to_head_parallel(B_part, cp_group, cp_size)
C_part = seq_to_head_parallel(C_part, cp_group, cp_size)
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
# ── 3. Local head dimensions ──
local_num_heads = mixer.num_heads // cp_size
local_intermediate_size = local_num_heads * mixer.head_dim
local_n_groups = mixer.n_groups // cp_size
# Slice parameters for local heads
head_start = cp_rank * local_num_heads
head_end = head_start + local_num_heads
local_A = A[head_start:head_end]
local_D = mixer.D[head_start:head_end]
local_dt_bias = mixer.dt_bias[head_start:head_end]
# Slice conv1d weight/bias for local channels
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
conv_x_start = cp_rank * local_intermediate_size
conv_x_end = conv_x_start + local_intermediate_size
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
conv_b_end = conv_b_start + local_n_groups * mixer.ssm_state_size
conv_c_start = mixer.intermediate_size + groups_time_state_size + cp_rank * local_n_groups * mixer.ssm_state_size
conv_c_end = conv_c_start + local_n_groups * mixer.ssm_state_size
conv_indices = torch.cat(
[
torch.arange(conv_x_start, conv_x_end, device=mixer.conv1d.weight.device),
torch.arange(conv_b_start, conv_b_end, device=mixer.conv1d.weight.device),
torch.arange(conv_c_start, conv_c_end, device=mixer.conv1d.weight.device),
]
)
local_conv_weight = mixer.conv1d.weight[conv_indices]
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
# ── 4. Causal conv1d on the full sequence, local heads ──
# Must reset at sequence boundaries for packed batches, otherwise the
# kernel-1 left pad leaks state across sequences.
hidden_states_B_C, _ = fla_causal_conv1d(
x=hidden_states_B_C,
weight=local_conv_weight.squeeze(1),
bias=local_conv_bias,
activation=mixer.activation,
cu_seqlens=cu_seqlens,
)
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
hidden_states_local, B_local, C_local = torch.split(
hidden_states_B_C,
[local_intermediate_size, local_groups_time_state_size, local_groups_time_state_size],
dim=-1,
)
# ── 5. SSM scan on full sequence, local heads ──
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
scan_output = mamba_chunk_scan_combined(
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
time_step,
local_A,
B_local.view(batch_size, full_seq_len, local_n_groups, -1),
C_local.view(batch_size, full_seq_len, local_n_groups, -1),
chunk_size=mixer.chunk_size,
D=local_D,
z=None,
seq_idx=seq_idx,
return_final_states=False,
dt_bias=local_dt_bias,
dt_softplus=True,
**dt_limit_kwargs,
)
scan_output = scan_output.view(batch_size, full_seq_len, local_intermediate_size)
# ── 6. Gated RMSNorm with local weights ──
# Zamba2RMSNormGated normalizes within groups of size `group_size`.
# In head-parallel mode, we have local_intermediate_size features.
# The group_size stays the same, but group_count is reduced.
local_norm_weight = mixer.norm.weight[cp_rank * local_intermediate_size : (cp_rank + 1) * local_intermediate_size]
scan_output = _gated_rms_norm(
scan_output, gate, local_norm_weight, mixer.norm.variance_epsilon, mixer.norm.group_size
)
# ── 7. All-to-all: head-parallel -> seq-parallel ──
scan_output = head_to_seq_parallel(scan_output, cp_group, cp_size)
# ── 8. out_proj (token-parallel, no communication needed) ──
return mixer.out_proj(scan_output)
def _gated_rms_norm(
x: torch.Tensor, gate: torch.Tensor, weight: torch.Tensor, eps: float, group_size: int
) -> torch.Tensor:
"""Gated RMSNorm matching Zamba2RMSNormGated: gate -> group-wise RMSNorm -> weight."""
input_dtype = x.dtype
x = x.to(torch.float32)
if gate is not None:
x = x * torch.nn.functional.silu(gate.to(torch.float32))
*prefix_dims, last_dim = x.shape
group_count = last_dim // group_size
x_grouped = x.view(*prefix_dims, group_count, group_size)
variance = x_grouped.pow(2).mean(-1, keepdim=True)
x_grouped = x_grouped * torch.rsqrt(variance + eps)
x = x_grouped.view(*prefix_dims, last_dim)
return (weight * x).to(input_dtype)
@@ -15,9 +15,8 @@ Ulysses is the simpler alternative to ring attention for context parallelism:
[S/cp, H, D] ◀── all-to-all ── [S, H/cp, D]
(seq ↔ heads)
Key benefit: the attention kernel itself does not need to be CP-aware. The
all-to-all is purely on Q/K/V tensors, so this works out of the box with
softmax flash-attn, linear attention, mamba, etc., without rewriting kernels.
The softmax-attention kernel itself does not need to be CP-aware. Hybrid models
use the same sequence/head redistribution in their owned recurrent modules.
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
@@ -224,14 +223,6 @@ def substitute_ulysses_attn(
AfmoeFlashAttention._compute_attention = _ulysses_compute_attention
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
Qwen3_5MoeGatedFlashAttention._compute_attention = _ulysses_compute_attention
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
Qwen3_5GatedFlashAttention._compute_attention = _ulysses_compute_attention
from prime_rl.trainer.models.gpt_oss.attention import substitute_gpt_oss_ulysses_attention
substitute_gpt_oss_ulysses_attention(process_group)
@@ -2,217 +2,142 @@ from transformers.configuration_utils import PretrainedConfig
class NemotronHConfig(PretrainedConfig):
"""Configuration for NemotronH (Nemotron-3-Super-120B-A12B) hybrid Mamba-Transformer-MoE model.
The model architecture is defined by `layers_block_type`, a list where each element is
one of "mamba", "attention", or "moe". The 120B model uses a pattern like MEMEMEM*EMEMEMEM*...
(M=Mamba-2, E=MoE with latent projections, *=Attention) repeated across 88 layers.
Args:
vocab_size: Vocabulary size.
hidden_size: Dimension of the hidden representations.
layers_block_type: Explicit list of layer types. Determines num_hidden_layers.
tie_word_embeddings: Whether to tie input/output embeddings.
pad_token_id: Padding token id.
bos_token_id: Beginning of sequence token id.
eos_token_id: End of sequence token id.
num_attention_heads: Number of attention heads.
num_key_value_heads: Number of key/value heads for GQA.
head_dim: Dimension of each attention head.
max_position_embeddings: Maximum sequence length.
attention_bias: Whether to use bias in attention layers.
intermediate_size: MLP intermediate dimension (for shared expert).
mlp_hidden_act: Activation function for MLP layers.
mlp_bias: Whether to use bias in MLP layers.
use_mamba_kernels: Whether to use fast mamba CUDA kernels.
ssm_state_size: Mamba state space dimension.
mamba_num_heads: Number of mamba heads.
mamba_n_groups: Number of groups in mamba.
mamba_head_dim: Dimension per mamba head.
mamba_d_conv: Convolution kernel size.
mamba_expand: Expansion factor.
mamba_hidden_act: Activation for mamba layers.
mamba_dt_min: Time step minimum.
mamba_dt_max: Time step maximum.
mamba_dt_limit: Time step limits.
mamba_dt_init_floor: Floor for time step initialization.
mamba_conv_bias: Whether to use bias in mamba convolution.
mamba_proj_bias: Whether to use bias in mamba projections.
mamba_chunk_size: Chunk size for mamba processing.
n_routed_experts: Number of routed experts.
n_shared_experts: Number of shared experts.
moe_intermediate_size: Expert intermediate dimension.
moe_shared_expert_intermediate_size: Shared expert intermediate dimension.
moe_latent_size: Latent projection size (None means use hidden_size).
num_experts_per_tok: Top-k routing parameter.
routed_scaling_factor: Scaling factor for routed expert outputs.
norm_topk_prob: Whether to normalize top-k probabilities.
use_bias: Global bias setting.
initializer_range: Standard deviation for weight initialization.
layer_norm_epsilon: Epsilon for layer normalization.
residual_in_fp32: Whether to keep residuals in fp32.
rescale_prenorm_residual: Whether to rescale pre-norm residuals.
load_balance_coeff: Auxiliary-loss-free load balancing coefficient.
"""
model_type = "nemotron_h"
keys_to_ignore_at_inference = ["past_key_values"]
PATTERN_MAP = {"M": "mamba", "E": "moe", "*": "attention"}
REVERSE_PATTERN_MAP = {"mamba": "M", "moe": "E", "attention": "*"}
PATTERN_TO_LAYER_TYPE = {
"M": "mamba",
"E": "moe",
"*": "attention",
}
def __init__(
self,
# General
vocab_size=131072,
hidden_size=4096,
layers_block_type=None,
num_hidden_layers=None,
tie_word_embeddings=False,
pad_token_id=0,
bos_token_id=1,
eos_token_id=2,
# Attention
num_attention_heads=32,
num_key_value_heads=8,
head_dim=128,
max_position_embeddings=4096,
attention_bias=False,
# MLP
intermediate_size=21504,
mlp_hidden_act="relu2",
mlp_bias=False,
# Mamba
use_mamba_kernels=True,
ssm_state_size=128,
mamba_num_heads=128,
mamba_n_groups=8,
mamba_head_dim=64,
mamba_d_conv=4,
mamba_expand=2,
mamba_hidden_act="silu",
mamba_dt_min=0.001,
mamba_dt_max=0.1,
mamba_dt_limit=(0.0, float("inf")),
mamba_dt_init_floor=1e-4,
mamba_conv_bias=True,
mamba_proj_bias=False,
mamba_chunk_size=128,
# MoE
n_routed_experts=8,
n_shared_experts=1,
moe_intermediate_size=7688,
moe_shared_expert_intermediate_size=7688,
moe_latent_size=None,
num_experts_per_tok=2,
routed_scaling_factor=1.0,
norm_topk_prob=True,
# General training
use_bias=False,
initializer_range=0.02,
layer_norm_epsilon=1e-5,
residual_in_fp32=False,
rescale_prenorm_residual=True,
# PrimeRL training features
load_balance_coeff=None,
# RoPE
rope_theta=10000.0,
rope_scaling=None,
vocab_size: int = 131072,
hidden_size: int = 4096,
num_hidden_layers: int | None = None,
hybrid_override_pattern: str | None = None,
layers_block_type: list[str] | None = None,
num_attention_heads: int = 32,
num_key_value_heads: int = 8,
head_dim: int = 128,
max_position_embeddings: int = 4096,
attention_bias: bool = False,
attention_dropout: float = 0.0,
intermediate_size: int = 21504,
mlp_hidden_act: str = "relu2",
mlp_bias: bool = False,
ssm_state_size: int = 128,
mamba_num_heads: int = 128,
mamba_head_dim: int = 64,
mamba_hidden_act: str = "silu",
n_groups: int = 8,
conv_kernel: int = 4,
expand: int = 2,
time_step_min: float = 0.001,
time_step_max: float = 0.1,
time_step_limit: tuple[float, float] | list[float] | None = (0.0, float("inf")),
time_step_floor: float = 1e-4,
use_conv_bias: bool = True,
chunk_size: int = 128,
mamba_proj_bias: bool = False,
n_routed_experts: int = 8,
n_shared_experts: int = 1,
moe_intermediate_size: int = 7688,
moe_shared_expert_intermediate_size: int = 7688,
moe_latent_size: int | None = None,
moe_shared_expert_overlap: bool = True,
num_experts_per_tok: int = 2,
routed_scaling_factor: float = 1.0,
n_group: int = 1,
topk_group: int = 1,
norm_topk_prob: bool = True,
use_bias: bool = False,
initializer_range: float = 0.02,
layer_norm_epsilon: float = 1e-5,
residual_in_fp32: bool = False,
hidden_dropout: float = 0.0,
rescale_prenorm_residual: bool = True,
load_balance_coeff: float | None = None,
tie_word_embeddings: bool = False,
pad_token_id: int | None = 0,
bos_token_id: int | None = 1,
eos_token_id: int | list[int] | None = 2,
**kwargs,
):
# Handle hybrid_override_pattern for backward compatibility
if "hybrid_override_pattern" in kwargs:
pattern = kwargs.pop("hybrid_override_pattern")
if layers_block_type is None:
layers_block_type = [self.PATTERN_MAP[c] for c in pattern]
) -> None:
if layers_block_type is None:
layers_block_type = ["mamba", "moe", "attention", "moe"]
pattern = hybrid_override_pattern or "ME*E"
layers_block_type = [self.PATTERN_TO_LAYER_TYPE[token] for token in pattern]
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.layers_block_type = layers_block_type
# Attention config
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.head_dim = head_dim
self.max_position_embeddings = max_position_embeddings
self.attention_bias = attention_bias
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.attention_dropout = attention_dropout
# MLP config
self.intermediate_size = intermediate_size
self.mlp_hidden_act = mlp_hidden_act
self.mlp_bias = mlp_bias
# Mamba config - stored with HF-compatible attribute names used by NemotronHMamba2Mixer
self.use_mamba_kernels = use_mamba_kernels
self.ssm_state_size = ssm_state_size
self.mamba_num_heads = mamba_num_heads
self.n_groups = mamba_n_groups
self.mamba_head_dim = mamba_head_dim
self.conv_kernel = mamba_d_conv
self.expand = mamba_expand
self.mamba_hidden_act = mamba_hidden_act
self.time_step_min = mamba_dt_min
self.time_step_max = mamba_dt_max
self.time_step_limit = mamba_dt_limit
self.time_step_floor = mamba_dt_init_floor
self.use_conv_bias = mamba_conv_bias
self.n_groups = n_groups
self.conv_kernel = conv_kernel
self.expand = expand
self.time_step_min = time_step_min
self.time_step_max = time_step_max
self.time_step_limit = time_step_limit
self.time_step_floor = time_step_floor
self.use_conv_bias = use_conv_bias
self.chunk_size = chunk_size
self.mamba_proj_bias = mamba_proj_bias
self.chunk_size = mamba_chunk_size
# Zamba2MambaMixer compat aliases (read by parent __init__ before NemotronHMamba2Mixer overrides).
# mamba_expand must give the correct intermediate_size = mamba_num_heads * mamba_head_dim
# when Zamba2 computes int(mamba_expand * hidden_size); the config's raw "expand" field
# does not satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
self.mamba_d_state = ssm_state_size
self.mamba_d_conv = mamba_d_conv
self.mamba_expand = (mamba_num_heads * mamba_head_dim) / hidden_size
self.mamba_ngroups = mamba_n_groups
self.mamba_headdim = mamba_head_dim
self.n_mamba_heads = mamba_num_heads
self.use_mem_eff_path = True
self.add_bias_linear = use_bias
# MoE config
self.n_routed_experts = n_routed_experts
self.n_shared_experts = n_shared_experts
self.moe_intermediate_size = moe_intermediate_size
self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
self.moe_latent_size = moe_latent_size
self.moe_shared_expert_overlap = moe_shared_expert_overlap
self.num_experts_per_tok = num_experts_per_tok
self.routed_scaling_factor = routed_scaling_factor
self.n_group = n_group
self.topk_group = topk_group
self.norm_topk_prob = norm_topk_prob
# General training config
self.use_bias = use_bias
self.initializer_range = initializer_range
self.layer_norm_epsilon = layer_norm_epsilon
self.residual_in_fp32 = residual_in_fp32
self.hidden_dropout = hidden_dropout
self.rescale_prenorm_residual = rescale_prenorm_residual
# PrimeRL training features
self.load_balance_coeff = load_balance_coeff
super().__init__(
tie_word_embeddings=tie_word_embeddings,
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@property
def layer_types(self) -> list[str]:
return self.layers_block_type
@property
def num_hidden_layers(self) -> int:
return len(self.layers_block_type)
@num_hidden_layers.setter
def num_hidden_layers(self, value):
if value is not None and value < len(self.layers_block_type):
self.layers_block_type = self.layers_block_type[:value]
def num_hidden_layers(self, value: int | None) -> None:
if value is None or not hasattr(self, "layers_block_type"):
return
self.layers_block_type = self.layers_block_type[:value]
__all__ = ["NemotronHConfig"]
@@ -1,100 +1,55 @@
"""Declarative HF<->prime conversion chain for NemotronH.
from torch import Tensor
NemotronH is the most involved conversion: a unified HF ``mixer`` namespace is
split into prime's ``mamba`` / ``self_attn`` / ``mlp`` by layer type, the
checkpoint uses a ``backbone.`` prefix, and the MoE router bias is shifted by
its per-tensor min on the way in (and intentionally *not* restored on the way
out — a lossy roundtrip the chain reproduces via a :class:`MapValue` whose
backward is the identity). Experts are up/down only, with no gate projection.
"""
from __future__ import annotations
from prime_rl.trainer.models.conversion_ops import (
Conditional,
ConvOp,
Drop,
MapValue,
PrefixRename,
Rename,
Stack,
key_present,
)
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, PrefixRename, Rename, Stack
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
def _moe_layer_ops(prefix: str) -> list[ConvOp]:
return [
# Router gate and selection bias.
# plus the load-balancing bias which is shifted by its min on the way in
# and not undone on the way out (MapValue backward = identity).
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.selection_bias"),
MapValue(
f"{prefix}.mlp.router.selection_bias",
forward=lambda x: x - x.min(),
backward=lambda x: x,
),
# Experts are up/down only. HF is either per-expert weights or
# a 3-D fused-at-experts-level up_proj/down_proj. Backward always emits
# per-expert (the predicate's HF key is absent in prime -> else branch).
Conditional(
predicate=key_present(f"{prefix}.mixer.experts.up_proj"),
then=[
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.up_proj"),
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.down_proj"),
],
else_=[
Stack(
stacked=f"{prefix}.mlp.experts.up_proj",
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
),
Stack(
stacked=f"{prefix}.mlp.experts.down_proj",
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
),
],
),
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
]
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
return "backbone.embeddings.weight" in state_dict or any(".mixer." in name for name in state_dict)
def _layer_op(prefix: str) -> ConvOp:
"""One uniform op for any layer: detect its type from a signature key and
dispatch. No ``layers_block_type`` needed — the unified HF ``mixer.``
namespace is disambiguated by which sub-key is present (and, on the way
back, by which prime namespace is present, so the predicates work both
directions). Mamba/attention keep a bulk ``PrefixRename`` (robust to params
we didn't enumerate); MoE needs its specific ops."""
is_attention = lambda sd: ( # noqa: E731
f"{prefix}.mixer.q_proj.weight" in sd or f"{prefix}.self_attn.q_proj.weight" in sd
)
is_moe = lambda sd: ( # noqa: E731
f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate.weight" in sd
)
return Conditional(
is_attention,
then=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn.")],
else_=[
Conditional(
is_moe,
then=_moe_layer_ops(prefix),
else_=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.mamba.")],
)
],
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
return "model.embed_tokens.weight" in state_dict or any(
namespace in name for name in state_dict for namespace in (".mamba.", ".self_attn.", ".mlp.router.")
)
def conversion_chain(config) -> list[ConvOp]:
"""Uniform per-layer dispatch — no ``layers_block_type`` required."""
def conversion_chain(config: NemotronHConfig) -> list[ConvOp]:
ops: list[ConvOp] = [
# Global. Listed first so the backbone<->model swap is played LAST on the
# way back (everything must be in model.* form before re-prefixing).
PrefixRename("backbone.", "model."),
Drop("mtp.", is_prefix=True),
Rename("model.embeddings.weight", "model.embed_tokens.weight"),
Rename("model.norm_f.weight", "model.norm.weight"),
]
ops.extend(_layer_op(f"model.layers.{i}") for i in range(config.num_hidden_layers))
for layer_idx, layer_type in enumerate(config.layer_types):
prefix = f"model.layers.{layer_idx}"
if layer_type == "mamba":
ops.append(PrefixRename(f"{prefix}.mixer.", f"{prefix}.mamba."))
elif layer_type == "attention":
ops.append(PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn."))
elif layer_type == "moe":
ops.extend(
[
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
Rename(
f"{prefix}.mixer.gate.e_score_correction_bias",
f"{prefix}.mlp.router.selection_bias",
),
Stack(
stacked=f"{prefix}.mlp.experts.up_proj",
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
),
Stack(
stacked=f"{prefix}.mlp.experts.down_proj",
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
),
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
]
)
return ops
__all__ = ["conversion_chain", "is_hf_state_dict", "is_prime_state_dict"]
@@ -0,0 +1,255 @@
"""Nemotron-H Mamba-2 and context-parallel execution.
Packed training needs the convolution and state-space scan to reset at every
document boundary. Under Ulysses context parallelism, each rank also needs the
full sequence for its local Mamba heads because recurrent state cannot be split
along the sequence.
"""
import math
import torch
import torch.distributed as dist
from torch import nn
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
def sequence_to_head_parallel(
tensor: torch.Tensor,
process_group: dist.ProcessGroup,
world_size: int,
) -> torch.Tensor:
"""Redistribute ``[B, S/world, D]`` into ``[B, S, D/world]``."""
batch_size, local_sequence_length, feature_size = tensor.shape
local_feature_size = feature_size // world_size
tensor = tensor.reshape(batch_size, local_sequence_length, world_size, local_feature_size)
tensor = tensor.permute(2, 0, 1, 3).contiguous()
tensor = all_to_all_single_equal(tensor, process_group)
return tensor.permute(1, 0, 2, 3).reshape(
batch_size,
world_size * local_sequence_length,
local_feature_size,
)
def head_to_sequence_parallel(
tensor: torch.Tensor,
process_group: dist.ProcessGroup,
world_size: int,
) -> torch.Tensor:
"""Redistribute ``[B, S, D/world]`` into ``[B, S/world, D]``."""
batch_size, sequence_length, local_feature_size = tensor.shape
local_sequence_length = sequence_length // world_size
tensor = tensor.reshape(batch_size, world_size, local_sequence_length, local_feature_size)
tensor = tensor.permute(1, 0, 2, 3).contiguous()
tensor = all_to_all_single_equal(tensor, process_group)
return tensor.permute(1, 2, 0, 3).reshape(
batch_size,
local_sequence_length,
world_size * local_feature_size,
)
class GatedRMSNorm(nn.Module):
def __init__(self, hidden_size: int, group_size: int, eps: float) -> None:
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.group_size = group_size
self.variance_epsilon = eps
def forward(
self,
hidden_states: torch.Tensor,
gate: torch.Tensor,
weight: torch.Tensor | None = None,
) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.float() * torch.nn.functional.silu(gate.float())
group_count = hidden_states.shape[-1] // self.group_size
grouped_states = hidden_states.reshape(*hidden_states.shape[:-1], group_count, self.group_size)
variance = grouped_states.square().mean(dim=-1, keepdim=True)
hidden_states = (grouped_states * torch.rsqrt(variance + self.variance_epsilon)).flatten(-2)
return (self.weight if weight is None else weight) * hidden_states.to(input_dtype)
class NemotronHMamba2(nn.Module):
def __init__(self, config: NemotronHConfig) -> None:
super().__init__()
from fla.modules.conv import causal_conv1d
from fla.ops.utils import prepare_sequence_ids
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
self.hidden_size = config.hidden_size
self.state_size = config.ssm_state_size
self.num_heads = config.mamba_num_heads
self.head_dim = config.mamba_head_dim
self.num_groups = config.n_groups
self.intermediate_size = self.num_heads * self.head_dim
self.group_state_size = self.num_groups * self.state_size
self.conv_size = self.intermediate_size + 2 * self.group_state_size
self.chunk_size = config.chunk_size
self.time_step_limit = config.time_step_limit
self.activation = config.mamba_hidden_act
projection_size = self.intermediate_size + self.conv_size + self.num_heads
self.in_proj = nn.Linear(config.hidden_size, projection_size, bias=config.use_bias)
self.conv1d = nn.Conv1d(
self.conv_size,
self.conv_size,
kernel_size=config.conv_kernel,
groups=self.conv_size,
padding=config.conv_kernel - 1,
bias=config.use_conv_bias,
)
self.dt_bias = nn.Parameter(torch.empty(self.num_heads))
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
self.D = nn.Parameter(torch.ones(self.num_heads, dtype=torch.float32))
self.norm = GatedRMSNorm(
self.intermediate_size,
group_size=self.intermediate_size // self.num_groups,
eps=config.layer_norm_epsilon,
)
self.out_proj = nn.Linear(self.intermediate_size, config.hidden_size, bias=config.use_bias)
self.causal_conv1d = causal_conv1d
self.prepare_sequence_ids = prepare_sequence_ids
self.scan = mamba_chunk_scan_combined
time_steps = torch.exp(
torch.rand(self.num_heads, dtype=torch.float32)
* (math.log(config.time_step_max) - math.log(config.time_step_min))
+ math.log(config.time_step_min)
).clamp(min=config.time_step_floor)
with torch.no_grad():
self.dt_bias.copy_((time_steps + torch.log(-torch.expm1(-time_steps))).to(self.dt_bias.dtype))
def set_context_parallel_attributes(
self,
process_group: dist.ProcessGroup,
rank: int,
world_size: int,
) -> None:
self.process_group = process_group
self.context_parallel_rank = rank
self.context_parallel_world_size = world_size
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
batch_size, sequence_length, _ = hidden_states.shape
projected_states = self.in_proj(hidden_states)
gate, convolution_input, time_step = torch.split(
projected_states,
[self.intermediate_size, self.conv_size, self.num_heads],
dim=-1,
)
num_heads = self.num_heads
num_groups = self.num_groups
intermediate_size = self.intermediate_size
conv_weight = self.conv1d.weight
conv_bias = self.conv1d.bias
state_decay = -torch.exp(self.A_log.float())
skip = self.D
dt_bias = self.dt_bias
norm_weight = self.norm.weight
if hasattr(self, "process_group"):
world_size = self.context_parallel_world_size
rank = self.context_parallel_rank
gate = sequence_to_head_parallel(gate, self.process_group, world_size)
time_step = sequence_to_head_parallel(time_step, self.process_group, world_size)
recurrent_input, state_input, state_output = torch.split(
convolution_input,
[self.intermediate_size, self.group_state_size, self.group_state_size],
dim=-1,
)
convolution_input = torch.cat(
[
sequence_to_head_parallel(recurrent_input, self.process_group, world_size),
sequence_to_head_parallel(state_input, self.process_group, world_size),
sequence_to_head_parallel(state_output, self.process_group, world_size),
],
dim=-1,
)
num_heads //= world_size
num_groups //= world_size
intermediate_size //= world_size
head_start = rank * num_heads
group_start = rank * num_groups * self.state_size
intermediate_start = rank * intermediate_size
state_decay = state_decay[head_start : head_start + num_heads]
skip = skip[head_start : head_start + num_heads]
dt_bias = dt_bias[head_start : head_start + num_heads]
norm_weight = norm_weight[intermediate_start : intermediate_start + intermediate_size]
state_input_start = self.intermediate_size + group_start
state_output_start = self.intermediate_size + self.group_state_size + group_start
conv_weight = torch.cat(
[
conv_weight[intermediate_start : intermediate_start + intermediate_size],
conv_weight[state_input_start : state_input_start + num_groups * self.state_size],
conv_weight[state_output_start : state_output_start + num_groups * self.state_size],
]
)
if conv_bias is not None:
conv_bias = torch.cat(
[
conv_bias[intermediate_start : intermediate_start + intermediate_size],
conv_bias[state_input_start : state_input_start + num_groups * self.state_size],
conv_bias[state_output_start : state_output_start + num_groups * self.state_size],
]
)
sequence_length = convolution_input.shape[1]
convolution_output, _ = self.causal_conv1d(
x=convolution_input,
weight=conv_weight.squeeze(1),
bias=conv_bias,
activation=self.activation,
cu_seqlens=cu_seqlens,
)
local_group_state_size = num_groups * self.state_size
hidden_states, state_input, state_output = torch.split(
convolution_output,
[intermediate_size, local_group_state_size, local_group_state_size],
dim=-1,
)
scan_kwargs = {}
if self.time_step_limit is not None:
scan_kwargs["dt_limit"] = self.time_step_limit
hidden_states = self.scan(
hidden_states.reshape(batch_size, sequence_length, num_heads, self.head_dim),
time_step,
state_decay,
state_input.reshape(batch_size, sequence_length, num_groups, self.state_size),
state_output.reshape(batch_size, sequence_length, num_groups, self.state_size),
chunk_size=self.chunk_size,
D=skip,
z=None,
seq_idx=self.prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0),
return_final_states=False,
dt_bias=dt_bias,
dt_softplus=True,
**scan_kwargs,
).reshape(batch_size, sequence_length, intermediate_size)
hidden_states = self.norm(hidden_states, gate, weight=norm_weight)
if hasattr(self, "process_group"):
hidden_states = head_to_sequence_parallel(
hidden_states,
self.process_group,
self.context_parallel_world_size,
)
return self.out_proj(hidden_states)
__all__ = [
"GatedRMSNorm",
"NemotronHMamba2",
"head_to_sequence_parallel",
"sequence_to_head_parallel",
]
@@ -1,576 +1,268 @@
"""PrimeRL implementation of NemotronH (Nemotron-3-Super-120B-A12B).
Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
- Mamba-2 layers (using NemotronHMamba2Mixer from HF transformers)
- MoE layers with non-gated experts and latent projections
- Attention layers (using shared FlashAttention/SDPA from prime-rl)
"""
from typing import Optional
import torch
import torch.distributed as dist
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.utils import prepare_sequence_ids
from torch import Tensor, nn
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.models.nemotron_h.modular_nemotron_h import NemotronHMamba2Mixer
from transformers.utils import auto_docstring, logging
from transformers.modeling_outputs import BaseModelOutput
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, VanillaOutputLinear
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.moe import (
GroupedExperts,
MoE,
TokenChoiceTopKRouter,
)
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import conversion_chain
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
conversion_chain,
is_hf_state_dict,
is_prime_state_dict,
)
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
logger = logging.get_logger(__name__)
_patch_applied = False
def _patch_mamba2_use_triton_ssd():
"""Patch NemotronHMamba2Mixer to use mamba_ssm Triton SSD kernels.
The HF torch_forward computes softplus in model dtype (bf16), while vLLM's
Triton kernels and mamba_ssm use fp32. This causes ~0.4 KL divergence.
This patch makes the mixer use mamba_chunk_scan_combined (Triton, fp32
softplus) for the SSD computation, with fla's Triton causal_conv1d for
convolution. Requires mamba_ssm installed.
"""
global _patch_applied
if _patch_applied:
return
if not torch.cuda.is_available():
logger.warning_once("CUDA not available; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
return
try:
from mamba_ssm.ops.triton.ssd_combined import (
mamba_chunk_scan_combined as _mamba_chunk_scan_combined,
)
except ImportError:
logger.warning_once("mamba_ssm not installed; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
return
if _mamba_chunk_scan_combined is None:
logger.warning_once("mamba_ssm not available; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
return
def _varlen_mamba_forward(self, hidden_states, cu_seqlens):
"""Varlen-aware mamba forward. `cu_seqlens` is required: shape [num_seq+1],
e.g. [0, s1, s1+s2, ...]. Handles packed batches by:
- passing cu_seqlens to causal_conv1d (conv state resets at boundaries)
- passing seq_idx to mamba_chunk_scan_combined (SSM state resets at boundaries)
"""
batch_size, seq_len, _ = hidden_states.shape
assert batch_size == 1, "varlen mamba expects batch_size=1 (packed)"
groups_time_state_size = self.n_groups * self.ssm_state_size
# 1. Input projection (pointwise, no cross-seq mixing)
projected_states = self.in_proj(hidden_states)
A = -torch.exp(self.A_log.float())
dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
gate, hidden_states_B_C, time_step = torch.split(
projected_states,
[self.intermediate_size, self.conv_dim, self.num_heads],
dim=-1,
)
# 2. Causal conv1d — must reset at sequence boundaries for packed batches,
# otherwise the kernel-1 left pad leaks state across sequences.
hidden_states_B_C, _ = fla_causal_conv1d(
x=hidden_states_B_C,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cu_seqlens=cu_seqlens,
)
hidden_states, B, C = torch.split(
hidden_states_B_C,
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
dim=-1,
)
# 3. SSM with seq_idx so state resets at sequence boundaries
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
scan_output = _mamba_chunk_scan_combined(
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
time_step,
A,
B.view(batch_size, seq_len, self.n_groups, -1),
C.view(batch_size, seq_len, self.n_groups, -1),
chunk_size=self.chunk_size,
D=self.D,
z=None,
seq_idx=seq_idx,
return_final_states=False,
dt_bias=self.dt_bias,
dt_softplus=True,
**dt_limit_kwargs,
)
scan_output = scan_output.view(batch_size, seq_len, -1)
scan_output = self.norm(scan_output, gate)
return self.out_proj(scan_output)
def _patched_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
if cu_seqlens is not None and cache_params is None and "cuda" in self.in_proj.weight.device.type:
return _varlen_mamba_forward(self, hidden_states, cu_seqlens)
if "cuda" in self.in_proj.weight.device.type:
# Disable fused training path (needs causal_conv1d CUDA extension)
orig = self.use_mem_eff_path
self.use_mem_eff_path = False
result = self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
self.use_mem_eff_path = orig
return result
return self.torch_forward(hidden_states, cache_params, attention_mask)
NemotronHMamba2Mixer.forward = _patched_forward
_patch_applied = True
logger.info("Patched NemotronHMamba2Mixer: Triton SSD kernels + varlen (cu_seqlens) support")
def _ensure_zamba2_compat(config: NemotronHConfig):
"""Add Zamba2-compatible attribute aliases to NemotronHConfig.
The HF modular NemotronHMamba2Mixer inherits from Zamba2MambaMixer, whose
__init__ reads Zamba2-style attribute names before the NemotronH child
overrides them. We set the missing aliases so the parent __init__ doesn't
crash.
Critically, ``mamba_expand`` must give ``mamba_num_heads * mamba_head_dim``
when multiplied by ``hidden_size``; the config's ``expand`` field does not
satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
"""
correct_intermediate = config.mamba_num_heads * config.mamba_head_dim
correct_expand = correct_intermediate / config.hidden_size
aliases = {
"mamba_d_state": config.ssm_state_size,
"mamba_d_conv": config.conv_kernel,
"mamba_ngroups": config.n_groups,
"mamba_headdim": config.mamba_head_dim,
"n_mamba_heads": config.mamba_num_heads,
"add_bias_linear": getattr(config, "use_bias", False),
"use_mem_eff_path": True,
}
for attr, value in aliases.items():
if not hasattr(config, attr):
setattr(config, attr, value)
config.mamba_expand = correct_expand
class NemotronHMambaLayer(GradientCheckpointingLayer):
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual.
With context parallelism, uses all-to-all head partitioning: transposes
from sequence-parallel to head-parallel before the SSM, so each CP rank
processes the full sequence on a subset of heads, then transposes back.
"""
def __init__(self, config: NemotronHConfig, layer_idx: int):
super().__init__()
_patch_mamba2_use_triton_ssd()
_ensure_zamba2_compat(config)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
self.mamba = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
self.mlp = None # No MoE in this layer type
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
assert self.mamba.num_heads % cp_world_size == 0, (
f"num_heads ({self.mamba.num_heads}) must be divisible by cp_world_size ({cp_world_size})"
)
assert self.mamba.n_groups % cp_world_size == 0, (
f"n_groups ({self.mamba.n_groups}) must be divisible by cp_world_size ({cp_world_size})"
)
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
@property
def cp_enabled(self) -> bool:
return hasattr(self, "_cp_group")
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,
routed_experts: torch.Tensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
if self.cp_enabled:
global_cu_seqlens = (
cu_seqlens if cu_seqlens is not None and cu_seqlens_are_pre_shard else ULYSSES_PARAMS["cu_seqlens"]
)
hidden_states = mamba_cp_forward(
self.mamba,
hidden_states,
self._cp_group,
self._cp_rank,
self._cp_world_size,
global_cu_seqlens,
)
else:
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
return residual + hidden_states
class NemotronHMoE(MoE):
def __init__(self, *, hidden_size: int, latent_size: int, **kwargs):
def __init__(
self,
*,
hidden_size: int,
latent_size: int,
projection_bias: bool,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=False)
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=False)
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=projection_bias)
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=projection_bias)
def prepare_expert_input(self, x: torch.Tensor) -> torch.Tensor:
return self.fc1_latent_proj(x)
def prepare_expert_input(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.fc1_latent_proj(hidden_states)
def prepare_expert_output(self, x: torch.Tensor) -> torch.Tensor:
return self.fc2_latent_proj(x)
def prepare_expert_output(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.fc2_latent_proj(hidden_states)
class NemotronHMoELayer(GradientCheckpointingLayer):
"""MoE layer with latent routed experts."""
def __init__(self, config: NemotronHConfig):
class NemotronHDecoderLayer(nn.Module):
def __init__(self, config: NemotronHConfig, layer_idx: int) -> None:
super().__init__()
self.layer_type = config.layer_types[layer_idx]
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
effective_latent_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
router = TokenChoiceTopKRouter(
dim=config.hidden_size,
num_experts=config.n_routed_experts,
top_k=config.num_experts_per_tok,
score_func="sigmoid",
route_norm=config.norm_topk_prob,
route_scale=config.routed_scaling_factor,
selection_bias=True,
topk_sorted=False,
)
router.fp32_gate = True
experts = GroupedExperts(
dim=effective_latent_dim,
hidden_dim=config.moe_intermediate_size,
num_experts=config.n_routed_experts,
expert_type="non_gated",
activation=config.mlp_hidden_act,
)
shared_expert = FeedForward(
dim=config.hidden_size,
hidden_dim=config.moe_shared_expert_intermediate_size,
expert_type="non_gated",
activation=config.mlp_hidden_act,
)
moe_kwargs = dict(
router=router,
experts=experts,
shared_expert=shared_expert,
score_before_experts=False,
load_balance_coeff=config.load_balance_coeff,
)
if config.moe_latent_size is None:
self.mlp = MoE(**moe_kwargs)
else:
self.mlp = NemotronHMoE(
hidden_size=config.hidden_size,
latent_size=config.moe_latent_size,
**moe_kwargs,
if self.layer_type == "mamba":
self.mamba = NemotronHMamba2(config)
elif self.layer_type == "attention":
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](
AttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
is_causal=True,
attention_bias=config.attention_bias,
output_bias=config.attention_bias,
use_qk_norm=False,
rms_norm_eps=config.layer_norm_epsilon,
)
)
elif self.layer_type == "moe":
router = TokenChoiceTopKRouter(
dim=config.hidden_size,
num_experts=config.n_routed_experts,
top_k=config.num_experts_per_tok,
score_func="sigmoid",
route_norm=config.norm_topk_prob,
route_scale=config.routed_scaling_factor,
selection_bias=True,
topk_sorted=False,
)
expert_size = config.moe_latent_size or config.hidden_size
experts = GroupedExperts(
dim=expert_size,
hidden_dim=config.moe_intermediate_size,
num_experts=config.n_routed_experts,
expert_type="non_gated",
activation=config.mlp_hidden_act,
bias=config.mlp_bias,
)
experts.init_weights(config.initializer_range)
shared_expert = FeedForward(
dim=config.hidden_size,
hidden_dim=config.moe_shared_expert_intermediate_size,
expert_type="non_gated",
activation=config.mlp_hidden_act,
bias=config.mlp_bias,
)
moe_kwargs = {
"router": router,
"experts": experts,
"shared_expert": shared_expert,
"score_before_experts": False,
"load_balance_coeff": config.load_balance_coeff,
}
if config.moe_latent_size is None:
self.mlp = MoE(**moe_kwargs)
else:
self.mlp = NemotronHMoE(
hidden_size=config.hidden_size,
latent_size=config.moe_latent_size,
projection_bias=config.mlp_bias,
**moe_kwargs,
)
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,
cu_seqlens: torch.Tensor,
max_seqlen: int,
routed_experts: torch.Tensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
if self.layer_type == "mamba":
hidden_states = self.mamba(hidden_states, cu_seqlens)
elif self.layer_type == "attention":
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
else:
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
return residual + hidden_states
class NemotronHAttentionLayer(GradientCheckpointingLayer):
"""Attention layer: norm -> FlashAttention/SDPA -> residual."""
def __init__(self, config: NemotronHConfig):
super().__init__()
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
attn_config = AttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
is_causal=True,
attention_bias=config.attention_bias,
use_qk_norm=False,
rms_norm_eps=config.layer_norm_epsilon,
)
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
self.mlp = None # No MoE in this layer type
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,
routed_experts: torch.Tensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
return residual + hidden_states
BLOCK_TYPE_MAP = {
"mamba": NemotronHMambaLayer,
"moe": NemotronHMoELayer,
"attention": NemotronHAttentionLayer,
}
def _build_layer(config: NemotronHConfig, layer_idx: int):
layer_type = config.layers_block_type[layer_idx]
cls = BLOCK_TYPE_MAP[layer_type]
if layer_type == "mamba":
return cls(config, layer_idx=layer_idx)
return cls(config)
@auto_docstring
class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
config: NemotronHConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["NemotronHMambaLayer", "NemotronHMoELayer", "NemotronHAttentionLayer"]
_supports_flash_attn = True
_supports_sdpa = False
_can_compile_fullgraph = False
@classmethod
def cp_support(cls, config) -> CPSupport:
return CPSupport(
frozenset({"ulysses"}),
"ring CP is a softmax-attention algorithm and cannot run this model's Mamba layers, "
"whereas ulysses' all-to-all on Q/K/V leaves the SSM kernel unchanged",
"Mamba layers require Ulysses to reconstruct full sequences while sharding Mamba heads",
)
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.selection_bias"))
def _init_weights(self, module):
std = self.config.initializer_range
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=std)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, (GroupedExperts, TokenChoiceTopKRouter)):
module.init_weights(std)
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mixer." in name for name in state_dict) or any("backbone." in name for name in state_dict)
return is_hf_state_dict(state_dict)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mamba." in name
or "mlp.experts.up_proj" in name
or "self_attn." in name
or "model.embed_tokens." in name
or "model.norm." in name
for name in state_dict
)
return is_prime_state_dict(state_dict)
@classmethod
def conversion_chain(cls, config):
def conversion_chain(cls, config: NemotronHConfig):
return conversion_chain(config)
@classmethod
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
# HF NemotronH unifies attention/mlp under a single `mixer` attribute per layer.
import re
rename = [
(re.compile(r"(\.layers\.\d+)\.mlp\."), r"\1.mixer."),
(re.compile(r"(\.layers\.\d+)\.self_attn\."), r"\1.mixer."),
]
for old_key in list(state_dict.keys()):
new_key = old_key
for pattern, repl in rename:
new_key = pattern.sub(repl, new_key)
if new_key != old_key:
state_dict[new_key] = state_dict.pop(old_key)
for name in list(state_dict):
hf_name = re.sub(r"(\.layers\.\d+)\.(?:self_attn|mlp|mamba)\.", r"\1.mixer.", name)
if hf_name != name:
state_dict[hf_name] = state_dict.pop(name)
return state_dict
class NemotronHModel(NemotronHPreTrainedModel):
def __init__(self, config: NemotronHConfig):
def __init__(self, config: NemotronHConfig) -> None:
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList([_build_layer(config, i) for i in range(config.num_hidden_layers)])
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
self.layers = nn.ModuleList(
NemotronHDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)
)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
# NemotronH does not use RoPE - position information comes from Mamba layers
self.rotary_emb = None
def set_context_parallel_attributes(
self,
process_group: dist.ProcessGroup,
rank: int,
world_size: int,
) -> None:
for module in self.layers.modules():
if isinstance(module, NemotronHMamba2):
module.set_context_parallel_attributes(process_group, rank, world_size)
self.gradient_checkpointing = False
self.post_init()
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
for layer in self.layers.modules():
if isinstance(layer, NemotronHMambaLayer):
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token, indexed by global layer index. Only used for router replay; slots
for non-MoE (Mamba/attention) layers are ignored.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
) -> BaseModelOutput:
hidden_states = self.embed_tokens(input_ids)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
seq_lens.to(device=hidden_states.device),
total_tokens=None if seq_lens_are_pre_shard else hidden_states.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids) if self.rotary_emb is not None else None
for layer_idx, decoder_layer in enumerate(self.layers):
# routed_experts is indexed by global layer index; non-MoE layers ignore it.
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
routed_experts=routed_experts_layer,
cu_seqlens_are_pre_shard=seq_lens_are_pre_shard,
cu_seqlens,
max_seqlen,
routed_experts=layer_routed_experts,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
return BaseModelOutput(last_hidden_state=self.norm(hidden_states))
@auto_docstring
class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config: NemotronHConfig):
class NemotronHForCausalLM(NemotronHPreTrainedModel):
def __init__(self, config: NemotronHConfig) -> None:
super().__init__(config)
self.model = NemotronHModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
self.lm_head = VanillaOutputLinear(config.hidden_size, config.vocab_size)
def get_decoder(self):
return self.model
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def set_context_parallel_attributes(
self,
process_group: dist.ProcessGroup,
rank: int,
world_size: int,
) -> None:
self.model.set_context_parallel_attributes(process_group, rank, world_size)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
logits_to_keep: int = 0,
temperature: Optional[torch.Tensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
labels: torch.LongTensor | None = None,
temperature: torch.Tensor | None = None,
sampling_mask: torch.Tensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs,
) -> PrimeLmOutput:
if position_ids is None:
if inputs_embeds is not None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
else:
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
outputs.last_hidden_state,
labels,
temperature=temperature,
sampling_mask=sampling_mask,
)
def init_buffers_post_meta(self):
pass
def init_buffers_post_meta(self) -> None:
for module in self.modules():
if isinstance(module, MoE):
module.tokens_per_expert.zero_()
module.routing_confidence_sum.zero_()
__all__ = [
"NemotronHDecoderLayer",
"NemotronHForCausalLM",
"NemotronHMoE",
"NemotronHModel",
"NemotronHPreTrainedModel",
]
@@ -1,3 +1,19 @@
from .configuration_qwen3_5 import (
Qwen3_5Config,
Qwen3_5MoeConfig,
Qwen3_5MoeTextConfig,
Qwen3_5TextConfig,
Qwen3_5VisionConfig,
)
from .modeling_qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model, Qwen3_5PreTrainedModel
__all__ = ["Qwen3_5ForCausalLM", "Qwen3_5Model", "Qwen3_5PreTrainedModel"]
__all__ = [
"Qwen3_5Config",
"Qwen3_5ForCausalLM",
"Qwen3_5Model",
"Qwen3_5MoeConfig",
"Qwen3_5MoeTextConfig",
"Qwen3_5PreTrainedModel",
"Qwen3_5TextConfig",
"Qwen3_5VisionConfig",
]
@@ -0,0 +1,86 @@
import torch
from torch import nn
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from prime_rl.trainer.models.qwen3_5.norm import Qwen3_5RMSNorm
class Qwen3_5Attention(FlashAttention):
def __init__(self, config: Qwen3_5TextConfig, attention_implementation: str) -> None:
flash_attn_version = {
"flash_attention_2": 2,
"flash_attention_3": 3,
"flash_attention_4": 4,
}[attention_implementation]
super().__init__(
AttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
is_causal=True,
attention_bias=config.attention_bias,
output_bias=config.attention_bias,
use_qk_norm=False,
rms_norm_eps=config.rms_norm_eps,
),
flash_attn_version=flash_attn_version,
)
self.num_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.attn_output_gate = config.attn_output_gate
q_output_size = self.num_heads * self.head_dim * (2 if self.attn_output_gate else 1)
self.qkv_sizes = (q_output_size, self.qkv_sizes[1], self.qkv_sizes[2])
self.q_proj = nn.Linear(config.hidden_size, q_output_size, bias=config.attention_bias)
self.q_norm = Qwen3_5RMSNorm(self.head_dim, config.rms_norm_eps)
self.k_norm = Qwen3_5RMSNorm(self.head_dim, config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor,
max_seqlen: int,
) -> tuple[torch.Tensor, None]:
batch_size, sequence_length, _ = hidden_states.shape
query_states, key_states, value_states = self.project_qkv(hidden_states)
if self.attn_output_gate:
query_states, output_gate = query_states.view(
batch_size, sequence_length, self.num_heads, self.head_dim * 2
).chunk(2, dim=-1)
output_gate = output_gate.reshape(batch_size, sequence_length, -1)
else:
query_states = query_states.view(batch_size, sequence_length, self.num_heads, self.head_dim)
output_gate = None
key_states = key_states.view(batch_size, sequence_length, self.num_key_value_heads, self.head_dim)
value_states = value_states.view(batch_size, sequence_length, self.num_key_value_heads, self.head_dim)
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(
query_states.transpose(1, 2),
key_states.transpose(1, 2),
cos,
sin,
)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
attention_output = self._compute_attention(
query_states[0],
key_states[0],
value_states[0],
cu_seqlens,
max_seqlen,
).reshape(batch_size, sequence_length, -1)
if output_gate is not None:
attention_output = attention_output * output_gate.sigmoid()
return self.o_proj(attention_output), None
__all__ = ["Qwen3_5Attention"]
@@ -0,0 +1,207 @@
from transformers.configuration_utils import PretrainedConfig
class Qwen3_5TextConfig(PretrainedConfig):
model_type = "qwen3_5_text"
base_config_key = "text_config"
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
def __init__(
self,
vocab_size: int = 248320,
hidden_size: int = 4096,
intermediate_size: int = 12288,
num_hidden_layers: int = 32,
num_attention_heads: int = 16,
num_key_value_heads: int = 4,
head_dim: int = 256,
hidden_act: str = "silu",
max_position_embeddings: int = 32768,
initializer_range: float = 0.02,
rms_norm_eps: float = 1e-6,
rope_theta: float = 10_000.0,
rope_scaling: dict | None = None,
rope_parameters: dict | None = None,
attention_bias: bool = False,
attention_dropout: float = 0.0,
attn_output_gate: bool = True,
output_gate_type: str = "silu",
linear_conv_kernel_dim: int = 4,
linear_key_head_dim: int = 128,
linear_value_head_dim: int = 128,
linear_num_key_heads: int = 16,
linear_num_value_heads: int = 32,
layer_types: list[str] | None = None,
full_attention_interval: int = 4,
mamba_ssm_dtype: str = "float32",
use_cache: bool = True,
pad_token_id: int | None = None,
bos_token_id: int | None = None,
eos_token_id: int | list[int] | None = None,
tie_word_embeddings: bool = False,
**kwargs,
) -> None:
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.head_dim = head_dim
self.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.attn_output_gate = attn_output_gate
self.output_gate_type = output_gate_type
if rope_parameters is None:
rope_parameters = rope_scaling
if rope_parameters is None:
rope_parameters = {
"rope_type": "default",
"rope_theta": rope_theta,
"partial_rotary_factor": kwargs.pop("partial_rotary_factor", 0.25),
"mrope_interleaved": True,
}
self.rope_parameters = dict(rope_parameters)
self.rope_parameters.setdefault("rope_type", "default")
self.rope_parameters.setdefault("rope_theta", rope_theta)
self.rope_parameters.setdefault("partial_rotary_factor", kwargs.pop("partial_rotary_factor", 0.25))
self.rope_parameters.setdefault("mrope_interleaved", True)
self.linear_conv_kernel_dim = linear_conv_kernel_dim
self.linear_key_head_dim = linear_key_head_dim
self.linear_value_head_dim = linear_value_head_dim
self.linear_num_key_heads = linear_num_key_heads
self.linear_num_value_heads = linear_num_value_heads
self.layer_types = layer_types or [
"linear_attention" if (layer_idx + 1) % full_attention_interval else "full_attention"
for layer_idx in range(num_hidden_layers)
]
self.mamba_ssm_dtype = mamba_ssm_dtype
self.use_cache = use_cache
kwargs.pop("mtp_num_hidden_layers", None)
kwargs.pop("mtp_use_dedicated_embeddings", None)
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
class Qwen3_5MoeTextConfig(Qwen3_5TextConfig):
model_type = "qwen3_5_moe_text"
def __init__(
self,
moe_intermediate_size: int = 512,
shared_expert_intermediate_size: int = 512,
num_experts_per_tok: int = 8,
num_experts: int = 256,
output_router_logits: bool = False,
router_aux_loss_coef: float = 0.001,
load_balance_coeff: float | None = None,
**kwargs,
) -> None:
self.moe_intermediate_size = moe_intermediate_size
self.shared_expert_intermediate_size = shared_expert_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.num_experts = num_experts
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
self.load_balance_coeff = load_balance_coeff
kwargs.pop("mlp_only_layers", None)
super().__init__(**kwargs)
class Qwen3_5VisionConfig(PretrainedConfig):
model_type = "qwen3_5_vision"
base_config_key = "vision_config"
def __init__(
self,
depth: int = 27,
hidden_size: int = 1152,
hidden_act: str = "gelu_pytorch_tanh",
intermediate_size: int = 4304,
num_heads: int = 16,
in_channels: int = 3,
patch_size: int = 16,
spatial_merge_size: int = 2,
temporal_patch_size: int = 2,
out_hidden_size: int = 3584,
num_position_embeddings: int = 2304,
initializer_range: float = 0.02,
**kwargs,
) -> None:
self.depth = depth
self.hidden_size = hidden_size
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.num_heads = num_heads
self.in_channels = in_channels
self.patch_size = patch_size
self.spatial_merge_size = spatial_merge_size
self.temporal_patch_size = temporal_patch_size
self.out_hidden_size = out_hidden_size
self.num_position_embeddings = num_position_embeddings
self.initializer_range = initializer_range
kwargs.pop("deepstack_visual_indexes", None)
super().__init__(**kwargs)
class Qwen3_5Config(PretrainedConfig):
model_type = "qwen3_5"
sub_configs = {"vision_config": Qwen3_5VisionConfig, "text_config": Qwen3_5TextConfig}
def __init__(
self,
text_config: dict | PretrainedConfig | None = None,
vision_config: dict | PretrainedConfig | None = None,
image_token_id: int = 248056,
video_token_id: int = 248057,
vision_start_token_id: int = 248053,
vision_end_token_id: int = 248054,
tie_word_embeddings: bool = False,
**kwargs,
) -> None:
self.text_config = (
self.sub_configs["text_config"](**text_config) if isinstance(text_config, dict) else text_config
) or self.sub_configs["text_config"]()
self.vision_config = (
self.sub_configs["vision_config"](**vision_config) if isinstance(vision_config, dict) else vision_config
) or self.sub_configs["vision_config"]()
self.image_token_id = image_token_id
self.video_token_id = video_token_id
self.vision_start_token_id = vision_start_token_id
self.vision_end_token_id = vision_end_token_id
kwargs.pop("language_model_only", None)
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
class Qwen3_5MoeConfig(Qwen3_5Config):
model_type = "qwen3_5_moe"
sub_configs = {"vision_config": Qwen3_5VisionConfig, "text_config": Qwen3_5MoeTextConfig}
def __init__(
self,
text_config: dict | PretrainedConfig | None = None,
vision_config: dict | PretrainedConfig | None = None,
**kwargs,
) -> None:
super().__init__(text_config=text_config, vision_config=vision_config, **kwargs)
__all__ = [
"Qwen3_5Config",
"Qwen3_5MoeConfig",
"Qwen3_5MoeTextConfig",
"Qwen3_5TextConfig",
"Qwen3_5VisionConfig",
]
@@ -0,0 +1,48 @@
from torch import Tensor
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, Rename, SplitConcat
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5MoeTextConfig
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
return any(name == "mtp.fc.weight" or name.endswith("mlp.experts.gate_up_proj") for name in state_dict)
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
if any(name.endswith("mlp.experts.gate_proj") for name in state_dict):
return True
has_qwen_layers = any(name.endswith("linear_attn.A_log") for name in state_dict)
has_fused_experts = any(name.endswith("mlp.experts.gate_up_proj") for name in state_dict)
return has_qwen_layers and not has_fused_experts
def conversion_chain(config) -> list[ConvOp]:
operations: list[ConvOp] = [Drop("mtp.", is_prefix=True)]
text_config = getattr(config, "text_config", config)
if not isinstance(text_config, Qwen3_5MoeTextConfig):
return operations
model_prefix = "model.language_model" if hasattr(config, "vision_config") else "model"
for layer_index in range(text_config.num_hidden_layers):
prefix = f"{model_prefix}.layers.{layer_index}.mlp"
operations.extend(
[
Rename(f"{prefix}.gate.weight", f"{prefix}.router.gate.weight"),
Rename(
f"{prefix}.shared_expert_gate.weight",
f"{prefix}.shared_expert.output_gate.weight",
),
SplitConcat(
combined=f"{prefix}.experts.gate_up_proj",
parts=[
(f"{prefix}.experts.gate_proj", None),
(f"{prefix}.experts.up_proj", None),
],
dim=1,
),
]
)
return operations
__all__ = ["conversion_chain", "is_hf_state_dict", "is_prime_state_dict"]
@@ -0,0 +1,114 @@
import torch
import torch.nn.functional as F
from fla.modules import FusedRMSNormGated
from fla.modules.conv import causal_conv1d
from fla.ops.cp import build_cp_context
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
from torch import nn
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
# FLA's CP convolution uses an all-gather layout that Dynamo cannot trace.
causal_conv1d_with_context_parallelism = torch.compiler.disable(causal_conv1d)
class Qwen3_5GatedDeltaNet(nn.Module):
def __init__(self, config: Qwen3_5TextConfig) -> None:
super().__init__()
self.num_value_heads = config.linear_num_value_heads
self.num_key_heads = config.linear_num_key_heads
self.key_head_dim = config.linear_key_head_dim
self.value_head_dim = config.linear_value_head_dim
self.key_dim = self.key_head_dim * self.num_key_heads
self.value_dim = self.value_head_dim * self.num_value_heads
self.conv_kernel_size = config.linear_conv_kernel_dim
self.activation = config.hidden_act
conv_dim = self.key_dim * 2 + self.value_dim
self.conv1d = nn.Conv1d(
conv_dim,
conv_dim,
kernel_size=self.conv_kernel_size,
groups=conv_dim,
padding=self.conv_kernel_size - 1,
bias=False,
)
self.dt_bias = nn.Parameter(torch.ones(self.num_value_heads))
self.A_log = nn.Parameter(torch.empty(self.num_value_heads).uniform_(0, 16).log_())
self.norm = FusedRMSNormGated(
self.value_head_dim,
eps=config.rms_norm_eps,
activation=config.output_gate_type,
)
self.out_proj = nn.Linear(self.value_dim, config.hidden_size, bias=False)
self.in_proj_qkv = nn.Linear(config.hidden_size, conv_dim, bias=False)
self.in_proj_z = nn.Linear(config.hidden_size, self.value_dim, bias=False)
self.in_proj_b = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
self.in_proj_a = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
self.context_parallel_group = None
self.context_parallel_world_size = 1
def set_context_parallel_attributes(self, process_group, world_size: int) -> None:
self.context_parallel_group = process_group
self.context_parallel_world_size = world_size
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.LongTensor,
) -> torch.Tensor:
batch_size, sequence_length, _ = hidden_states.shape
mixed_qkv = self.in_proj_qkv(hidden_states)
output_gate = self.in_proj_z(hidden_states).reshape(
batch_size, sequence_length, self.num_value_heads, self.value_head_dim
)
beta = self.in_proj_b(hidden_states).sigmoid()
decay = -self.A_log.float().exp() * F.softplus(self.in_proj_a(hidden_states).float() + self.dt_bias)
context = None
if self.context_parallel_group is not None:
context = build_cp_context(
cu_seqlens=cu_seqlens.to(device=hidden_states.device, dtype=torch.int32),
group=self.context_parallel_group,
conv1d_kernel_size=self.conv_kernel_size,
)
convolution = causal_conv1d_with_context_parallelism if context is not None else causal_conv1d
mixed_qkv, _ = convolution(
x=mixed_qkv,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cu_seqlens=cu_seqlens,
cp_context=context,
)
query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
query = query.reshape(batch_size, sequence_length, self.num_key_heads, self.key_head_dim)
key = key.reshape(batch_size, sequence_length, self.num_key_heads, self.key_head_dim)
value = value.reshape(batch_size, sequence_length, self.num_value_heads, self.value_head_dim)
heads_per_key = self.num_value_heads // self.num_key_heads
if heads_per_key > 1:
query = query.repeat_interleave(heads_per_key, dim=2)
key = key.repeat_interleave(heads_per_key, dim=2)
core_output, _ = chunk_gated_delta_rule(
q=query,
k=key,
v=value,
g=decay,
beta=beta,
use_qk_l2norm_in_kernel=True,
cu_seqlens=context.cu_seqlens if context is not None else cu_seqlens,
cp_context=context,
)
core_output = self.norm(
core_output.reshape(-1, self.value_head_dim),
output_gate.reshape(-1, self.value_head_dim),
).reshape(batch_size, sequence_length, self.value_dim)
return self.out_proj(core_output)
__all__ = ["Qwen3_5GatedDeltaNet"]
@@ -1,141 +1,123 @@
import functools
from typing import Optional, Union
import torch
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.configuration_utils import PretrainedConfig
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from transformers.models.qwen3_5.modeling_qwen3_5 import (
Qwen3_5PreTrainedModel as HFQwen3_5PreTrainedModel,
)
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
from transformers.modeling_outputs import BaseModelOutput
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, VanillaOutputLinear
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeGatedAttentionConfig,
Qwen3_5MoeGatedDeltaNet,
Qwen3_5MoeGatedFlashAttention,
Qwen3_5MoeRMSNorm,
Qwen3_5MoeRotaryEmbedding,
normalize_qwen3_5_attn_implementation,
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
from prime_rl.trainer.models.qwen3_5.attention import Qwen3_5Attention
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import (
Qwen3_5MoeTextConfig,
Qwen3_5TextConfig,
)
from prime_rl.trainer.models.qwen3_5_moe.mrope import build_qwen3_5_mrope_position_ids
from prime_rl.trainer.models.qwen3_5.converting_qwen3_5 import (
conversion_chain,
is_hf_state_dict,
is_prime_state_dict,
)
from prime_rl.trainer.models.qwen3_5.gated_delta_net import Qwen3_5GatedDeltaNet
from prime_rl.trainer.models.qwen3_5.norm import Qwen3_5RMSNorm
from prime_rl.trainer.models.qwen3_5.rotary_embedding import (
Qwen3_5RotaryEmbedding,
build_qwen3_5_mrope_position_ids,
)
from prime_rl.trainer.models.qwen3_5.vision import Qwen3_5VisionModel
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
pass
QWEN35_ATTN_IMPL2CLASS = {
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
"flash_attention_4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
}
def _get_gated_attention(config: Qwen3_5TextConfig) -> nn.Module:
attn_config = Qwen3_5MoeGatedAttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
rms_norm_eps=config.rms_norm_eps,
attention_bias=config.attention_bias,
attention_dropout=config.attention_dropout,
)
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
config._attn_implementation = attn_impl
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"Qwen3.5 attention does not support '{config._attn_implementation}'. "
f"Supported implementations: {supported}."
)
return QWEN35_ATTN_IMPL2CLASS[attn_impl](attn_config)
def _create_rotary_emb(config: Qwen3_5TextConfig) -> Qwen3_5MoeRotaryEmbedding:
return Qwen3_5MoeRotaryEmbedding(config)
class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: Qwen3_5TextConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_type = config.layer_types[layer_idx]
if self.layer_type == "linear_attention":
self.linear_attn = Qwen3_5MoeGatedDeltaNet(config)
elif self.layer_type == "full_attention":
self.self_attn = _get_gated_attention(config)
else:
raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}")
self.mlp = FeedForward(
class Qwen3_5SharedExpert(FeedForward):
def __init__(self, config: Qwen3_5MoeTextConfig) -> None:
super().__init__(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
hidden_dim=config.shared_expert_intermediate_size,
expert_type="gated",
activation=config.hidden_act,
)
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.output_gate = nn.Linear(config.hidden_size, 1, bias=False)
def forward(self, hidden_states: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
output = super().forward(hidden_states, routed_experts)
return output * self.output_gate(hidden_states).sigmoid()
class Qwen3_5DecoderLayer(nn.Module):
def __init__(self, config: Qwen3_5TextConfig, layer_index: int) -> None:
super().__init__()
self.layer_type = config.layer_types[layer_index]
if self.layer_type == "linear_attention":
self.linear_attn = Qwen3_5GatedDeltaNet(config)
elif self.layer_type == "full_attention":
self.self_attn = Qwen3_5Attention(config, config._attn_implementation)
if isinstance(config, Qwen3_5MoeTextConfig):
router = TokenChoiceTopKRouter(
dim=config.hidden_size,
num_experts=config.num_experts,
top_k=config.num_experts_per_tok,
score_func="softmax",
route_norm=True,
route_scale=1.0,
selection_bias=config.load_balance_coeff is not None,
)
experts = GroupedExperts(
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
num_experts=config.num_experts,
expert_type="gated",
activation=config.hidden_act,
)
experts.init_weights(config.initializer_range)
self.mlp = MoE(
router=router,
experts=experts,
shared_expert=Qwen3_5SharedExpert(config),
score_before_experts=False,
load_balance_coeff=config.load_balance_coeff,
)
else:
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
expert_type="gated",
activation=config.hidden_act,
)
self.input_layernorm = Qwen3_5RMSNorm(config.hidden_size, config.rms_norm_eps)
self.post_attention_layernorm = Qwen3_5RMSNorm(config.hidden_size, config.rms_norm_eps)
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,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.FloatTensor:
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor,
max_seqlen: int,
routed_experts: torch.LongTensor | None = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
if self.layer_type == "linear_attention":
hidden_states = self.linear_attn(
hidden_states, cu_seqlens=cu_seqlens, cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard
hidden_states,
cu_seqlens,
)
else:
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
hidden_states,
position_embeddings,
cu_seqlens,
max_seqlen,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
return residual + hidden_states
return residual + self.mlp(hidden_states, routed_experts=routed_experts)
class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL):
config_class = Qwen3_5TextConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3_5DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = False
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
_can_record_outputs = {
"hidden_states": Qwen3_5DecoderLayer,
}
@classmethod
def cp_support(cls, config) -> CPSupport:
@@ -144,9 +126,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
if "linear_attention" in (getattr(text_config, "layer_types", None) or ()):
return CPSupport(
frozenset({"ulysses"}),
"ring CP is a softmax-attention algorithm and cannot run this model's DeltaNet "
"layers, whereas ulysses' all-to-all on Q/K/V leaves the linear-attention kernel "
"unchanged",
"DeltaNet layers require Ulysses sequence sharding with FLA boundary-state exchange",
)
return CPSupport(ALL_CP_STYLES)
@@ -154,177 +134,138 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
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 "flash_attention_3")
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"Qwen3.5 attention does not support '{attn_implementation}'. Supported implementations: {supported}."
)
return attn_impl
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
return is_hf_state_dict(state_dict)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
# Dense models use identical key names in HF and PrimeRL format, so we
# never claim to be in a separate PrimeRL format. This disables the
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
return False
return is_prime_state_dict(state_dict)
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
def conversion_chain(cls, config):
return conversion_chain(config)
class Qwen3_5Model(Qwen3_5PreTrainedModel):
def __init__(self, config: Qwen3_5TextConfig):
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
def __init__(self, config: Qwen3_5TextConfig) -> None:
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
self.layers = nn.ModuleList(
[Qwen3_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
Qwen3_5DecoderLayer(config, layer_index) for layer_index in range(config.num_hidden_layers)
)
self.norm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = _create_rotary_emb(config)
self.gradient_checkpointing = False
self.norm = Qwen3_5RMSNorm(config.hidden_size, config.rms_norm_eps)
self.rotary_emb = Qwen3_5RotaryEmbedding(config)
self.post_init()
def get_input_embeddings(self):
def get_input_embeddings(self) -> nn.Embedding:
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.embed_tokens = embeddings
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
for layer in self.layers.modules():
if getattr(layer, "layer_type", None) == "linear_attention":
layer.linear_attn.cp_group = cp_group
layer.linear_attn.cp_rank = cp_rank
layer.linear_attn.cp_world_size = cp_world_size
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
self.context_parallel_group = process_group
self.context_parallel_rank = rank
self.context_parallel_world_size = world_size
for module in self.modules():
if isinstance(module, Qwen3_5GatedDeltaNet):
module.set_context_parallel_attributes(process_group, world_size)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
input_ids: torch.LongTensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.Tensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
) -> BaseModelOutput:
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device),
seq_lens.to(inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
cu_seqlens_are_pre_shard = seq_lens_are_pre_shard
for decoder_layer in self.layers:
for layer_index, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_index] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard,
position_embeddings,
cu_seqlens,
max_seqlen,
routed_experts=layer_routed_experts,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
return BaseModelOutput(last_hidden_state=self.norm(hidden_states))
class Qwen3_5VLMModel(nn.Module):
"""Composite VLM body: HF vision encoder + custom PrimeRL dense text model."""
def __init__(self, config: PretrainedConfig):
def __init__(self, config) -> None:
super().__init__()
self.config = config
self.visual = Qwen3_5VisionModel._from_config(config.vision_config)
self.visual = Qwen3_5VisionModel(config.vision_config)
self.language_model = Qwen3_5Model(config.text_config)
def get_input_embeddings(self):
def get_input_embeddings(self) -> nn.Embedding:
return self.language_model.get_input_embeddings()
def set_input_embeddings(self, value):
self.language_model.set_input_embeddings(value)
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.language_model.set_input_embeddings(embeddings)
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self.language_model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
self.language_model.set_context_parallel_attributes(process_group, rank, world_size)
def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
vcfg = self.config.vision_config
m = vcfg.spatial_merge_size
num_patches = m * m
patch_dim = vcfg.in_channels * vcfg.temporal_patch_size * vcfg.patch_size * vcfg.patch_size
pixel_values = torch.zeros(num_patches, patch_dim, device=device, dtype=self.visual.dtype)
grid_thw = torch.tensor([[1, m, m]], dtype=torch.long, device=device)
return pixel_values, grid_thw
def prepare_inputs_embeds_and_position_ids(
def prepare_inputs(
self,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
*,
position_ids: torch.LongTensor | None,
pixel_values: torch.Tensor | None,
image_grid_thw: torch.LongTensor | None,
mm_token_type_ids: torch.LongTensor | None,
seq_lens: torch.LongTensor,
) -> tuple[torch.FloatTensor, torch.LongTensor]:
) -> tuple[torch.Tensor, torch.LongTensor]:
inputs_embeds = self.language_model.embed_tokens(input_ids)
has_images = pixel_values is not None
vision_grid_thw = image_grid_thw
vision_grid = image_grid_thw
if has_images:
pixel_values = pixel_values.type(self.visual.dtype)
pixel_values = pixel_values.to(self.visual.dtype)
else:
pixel_values, vision_grid_thw = self._dummy_vision_inputs(inputs_embeds.device)
vision_output = self.visual(pixel_values, grid_thw=vision_grid_thw, return_dict=True)
image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype)
merge_size = self.config.vision_config.spatial_merge_size
num_patches = merge_size**2
patch_dim = (
self.config.vision_config.in_channels
* self.config.vision_config.temporal_patch_size
* self.config.vision_config.patch_size**2
)
pixel_values = torch.zeros(
num_patches,
patch_dim,
device=inputs_embeds.device,
dtype=self.visual.dtype,
)
vision_grid = torch.tensor([[1, merge_size, merge_size]], device=inputs_embeds.device)
image_embeds = self.visual(pixel_values, vision_grid).pooler_output.to(inputs_embeds.dtype)
if has_images:
image_mask = input_ids == self.config.image_token_id
image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
else:
# Every rank must retain the vision graph so FSDP collectives stay symmetric.
inputs_embeds = inputs_embeds + image_embeds.sum() * 0.0
if position_ids is None:
if image_grid_thw is not None:
if image_grid_thw is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
else:
if mm_token_type_ids is None:
raise ValueError("mm_token_type_ids are required with Qwen3.5 image inputs")
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
@@ -332,9 +273,6 @@ class Qwen3_5VLMModel(nn.Module):
spatial_merge_size=self.config.vision_config.spatial_merge_size,
seq_lens=seq_lens,
)
else:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
return inputs_embeds, position_ids
def forward(
@@ -344,105 +282,86 @@ class Qwen3_5VLMModel(nn.Module):
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=seq_lens,
) -> BaseModelOutput:
inputs_embeds, position_ids = self.prepare_inputs(
input_ids,
position_ids,
pixel_values,
image_grid_thw,
mm_token_type_ids,
seq_lens,
)
cp_group = getattr(self.language_model, "_cp_group", None)
if image_grid_thw is not None and cp_group is not None:
cp_rank = self.language_model._cp_rank
cp_world_size = self.language_model._cp_world_size
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style="ulysses", seq_lens=seq_lens)
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=cp_rank, cp_world_size=cp_world_size)
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
process_group = getattr(self.language_model, "context_parallel_group", None)
if image_grid_thw is not None and process_group is not None:
rank = self.language_model.context_parallel_rank
world_size = self.language_model.context_parallel_world_size
setup_cp_attention_params(position_ids, cp_group=process_group, cp_style="ulysses", seq_lens=seq_lens)
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=rank, cp_world_size=world_size)
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=rank, cp_world_size=world_size)
if routed_experts is not None:
routed_experts = shard_for_cp(routed_experts, cp_rank=rank, cp_world_size=world_size)
seq_lens_are_pre_shard = True
return self.language_model(
inputs_embeds=inputs_embeds,
position_ids=position_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
"""Unified dense Qwen3.5 model for both text-only and VLM configs."""
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel):
def __init__(self, config) -> None:
super().__init__(config)
self.is_vlm = hasattr(config, "vision_config")
text_config = config.text_config if self.is_vlm else config
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_checkpoint_conversion_mapping = {}
_tp_plan = {"lm_head": "colwise_gather_output"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
self._is_vlm = hasattr(config, "vision_config")
self.supports_packed_multimodal_training = self._is_vlm
if self._is_vlm:
if self.is_vlm:
self.model = Qwen3_5VLMModel(config)
text_config = config.text_config
self._tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
else:
self.model = Qwen3_5Model(config)
text_config = config
self.vocab_size = text_config.vocab_size
self.lm_head = nn.Linear(text_config.hidden_size, text_config.vocab_size, bias=False)
self.post_init()
self.supports_packed_multimodal_training = self.is_vlm
self.lm_head = VanillaOutputLinear(text_config.hidden_size, text_config.vocab_size)
def get_input_embeddings(self):
def get_input_embeddings(self) -> nn.Embedding:
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
self.model.set_input_embeddings(value)
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.model.set_input_embeddings(embeddings)
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
self.model.set_context_parallel_attributes(process_group, rank, world_size)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Union[torch.Tensor, None] = None,
pixel_values: Optional[torch.Tensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
mm_token_type_ids: Optional[torch.LongTensor] = None,
input_ids: torch.LongTensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.Tensor | None = None,
labels: torch.LongTensor | None = None,
temperature: torch.Tensor | None = None,
sampling_mask: torch.Tensor | None = None,
routed_experts: torch.LongTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now"
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5 for now"
if self._is_vlm:
if self.is_vlm:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
@@ -451,42 +370,35 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
outputs.last_hidden_state,
labels,
temperature=temperature,
sampling_mask=sampling_mask,
)
def init_buffers_post_meta(self):
if self._is_vlm:
lm_rope = self.model.language_model.rotary_emb
else:
lm_rope = self.model.rotary_emb
if hasattr(lm_rope, "rope_init_fn"):
inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device)
lm_rope.inv_freq.copy_(inv_freq)
if self._is_vlm:
vis_rope = self.model.visual.rotary_pos_emb
if hasattr(vis_rope, "inv_freq"):
dim = vis_rope.inv_freq.shape[0]
inv_freq = 1.0 / (
10000.0
** (torch.arange(0, dim * 2, 2, dtype=torch.float32, device=vis_rope.inv_freq.device) / (dim * 2))
)
vis_rope.inv_freq.copy_(inv_freq)
def init_buffers_post_meta(self) -> None:
language_model = self.model.language_model if self.is_vlm else self.model
language_model.rotary_emb.reset_parameters()
if self.is_vlm:
self.model.visual.rotary_pos_emb.reset_parameters()
for module in self.modules():
if isinstance(module, MoE):
module.tokens_per_expert.zero_()
module.routing_confidence_sum.zero_()
if module.router.selection_bias is not None:
module.router.selection_bias.zero_()
__all__ = [
"Qwen3_5Attention",
"Qwen3_5DecoderLayer",
"Qwen3_5ForCausalLM",
"Qwen3_5GatedFlashAttention",
"Qwen3_5Model",
"Qwen3_5PreTrainedModel",
]
@@ -0,0 +1,25 @@
import torch
from torch import nn
class Qwen3_5RMSNorm(nn.Module):
"""Qwen's zero-centered RMSNorm, whose effective scale is ``1 + weight``."""
def __init__(self, hidden_size: int, eps: float) -> None:
super().__init__()
self.weight = nn.Parameter(torch.empty(hidden_size))
self.variance_epsilon = eps
self.reset_parameters()
def reset_parameters(self) -> None:
nn.init.zeros_(self.weight)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.float()
variance = hidden_states.square().mean(dim=-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return ((1.0 + self.weight.float()) * hidden_states).to(input_dtype)
__all__ = ["Qwen3_5RMSNorm"]
@@ -0,0 +1,172 @@
import itertools
import torch
from torch import nn
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
class Qwen3_5RotaryEmbedding(nn.Module):
inv_freq: torch.Tensor
def __init__(self, config: Qwen3_5TextConfig, device=None) -> None:
super().__init__()
self.config = config
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.rope_type = config.rope_parameters["rope_type"]
self.rope_init_fn = self.compute_default_rope_parameters
if self.rope_type != "default":
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn(config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
self.mrope_section = config.rope_parameters.get("mrope_section")
if self.mrope_section is None:
self.mrope_section = self.scaled_mrope_section(inv_freq.numel())
@staticmethod
def scaled_mrope_section(num_rotary_pairs: int) -> list[int]:
default_section = [11, 11, 10]
total = sum(default_section)
section = [num_rotary_pairs * size // total for size in default_section]
remainder_order = sorted(
range(len(section)),
key=lambda index: num_rotary_pairs * default_section[index] % total,
reverse=True,
)
for index in remainder_order[: num_rotary_pairs - sum(section)]:
section[index] += 1
return section
@staticmethod
def compute_default_rope_parameters(
config: Qwen3_5TextConfig,
device: torch.device | None = None,
seq_len: int | None = None,
) -> tuple[torch.Tensor, float]:
del seq_len
rope_parameters = config.rope_parameters
rotary_dim = int(config.head_dim * rope_parameters.get("partial_rotary_factor", 1.0))
positions = torch.arange(0, rotary_dim, 2, dtype=torch.int64, device=device).float()
return 1.0 / (rope_parameters["rope_theta"] ** (positions / rotary_dim)), 1.0
def reset_parameters(self) -> None:
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, self.inv_freq.device)
self.inv_freq.copy_(inv_freq)
self.original_inv_freq.copy_(inv_freq)
@torch.no_grad()
@dynamic_rope_update
def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
if position_ids.ndim == 2:
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
position_ids = position_ids.to(hidden_states.device)
inv_freq = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
positions = position_ids[:, :, None, :].float()
device_type = hidden_states.device.type if hidden_states.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False):
frequencies = (inv_freq @ positions).transpose(2, 3)
interleaved = frequencies[0].clone()
for dimension, offset in enumerate((1, 2), start=1):
index = slice(offset, self.mrope_section[dimension] * 3, 3)
interleaved[..., index] = frequencies[dimension, ..., index]
embeddings = torch.cat((interleaved, interleaved), dim=-1)
cos = embeddings.cos() * self.attention_scaling
sin = embeddings.sin() * self.attention_scaling
return cos.to(hidden_states.dtype), sin.to(hidden_states.dtype)
def get_qwen3_5_vision_position_ids(
*,
start_position: int,
grid_thw: torch.Tensor,
spatial_merge_size: int,
temporal_merge_size: int = 1,
time_interval: int = 1,
device: torch.device | None = None,
) -> torch.LongTensor:
grid_t = int(grid_thw[0].item()) // temporal_merge_size
grid_h = int(grid_thw[1].item()) // spatial_merge_size
grid_w = int(grid_thw[2].item()) // spatial_merge_size
temporal = torch.arange(grid_t, device=device) * time_interval + start_position
height = torch.arange(grid_h, device=device) + start_position
width = torch.arange(grid_w, device=device) + start_position
return torch.stack(
[
temporal.repeat_interleave(grid_h * grid_w),
height.repeat_interleave(grid_w).repeat(grid_t),
width.repeat(grid_h * grid_t),
],
dim=0,
)
def build_qwen3_5_mrope_position_ids(
*,
input_ids: torch.LongTensor,
mm_token_type_ids: torch.LongTensor,
image_grid_thw: torch.LongTensor | None,
spatial_merge_size: int,
seq_lens: torch.Tensor,
) -> torch.LongTensor:
seq_lens = seq_lens.to(device=input_ids.device, dtype=torch.long)
image_grids = iter(image_grid_thw) if image_grid_thw is not None else None
position_ids = torch.empty(3, 1, input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device)
offset = 0
for sequence_length_tensor in seq_lens:
sequence_length = int(sequence_length_tensor)
token_types = mm_token_type_ids[0, offset : offset + sequence_length]
current_position = 0
sequence_positions = []
for modality, indexed_group in itertools.groupby(enumerate(token_types.tolist()), lambda item: item[1]):
group = list(indexed_group)
group_length = group[-1][0] - group[0][0] + 1
if modality == 0:
text_positions = torch.arange(group_length, device=input_ids.device) + current_position
sequence_positions.append(text_positions.unsqueeze(0).expand(3, -1))
current_position += group_length
continue
if modality == 2:
raise ValueError("Qwen3.5 video MRoPE is not supported")
if modality != 1:
raise ValueError(f"Unsupported Qwen3.5 multimodal token type: {modality}")
if image_grids is None:
raise ValueError("image_grid_thw is required for image tokens")
remaining = group_length
while remaining:
grid = next(image_grids, None)
if grid is None:
raise ValueError("Not enough image_grid_thw rows for the image tokens")
image_positions = get_qwen3_5_vision_position_ids(
start_position=current_position,
grid_thw=grid,
spatial_merge_size=spatial_merge_size,
device=input_ids.device,
)
if image_positions.shape[1] > remaining:
raise ValueError("Image token group length does not match image_grid_thw")
sequence_positions.append(image_positions)
current_position += max(int(grid[1]), int(grid[2])) // spatial_merge_size
remaining -= image_positions.shape[1]
positions = torch.cat(sequence_positions, dim=1)
if positions.shape[1] != sequence_length:
raise ValueError("Built MRoPE positions do not match the packed sequence length")
position_ids[:, 0, offset : offset + sequence_length] = positions
offset += sequence_length
if image_grids is not None and next(image_grids, None) is not None:
raise ValueError("image_grid_thw contains unused rows")
return position_ids
__all__ = ["Qwen3_5RotaryEmbedding", "build_qwen3_5_mrope_position_ids", "get_qwen3_5_vision_position_ids"]
@@ -0,0 +1,263 @@
import math
import torch
import torch.nn.functional as F
from torch import nn
from transformers.modeling_outputs import BaseModelOutputWithPooling
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
flash_attn_varlen_func,
)
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5VisionConfig
class Qwen3_5VisionRotaryEmbedding(nn.Module):
def __init__(self, dim: int, theta: float = 10_000.0) -> None:
super().__init__()
self.dim = dim
self.theta = theta
self.register_buffer("inv_freq", torch.empty(dim // 2), persistent=False)
self.reset_parameters()
def reset_parameters(self) -> None:
positions = torch.arange(0, self.dim, 2, dtype=torch.float32, device=self.inv_freq.device)
self.inv_freq.copy_(1.0 / (self.theta ** (positions / self.dim)))
def forward(self, sequence_length: int) -> torch.Tensor:
positions = torch.arange(sequence_length, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
return torch.outer(positions, self.inv_freq)
class Qwen3_5VisionPatchEmbed(nn.Module):
def __init__(self, config: Qwen3_5VisionConfig) -> None:
super().__init__()
self.in_channels = config.in_channels
self.temporal_patch_size = config.temporal_patch_size
self.patch_size = config.patch_size
kernel_size = (self.temporal_patch_size, self.patch_size, self.patch_size)
self.proj = nn.Conv3d(
self.in_channels,
config.hidden_size,
kernel_size=kernel_size,
stride=kernel_size,
bias=True,
)
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
pixel_values = pixel_values.view(
-1,
self.in_channels,
self.temporal_patch_size,
self.patch_size,
self.patch_size,
)
return self.proj(pixel_values.to(self.proj.weight.dtype)).view(pixel_values.shape[0], -1)
class Qwen3_5VisionMLP(nn.Module):
def __init__(self, config: Qwen3_5VisionConfig) -> None:
super().__init__()
self.linear_fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
self.linear_fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.linear_fc2(F.gelu(self.linear_fc1(hidden_states), approximate="tanh"))
class Qwen3_5VisionAttention(nn.Module):
FLASH_ATTENTION_FUNCTIONS = {
"flash_attention_2": flash_attn_varlen_func,
"flash_attention_3": flash_attn_3_varlen_func,
"flash_attention_4": flash_attn_4_varlen_func,
}
def __init__(self, config: Qwen3_5VisionConfig) -> None:
super().__init__()
self.num_heads = config.num_heads
self.head_dim = config.hidden_size // config.num_heads
self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=True)
self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
self.attention_implementation = config._attn_implementation
self.flash_attention = self.FLASH_ATTENTION_FUNCTIONS[self.attention_implementation]
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.IntTensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
sequence_length = hidden_states.shape[0]
query, key, value = (
self.qkv(hidden_states).view(sequence_length, 3, self.num_heads, self.head_dim).unbind(dim=1)
)
cos, sin = position_embeddings
cos = cos.unsqueeze(1).float()
sin = sin.unsqueeze(1).float()
query_dtype = query.dtype
query = ((query.float() * cos) + (rotate_half(query.float()) * sin)).to(query_dtype)
key = ((key.float() * cos) + (rotate_half(key.float()) * sin)).to(query_dtype)
if self.attention_implementation == "flash_attention_4":
attention_output, _ = self.flash_attention(
query,
key,
value,
cu_seqlens_q=cu_seqlens,
cu_seqlens_k=cu_seqlens,
causal=False,
)
else:
max_sequence_length = int((cu_seqlens[1:] - cu_seqlens[:-1]).max())
attention_output = self.flash_attention(
query,
key,
value,
cu_seqlens,
cu_seqlens,
max_sequence_length,
max_sequence_length,
causal=False,
)
return self.proj(attention_output.reshape(sequence_length, -1))
class Qwen3_5VisionBlock(nn.Module):
def __init__(self, config: Qwen3_5VisionConfig) -> None:
super().__init__()
self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.attn = Qwen3_5VisionAttention(config)
self.mlp = Qwen3_5VisionMLP(config)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.IntTensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
hidden_states = hidden_states + self.attn(self.norm1(hidden_states), cu_seqlens, position_embeddings)
return hidden_states + self.mlp(self.norm2(hidden_states))
class Qwen3_5VisionPatchMerger(nn.Module):
def __init__(self, config: Qwen3_5VisionConfig) -> None:
super().__init__()
merged_hidden_size = config.hidden_size * config.spatial_merge_size**2
self.merged_hidden_size = merged_hidden_size
self.norm = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.linear_fc1 = nn.Linear(merged_hidden_size, merged_hidden_size)
self.linear_fc2 = nn.Linear(merged_hidden_size, config.out_hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.norm(hidden_states).view(-1, self.merged_hidden_size)
return self.linear_fc2(F.gelu(self.linear_fc1(hidden_states)))
class Qwen3_5VisionModel(nn.Module):
def __init__(self, config: Qwen3_5VisionConfig) -> None:
super().__init__()
self.config = config
self.spatial_merge_size = config.spatial_merge_size
self.patch_embed = Qwen3_5VisionPatchEmbed(config)
self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size)
self.num_grid_per_side = math.isqrt(config.num_position_embeddings)
self.rotary_pos_emb = Qwen3_5VisionRotaryEmbedding(config.hidden_size // config.num_heads // 2)
self.blocks = nn.ModuleList(Qwen3_5VisionBlock(config) for _ in range(config.depth))
self.merger = Qwen3_5VisionPatchMerger(config)
@property
def dtype(self) -> torch.dtype:
return self.patch_embed.proj.weight.dtype
def rotary_embeddings(self, grid_thw: torch.Tensor) -> torch.Tensor:
grids = grid_thw.tolist()
frequency_table = self.rotary_pos_emb(max(max(height, width) for _, height, width in grids))
coordinates = []
merge_size = self.spatial_merge_size
for frames, height, width in grids:
block_rows = torch.arange(height // merge_size, device=frequency_table.device)
block_columns = torch.arange(width // merge_size, device=frequency_table.device)
intra_rows = torch.arange(merge_size, device=frequency_table.device)
intra_columns = torch.arange(merge_size, device=frequency_table.device)
rows = block_rows[:, None, None, None] * merge_size + intra_rows[None, None, :, None]
columns = block_columns[None, :, None, None] * merge_size + intra_columns[None, None, None, :]
rows = rows.expand(height // merge_size, width // merge_size, merge_size, merge_size).reshape(-1)
columns = columns.expand(height // merge_size, width // merge_size, merge_size, merge_size).reshape(-1)
coordinates.append(torch.stack((rows, columns), dim=-1).repeat(frames, 1))
return frequency_table[torch.cat(coordinates)].flatten(1)
def interpolated_position_embeddings(self, grid_thw: torch.Tensor) -> torch.Tensor:
embeddings = []
merge_size = self.spatial_merge_size
for frames, height, width in grid_thw.tolist():
row_positions = torch.linspace(
0,
self.num_grid_per_side - 1,
height,
device=self.pos_embed.weight.device,
)
column_positions = torch.linspace(
0,
self.num_grid_per_side - 1,
width,
device=self.pos_embed.weight.device,
)
row_floor = row_positions.floor().long()
column_floor = column_positions.floor().long()
row_ceil = (row_floor + 1).clamp_max(self.num_grid_per_side - 1)
column_ceil = (column_floor + 1).clamp_max(self.num_grid_per_side - 1)
row_fraction = row_positions - row_floor
column_fraction = column_positions - column_floor
indices = torch.stack(
[
(row_floor[:, None] * self.num_grid_per_side + column_floor[None, :]).flatten(),
(row_floor[:, None] * self.num_grid_per_side + column_ceil[None, :]).flatten(),
(row_ceil[:, None] * self.num_grid_per_side + column_floor[None, :]).flatten(),
(row_ceil[:, None] * self.num_grid_per_side + column_ceil[None, :]).flatten(),
]
)
weights = torch.stack(
[
((1 - row_fraction)[:, None] * (1 - column_fraction)[None, :]).flatten(),
((1 - row_fraction)[:, None] * column_fraction[None, :]).flatten(),
(row_fraction[:, None] * (1 - column_fraction)[None, :]).flatten(),
(row_fraction[:, None] * column_fraction[None, :]).flatten(),
]
).to(self.pos_embed.weight.dtype)
position_embedding = (self.pos_embed(indices) * weights[..., None]).sum(dim=0).repeat(frames, 1)
position_embedding = (
position_embedding.view(
frames,
height // merge_size,
merge_size,
width // merge_size,
merge_size,
-1,
)
.permute(0, 1, 3, 2, 4, 5)
.flatten(0, 4)
)
embeddings.append(position_embedding)
return torch.cat(embeddings)
def forward(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor) -> BaseModelOutputWithPooling:
hidden_states = self.patch_embed(pixel_values)
hidden_states = hidden_states + self.interpolated_position_embeddings(grid_thw)
rotary = self.rotary_embeddings(grid_thw)
rotary = torch.cat((rotary, rotary), dim=-1)
position_embeddings = (rotary.cos(), rotary.sin())
sequence_lengths = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0])
cu_seqlens = F.pad(sequence_lengths.cumsum(dim=0, dtype=torch.int32), (1, 0))
for block in self.blocks:
hidden_states = block(hidden_states, cu_seqlens, position_embeddings)
return BaseModelOutputWithPooling(
last_hidden_state=hidden_states,
pooler_output=self.merger(hidden_states),
)
__all__ = ["Qwen3_5VisionModel"]
@@ -1,13 +0,0 @@
from prime_rl.trainer.models.qwen3_5_moe.configuration_qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForCausalLM,
Qwen3_5MoeModel,
Qwen3_5MoePreTrainedModel,
)
__all__ = [
"Qwen3_5MoeConfig",
"Qwen3_5MoeForCausalLM",
"Qwen3_5MoeModel",
"Qwen3_5MoePreTrainedModel",
]
@@ -1,106 +0,0 @@
from transformers.configuration_utils import PretrainedConfig
class Qwen3_5MoeConfig(PretrainedConfig):
r"""
Configuration class for the custom PrimeRL Qwen3.5-MoE model.
This matches the HuggingFace `Qwen3_5MoeTextConfig` architecture:
hybrid attention (GatedDeltaNet linear + gated softmax), MoE with gated shared expert,
and (1+weight) RMSNorm parameterization.
Defaults match Qwen3.5-35B-A3B.
"""
model_type = "qwen3_5_moe_text"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size=248320,
hidden_size=2048,
num_hidden_layers=40,
num_attention_heads=16,
num_key_value_heads=2,
hidden_act="silu",
max_position_embeddings=32768,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
rope_scaling=None,
attention_bias=False,
attention_dropout=0.0,
head_dim=256,
# Linear attention (GatedDeltaNet) params
linear_conv_kernel_dim=4,
linear_key_head_dim=128,
linear_value_head_dim=128,
linear_num_key_heads=16,
linear_num_value_heads=32,
# MoE params
moe_intermediate_size=512,
shared_expert_intermediate_size=512,
num_experts_per_tok=8,
num_experts=256,
output_router_logits=False,
router_aux_loss_coef=0.001,
# Layer type configuration
layer_types=None,
# PrimeRL additions
load_balance_coeff=None,
pad_token_id=None,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.head_dim = head_dim
self.pad_token_id = pad_token_id
# Partial RoPE: only rotate 25% of head_dim
kwargs.setdefault("partial_rotary_factor", 0.25)
# Layer types: default every 4th layer is full_attention, rest linear_attention
self.layer_types = layer_types
if self.layer_types is None:
interval_pattern = kwargs.pop("full_attention_interval", 4)
self.layer_types = [
"linear_attention" if bool((i + 1) % interval_pattern) else "full_attention"
for i in range(self.num_hidden_layers)
]
# Linear attention (GatedDeltaNet) params
self.linear_conv_kernel_dim = linear_conv_kernel_dim
self.linear_key_head_dim = linear_key_head_dim
self.linear_value_head_dim = linear_value_head_dim
self.linear_num_key_heads = linear_num_key_heads
self.linear_num_value_heads = linear_num_value_heads
# MoE params
self.moe_intermediate_size = moe_intermediate_size
self.shared_expert_intermediate_size = shared_expert_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.num_experts = num_experts
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
# PrimeRL additions
self.load_balance_coeff = load_balance_coeff
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@@ -1,25 +0,0 @@
"""HF<->prime weight conversion for Qwen3.5-MoE, as a declarative op chain.
Per layer: the router and shared-expert output gate are nested under their
PrimeRL modules, and routed experts use stacked canonical projections.
"""
from __future__ import annotations
from prime_rl.trainer.models.conversion_ops import ConvOp, Rename, routed_experts_op
def _conversion_chain(config, model_prefix: str) -> list[ConvOp]:
ops: list[ConvOp] = []
for i in range(config.num_hidden_layers):
p = f"{model_prefix}.layers.{i}"
# Router: mlp.gate.weight -> mlp.router.gate.weight
ops.append(Rename(f"{p}.mlp.gate.weight", f"{p}.mlp.router.gate.weight"))
ops.append(Rename(f"{p}.mlp.shared_expert_gate.weight", f"{p}.mlp.shared_expert.output_gate.weight"))
ops.append(routed_experts_op(p, hf_experts="mlp.experts", prime_experts="mlp.experts", fused=True))
return ops
def conversion_chain(config) -> list[ConvOp]:
text_config = getattr(config, "text_config", config)
return _conversion_chain(text_config, "model") + _conversion_chain(text_config, "model.language_model")
File diff suppressed because it is too large Load Diff
@@ -1,130 +0,0 @@
from __future__ import annotations
import itertools
import torch
def get_qwen3_5_vision_position_ids(
*,
start_position: int,
grid_thw: torch.Tensor,
spatial_merge_size: int,
temp_merge_size: int = 1,
time_interval: int = 1,
device: torch.device | None = None,
) -> torch.LongTensor:
llm_grid_t = int(grid_thw[0].item()) // temp_merge_size
llm_grid_h = int(grid_thw[1].item()) // spatial_merge_size
llm_grid_w = int(grid_thw[2].item()) // spatial_merge_size
position_temporal = torch.arange(llm_grid_t, device=device) * time_interval
position_height = torch.arange(llm_grid_h, device=device) + start_position
position_width = torch.arange(llm_grid_w, device=device) + start_position
position_width = position_width.repeat(llm_grid_h * llm_grid_t)
position_height = position_height.repeat_interleave(llm_grid_w).repeat(llm_grid_t)
position_temporal = position_temporal.repeat_interleave(llm_grid_h * llm_grid_w) + start_position
return torch.stack([position_temporal, position_height, position_width], dim=0)
def build_qwen3_5_mrope_position_ids(
*,
input_ids: torch.LongTensor,
mm_token_type_ids: torch.LongTensor,
image_grid_thw: torch.LongTensor | None,
spatial_merge_size: int,
seq_lens: torch.Tensor,
) -> torch.LongTensor:
if input_ids.ndim != 2:
raise ValueError(f"input_ids must be 2D, got shape={tuple(input_ids.shape)}")
if mm_token_type_ids.shape != input_ids.shape:
raise ValueError(
"mm_token_type_ids must match input_ids shape: "
f"mm_token_type_ids={tuple(mm_token_type_ids.shape)}, input_ids={tuple(input_ids.shape)}"
)
if input_ids.shape[0] != 1:
raise ValueError("Packed Qwen3.5 MRoPE builder currently supports batch size 1")
total_seq_len = input_ids.shape[1]
seq_lens = seq_lens.to(device=input_ids.device, dtype=torch.long)
if seq_lens.ndim != 1:
raise ValueError(f"seq_lens must be 1D, got shape={tuple(seq_lens.shape)}")
if bool((seq_lens <= 0).any().item()):
raise ValueError(f"seq_lens must be positive, got {seq_lens.tolist()}")
if int(seq_lens.sum().item()) != total_seq_len:
raise ValueError(f"seq_lens sum must equal sequence length: {seq_lens.tolist()} vs {total_seq_len}")
image_grids = iter(image_grid_thw) if image_grid_thw is not None else None
all_positions = torch.empty(3, 1, total_seq_len, dtype=input_ids.dtype, device=input_ids.device)
offset = 0
for seq_len_tensor in seq_lens:
seq_len = int(seq_len_tensor.item())
token_types = mm_token_type_ids[0, offset : offset + seq_len]
current_pos = 0
segment_positions = []
for modality_type, group in itertools.groupby(enumerate(token_types.tolist()), lambda item: item[1]):
group = list(group)
group_len = group[-1][0] - group[0][0] + 1
if modality_type == 0:
segment_positions.append(
torch.arange(group_len, device=input_ids.device).view(1, -1).expand(3, -1) + current_pos
)
current_pos += group_len
continue
if modality_type == 2:
raise ValueError("Qwen3.5 video MRoPE is not supported by the custom trainer path yet")
if modality_type != 1:
raise ValueError(f"Unsupported Qwen3.5 multimodal token type: {modality_type}")
if image_grids is None:
raise ValueError("image_grid_thw is required when mm_token_type_ids contains image tokens")
remaining = group_len
while remaining > 0:
try:
grid_thw = next(image_grids)
except StopIteration as exc:
raise ValueError("Not enough image_grid_thw rows for image token groups") from exc
vision_positions = get_qwen3_5_vision_position_ids(
start_position=current_pos,
grid_thw=grid_thw,
spatial_merge_size=spatial_merge_size,
device=input_ids.device,
)
image_len = vision_positions.shape[1]
if image_len > remaining:
raise ValueError(
"Image token group length does not match image_grid_thw-derived token count: "
f"group_len={group_len}, grid_thw={grid_thw.tolist()}, "
f"derived={image_len}, spatial_merge_size={spatial_merge_size}"
)
segment_positions.append(vision_positions)
current_pos += max(int(grid_thw[1].item()), int(grid_thw[2].item())) // spatial_merge_size
remaining -= image_len
if not segment_positions:
raise ValueError("Cannot build MRoPE positions for an empty sequence segment")
segment_position_ids = torch.cat(segment_positions, dim=1)
if segment_position_ids.shape[1] != seq_len:
raise ValueError(
f"Built MRoPE length does not match segment length: {segment_position_ids.shape[1]} vs {seq_len}"
)
all_positions[:, 0, offset : offset + seq_len] = segment_position_ids
offset += seq_len
if image_grids is not None:
try:
extra_grid = next(image_grids)
except StopIteration:
pass
else:
raise ValueError(f"Unused image_grid_thw row while building MRoPE positions: {extra_grid.tolist()}")
return all_positions
+21 -4
View File
@@ -28,6 +28,7 @@ from prime_rl.trainer.models.layers.grouped_gemm import (
from prime_rl.trainer.models.layers.moe import MoE
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_language_model
def _resolve_grouped_gemm(config: ModelConfig) -> GroupedGemm:
@@ -62,11 +63,27 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
raise ValueError("A non-default model.moe runtime was configured, but the model has no custom MoE layers.")
return
grouped_gemm = _resolve_grouped_gemm(config)
selected_moes = set(moe_layers)
if config.moe.compute.apply_to != "all":
language_model = get_language_model(
model, override=config.vlm.language_model_attr if config.vlm is not None else None
)
selected_layers = config.moe.compute.resolve_layers(len(language_model.layers))
selected_moes = {
module
for index, layer in enumerate(language_model.layers.children())
if index in selected_layers
for module in layer.modules()
if isinstance(module, MoE)
}
get_logger().debug(f"Selected model layers for MoE compute: {sorted(selected_layers)}")
bf16_grouped_gemm = BF16GroupedGemm()
selected_grouped_gemm = _resolve_grouped_gemm(config) if selected_moes else bf16_grouped_gemm
ep_mesh = parallel_dims.get_mesh("ep") if parallel_dims.ep_enabled else None
dispatch = config.moe.dispatch
for moe in moe_layers:
grouped_gemm = selected_grouped_gemm if moe in selected_moes else bf16_grouped_gemm
if ep_mesh is not None and moe.experts.num_experts % parallel_dims.ep:
raise ValueError(
f"MoE expert count {moe.experts.num_experts} must be divisible by model.ep={parallel_dims.ep}."
@@ -79,7 +96,7 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
token_group_alignment=grouped_gemm.token_group_alignment,
)
elif isinstance(dispatch, TorchMoEDispatchConfig):
if dispatch.transport == "mxfp8":
if dispatch.transport == "mxfp8" and isinstance(grouped_gemm, MXFP8GroupedGemm):
token_dispatcher = MXFP8TorchTokenDispatcher(
num_experts=moe.experts.num_experts,
top_k=moe.router.top_k,
@@ -111,6 +128,6 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
parallelize_module(moe.experts, device_mesh=ep_mesh, parallelize_plan=ExpertWeightParallel())
get_logger().info(
f"Configured {len(moe_layers)} MoE layers with compute={config.moe.compute.type}, "
f"dispatch={config.moe.dispatch.type}, ep={parallel_dims.ep}"
f"Configured {len(selected_moes)}/{len(moe_layers)} MoE layers with compute={config.moe.compute.type}, "
f"apply_to={config.moe.compute.apply_to}, fallback=bf16, dispatch={config.moe.dispatch.type}, ep={parallel_dims.ep}"
)
+1
View File
@@ -280,6 +280,7 @@ def _is_moe_model(config: ModelConfig) -> bool:
from transformers import AutoConfig
model_config = AutoConfig.from_pretrained(config.name, trust_remote_code=config.trust_remote_code)
model_config = getattr(model_config, "text_config", model_config)
return hasattr(model_config, "num_experts") or hasattr(model_config, "n_routed_experts")
+40 -1
View File
@@ -189,7 +189,46 @@ def test_moe_runtime_defaults_are_independent_from_dense_quantization():
],
)
def test_supported_moe_runtime_configs(model):
TrainerModelConfig.model_validate(model)
config = TrainerModelConfig.model_validate(model)
assert config.moe.compute.resolve_layers(43) == set(range(43))
@pytest.mark.parametrize("backend", ["bf16", "deepgemm_fp8", "mxfp8"])
@pytest.mark.parametrize(
("selection", "num_layers", "selected"),
[
("all", 10, set(range(10))),
("85%", 48, set(range(40))),
("100%", 3, {0, 1, 2}),
("0%", 3, set()),
("33.3%", 10, {0, 1, 2}),
([], 10, set()),
([2, 0], 10, {0, 2}),
([0, 2, 2], 3, {0, 2}),
],
)
def test_moe_compute_apply_to(backend, selection, num_layers, selected):
config = TrainerModelConfig.model_validate({"moe": {"compute": {"type": backend, "apply_to": selection}}})
config = TrainerModelConfig.model_validate_json(config.model_dump_json())
assert config.moe.compute.resolve_layers(num_layers) == selected
@pytest.mark.parametrize("selection", ["*", "model.layers.*", "", "101%", "-1%", "nan%", [-1], [1.5], [True]])
def test_moe_compute_rejects_invalid_apply_to(selection):
with pytest.raises(ValidationError, match="apply_to"):
TrainerModelConfig.model_validate({"moe": {"compute": {"type": "mxfp8", "apply_to": selection}}})
def test_moe_compute_rejects_out_of_range_layer():
config = TrainerModelConfig.model_validate({"moe": {"compute": {"type": "mxfp8", "apply_to": [3]}}})
with pytest.raises(ValueError, match="out of range"):
config.moe.compute.resolve_layers(3)
@pytest.mark.parametrize(("selection", "selected"), [("all", {0, 1, 2}), ("50%", {0}), ("[0, 2]", {0, 2})])
def test_moe_compute_apply_to_cli(selection, selected):
config = cli(TrainerModelConfig, args=["--moe.compute.type", "mxfp8", "--moe.compute.apply-to", selection])
assert config.moe.compute.resolve_layers(3) == selected
@pytest.mark.parametrize(
@@ -0,0 +1,282 @@
import os
from unittest.mock import MagicMock
import pytest
import torch
import torch.distributed as dist
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import resolve_auto_attn
from prime_rl.trainer.models import AutoModelForCausalLMPrimeRL
from prime_rl.trainer.models.fusions import apply_model_fusions
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5 import (
Qwen3_5Config,
Qwen3_5MoeConfig,
Qwen3_5MoeTextConfig,
Qwen3_5TextConfig,
Qwen3_5VisionConfig,
)
from prime_rl.trainer.models.qwen3_5.attention import Qwen3_5Attention
from prime_rl.trainer.models.qwen3_5.gated_delta_net import Qwen3_5GatedDeltaNet
from prime_rl.trainer.models.qwen3_5.norm import Qwen3_5RMSNorm
from prime_rl.utils.cp import setup_model_cp
def get_text_config(config_cls=Qwen3_5TextConfig) -> Qwen3_5TextConfig:
moe_config = {}
if config_cls is Qwen3_5MoeTextConfig:
moe_config = dict(
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=8,
num_experts_per_tok=2,
)
return config_cls(
vocab_size=256,
hidden_size=256,
intermediate_size=512,
num_hidden_layers=4,
layer_types=["linear_attention", "linear_attention", "linear_attention", "full_attention"],
num_attention_heads=4,
num_key_value_heads=2,
head_dim=64,
max_position_embeddings=512,
linear_key_head_dim=32,
linear_value_head_dim=32,
linear_num_key_heads=4,
linear_num_value_heads=8,
linear_conv_kernel_dim=4,
**moe_config,
)
@pytest.fixture(params=[Qwen3_5TextConfig, Qwen3_5MoeTextConfig], ids=["dense", "moe"])
def text_config(request):
return get_text_config(request.param)
def get_vlm_config(text_config) -> Qwen3_5Config:
vision_config = Qwen3_5VisionConfig(
depth=1,
hidden_size=64,
intermediate_size=128,
num_heads=4,
out_hidden_size=text_config.hidden_size,
)
config_cls = Qwen3_5MoeConfig if isinstance(text_config, Qwen3_5MoeTextConfig) else Qwen3_5Config
return config_cls(
text_config=text_config,
vision_config=vision_config,
image_token_id=120,
video_token_id=121,
vision_start_token_id=122,
vision_end_token_id=123,
)
def get_model(config, device="cuda"):
runtime_config = ModelConfig()
resolve_auto_attn(runtime_config)
with torch.device(device):
model = AutoModelForCausalLMPrimeRL.from_config(
config, attn_implementation=runtime_config.attn, dtype=torch.bfloat16
)
inject_prime_lm_head(model, chunk_size=None)
return model
@pytest.mark.gpu
def test_norms_remain_zero_centered_after_model_init(text_config):
model = get_model(text_config)
norms = [module for module in model.modules() if isinstance(module, Qwen3_5RMSNorm)]
assert norms
assert all(torch.count_nonzero(norm.weight) == 0 for norm in norms)
@pytest.mark.gpu
def test_context_parallel_setup_chain_text_and_vlm(text_config):
cp_group = MagicMock()
text_model = get_model(text_config, device="meta")
linear_layer = text_model.model.layers[0]
text_model.model.layers[0] = torch.nn.Sequential(linear_layer)
setup_model_cp(text_model, cp_group, cp_rank=1, cp_world_size=2)
assert text_model.model.context_parallel_group is cp_group
assert text_model.model.context_parallel_rank == 1
assert text_model.model.context_parallel_world_size == 2
assert linear_layer.linear_attn.context_parallel_group is cp_group
assert linear_layer.linear_attn.context_parallel_world_size == 2
vlm_model = get_model(get_vlm_config(text_config), device="meta")
setup_model_cp(vlm_model, cp_group, cp_rank=0, cp_world_size=2)
assert vlm_model.model.language_model.context_parallel_group is cp_group
assert vlm_model.model.language_model.layers[0].linear_attn.context_parallel_world_size == 2
@pytest.mark.gpu
def test_qwen3_5_gated_delta_net_context_parallel():
if int(os.environ.get("WORLD_SIZE", 1)) != 2:
pytest.skip("run with torchrun --nproc-per-node=2")
dist.init_process_group("nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
try:
torch.manual_seed(0)
config = get_text_config()
config.hidden_size = 64
config.linear_key_head_dim = 128
config.linear_value_head_dim = 128
config.linear_num_key_heads = 16
config.linear_num_value_heads = 32
reference = Qwen3_5GatedDeltaNet(config).cuda().to(torch.bfloat16)
context_parallel = Qwen3_5GatedDeltaNet(config).cuda().to(torch.bfloat16)
context_parallel.load_state_dict(reference.state_dict())
context_parallel.set_context_parallel_attributes(dist.group.WORLD, world_size=2)
hidden_states = torch.randn(1, 16, config.hidden_size, device="cuda", dtype=torch.bfloat16)
dist.broadcast(hidden_states, src=0)
cu_seqlens = torch.tensor([0, 5, 11, 16], device="cuda", dtype=torch.int32)
reference_input = hidden_states.detach().clone().requires_grad_()
expected = reference(
reference_input,
cu_seqlens,
)
output_gradient = torch.randn_like(expected)
dist.broadcast(output_gradient, src=0)
expected.backward(output_gradient)
local_slice = slice(local_rank * 8, (local_rank + 1) * 8)
local_input = hidden_states[:, local_slice].detach().clone().requires_grad_()
actual = context_parallel(
local_input,
cu_seqlens,
)
actual.backward(output_gradient[:, local_slice])
gathered = [torch.empty_like(actual) for _ in range(2)]
dist.all_gather(gathered, actual)
torch.testing.assert_close(torch.cat(gathered, dim=1), expected, rtol=3e-2, atol=3e-2)
torch.testing.assert_close(
local_input.grad,
reference_input.grad[:, local_slice],
rtol=5e-2,
atol=5e-2,
)
finally:
dist.destroy_process_group()
def test_setup_model_cp_requires_hook_only_for_hybrid_models():
class HybridLayer(torch.nn.Module):
layer_type = "linear_attention"
class Inner:
layers = torch.nn.Sequential(torch.nn.Sequential(HybridLayer()))
class HybridNoHookModel:
model = Inner()
with pytest.raises(ValueError, match="set_context_parallel_attributes"):
setup_model_cp(HybridNoHookModel(), MagicMock(), cp_rank=0, cp_world_size=2)
class SoftmaxOnlyModel:
pass
setup_model_cp(SoftmaxOnlyModel(), MagicMock(), cp_rank=0, cp_world_size=2)
def test_ring_patches_flash_attention():
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
originals = {cls: cls._compute_attention for cls in (FlashAttention, AfmoeFlashAttention)}
try:
substitute_ring_attn(process_group=MagicMock(), heads_k_stride=1)
assert Qwen3_5Attention._compute_attention is FlashAttention._compute_attention
assert Qwen3_5Attention._compute_attention is not originals[FlashAttention]
finally:
for cls, method in originals.items():
cls._compute_attention = method
@pytest.mark.gpu
def test_forward_backward_and_packing(text_config):
prime_model = get_model(text_config)
fusions = ["qkv", "gate_up"] if isinstance(text_config, Qwen3_5MoeTextConfig) else ["qkv"]
apply_model_fusions(prime_model, fusions)
input_ids = torch.randint(0, prime_model.config.vocab_size, (1, 100), device="cuda")
position_ids = torch.arange(1, 101, device="cuda").unsqueeze(0)
prime_output = prime_model(
input_ids,
position_ids=position_ids,
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
)
prime_output["logits"].sum().backward()
assert torch.isfinite(prime_output["logits"]).all()
assert torch.isfinite(prime_model.model.embed_tokens.weight.grad).all()
packed_position_ids = torch.arange(1, 51, device="cuda").repeat(2).unsqueeze(0)
# Keep expert selection fixed to isolate packed sequence boundaries.
config = prime_model.config
routed_experts = None
if isinstance(config, Qwen3_5MoeTextConfig):
routed_experts = (
torch.rand(1, 100, config.num_hidden_layers, config.num_experts, device="cuda")
.topk(config.num_experts_per_tok, dim=-1)
.indices
)
with torch.no_grad():
packed = prime_model(
input_ids,
position_ids=packed_position_ids,
seq_lens=torch.tensor([50, 50], device="cuda"),
routed_experts=routed_experts,
)["logits"]
unpacked = torch.cat(
[
prime_model(
input_ids[:, start : start + 50],
position_ids=packed_position_ids[:, :50],
seq_lens=torch.tensor([50], device="cuda"),
routed_experts=routed_experts[:, start : start + 50] if routed_experts is not None else None,
)["logits"]
for start in (0, 50)
],
dim=1,
)
torch.testing.assert_close(packed, unpacked, atol=0.03, rtol=0.01)
@pytest.mark.gpu
def test_moe_router_replay():
"""When routed_experts are provided, the model uses them instead of computing routing."""
prime_model = get_model(get_text_config(Qwen3_5MoeTextConfig))
with torch.device("cuda"):
input_ids = torch.randint(0, prime_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
seq_lens = torch.tensor([input_ids.shape[1]], device="cuda")
out_normal = prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
num_layers = prime_model.config.num_hidden_layers
topk = prime_model.config.num_experts_per_tok
routed_experts = torch.randint(0, prime_model.config.num_experts, (1, 100, num_layers, topk), device="cuda")
prime_model.zero_grad()
out_replay = prime_model(
input_ids,
position_ids=position_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
)
assert out_replay["logits"].shape == out_normal["logits"].shape
out_replay["logits"].sum().backward()
assert prime_model.model.embed_tokens.weight.grad is not None
+336
View File
@@ -0,0 +1,336 @@
import pytest
import torch
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import can_reinit_empty_buffers, resolve_auto_attn
from prime_rl.trainer.models import AutoModelForCausalLMPrimeRL
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5 import (
Qwen3_5MoeConfig,
Qwen3_5MoeTextConfig,
Qwen3_5VisionConfig,
)
from prime_rl.trainer.models.qwen3_5.rotary_embedding import build_qwen3_5_mrope_position_ids
def get_vlm_config():
return Qwen3_5MoeConfig(
text_config=Qwen3_5MoeTextConfig(
vocab_size=256,
hidden_size=256,
num_hidden_layers=2,
layer_types=["linear_attention", "full_attention"],
num_attention_heads=4,
num_key_value_heads=2,
head_dim=64,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=4,
num_experts_per_tok=2,
max_position_embeddings=512,
linear_key_head_dim=32,
linear_value_head_dim=32,
linear_num_key_heads=4,
linear_num_value_heads=8,
rope_parameters={
"rope_type": "default",
"rope_theta": 10_000_000.0,
"partial_rotary_factor": 0.25,
"mrope_section": [3, 3, 2],
"mrope_interleaved": True,
},
),
vision_config=Qwen3_5VisionConfig(
depth=2,
hidden_size=128,
intermediate_size=256,
num_heads=4,
out_hidden_size=256,
),
image_token_id=250,
video_token_id=251,
vision_start_token_id=252,
vision_end_token_id=253,
)
def get_model(config, device="cuda"):
runtime_config = ModelConfig()
resolve_auto_attn(runtime_config)
with torch.device(device):
model = AutoModelForCausalLMPrimeRL.from_config(
config, attn_implementation=runtime_config.attn, dtype=torch.bfloat16
)
inject_prime_lm_head(model)
return model
def get_image_inputs(config, device="cuda", dtype=torch.bfloat16):
"""Create minimal image inputs matching the vision config."""
vc = config.vision_config
patch_dim = vc.in_channels * vc.temporal_patch_size * vc.patch_size * vc.patch_size
image_grid_thw = torch.tensor([[1, 2, 2]], device=device)
num_patches = int(image_grid_thw.prod().item())
pixel_values = torch.randn(num_patches, patch_dim, device=device, dtype=dtype)
num_image_tokens = num_patches // (vc.spatial_merge_size**2)
return pixel_values, image_grid_thw, num_image_tokens
def get_mm_token_type_ids(input_ids, image_token_id):
mm_token_type_ids = torch.zeros_like(input_ids)
mm_token_type_ids[input_ids == image_token_id] = 1
return mm_token_type_ids
def get_seq_lens(input_ids: torch.Tensor) -> torch.Tensor:
return torch.tensor([input_ids.shape[1]], device=input_ids.device)
@pytest.mark.gpu
def test_vlm_forward():
"""Custom VLM produces logits for both text-only and multimodal inputs."""
config = get_vlm_config()
model = get_model(config)
vocab = config.text_config.vocab_size
# Text-only (avoid special token range 250-253)
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out_text = model(input_ids=input_ids, position_ids=position_ids, seq_lens=get_seq_lens(input_ids))
assert out_text["logits"].shape == (1, 20, vocab)
# Multimodal
pixel_values, image_grid_thw, n_img_tokens = get_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids_mm = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = get_mm_token_type_ids(input_ids_mm, config.image_token_id)
out_mm = model(
input_ids=input_ids_mm,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=get_seq_lens(input_ids_mm),
)
assert out_mm["logits"].shape == (1, input_ids_mm.shape[1], vocab)
@pytest.mark.gpu
def test_vlm_backward():
"""Gradients flow through both vision scatter and text model."""
config = get_vlm_config()
model = get_model(config)
pixel_values, image_grid_thw, n_img_tokens = get_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = get_mm_token_type_ids(input_ids, config.image_token_id)
out = model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=get_seq_lens(input_ids),
)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
assert model.model.visual.patch_embed.proj.weight.grad is not None
@pytest.mark.gpu
def test_vlm_router_replay():
"""routed_experts bypasses router computation in VLM multimodal forward."""
config = get_vlm_config()
model = get_model(config)
vocab = config.text_config.vocab_size
pixel_values, image_grid_thw, n_img_tokens = get_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = get_mm_token_type_ids(input_ids, config.image_token_id)
seq_len = input_ids.shape[1]
num_layers = config.text_config.num_hidden_layers
topk = config.text_config.num_experts_per_tok
routed_experts = torch.randint(0, config.text_config.num_experts, (1, seq_len, num_layers, topk), device="cuda")
out = model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
seq_lens=get_seq_lens(input_ids),
)
assert out["logits"].shape == (1, seq_len, vocab)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
@pytest.mark.gpu
def test_vlm_meta_device_and_buffer_reinit():
"""Model can be created on meta device and buffers reinitialized."""
config = get_vlm_config()
model = get_model(config, device="meta")
assert can_reinit_empty_buffers(model)
model.to_empty(device="cuda")
model.init_buffers_post_meta()
lm_inv = model.model.language_model.rotary_emb.inv_freq
lm_original_inv = model.model.language_model.rotary_emb.original_inv_freq
vis_inv = model.model.visual.rotary_pos_emb.inv_freq
assert lm_inv.device.type == "cuda"
assert lm_original_inv.device.type == "cuda"
assert vis_inv.device.type == "cuda"
assert lm_inv.abs().sum() > 0
assert lm_original_inv.abs().sum() > 0
assert vis_inv.abs().sum() > 0
def test_qwen35_mrope_text_only_positions():
input_ids = torch.tensor([[10, 11, 12, 13]])
mm_token_type_ids = torch.zeros_like(input_ids)
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.arange(4).view(1, 1, -1).expand(3, 1, -1)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_single_image_with_surrounding_text():
input_ids = torch.tensor([[10, 11, 99, 99, 99, 99, 12]])
mm_token_type_ids = torch.tensor([[0, 0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.tensor(
[
[[0, 1, 2, 2, 2, 2, 4]],
[[0, 1, 2, 2, 3, 3, 4]],
[[0, 1, 2, 3, 2, 3, 4]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_adjacent_images_consume_multiple_grids():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 99, 99, 99, 99, 11]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.tensor(
[
[[0, 1, 1, 1, 1, 3, 3, 3, 3, 5]],
[[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]],
[[0, 1, 2, 1, 2, 3, 4, 3, 4, 5]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_packed_segments_reset_independently():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 11, 99, 99, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 0, 1, 1, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
seq_lens = torch.tensor([5, 5])
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=seq_lens,
)
expected_segment = torch.tensor(
[
[0, 1, 1, 1, 1],
[0, 1, 1, 2, 2],
[0, 1, 2, 1, 2],
]
)
torch.testing.assert_close(position_ids[:, 0, :5], expected_segment)
torch.testing.assert_close(position_ids[:, 0, 5:], expected_segment)
def test_qwen35_mrope_packed_matches_standalone_segments():
segment_input_ids = torch.tensor([[10, 99, 99, 99, 99, 11]])
segment_token_types = torch.tensor([[0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
standalone = build_qwen3_5_mrope_position_ids(
input_ids=segment_input_ids,
mm_token_type_ids=segment_token_types,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([segment_input_ids.shape[1]]),
)
packed = build_qwen3_5_mrope_position_ids(
input_ids=torch.cat([segment_input_ids, segment_input_ids], dim=1),
mm_token_type_ids=torch.cat([segment_token_types, segment_token_types], dim=1),
image_grid_thw=torch.cat([image_grid_thw, image_grid_thw], dim=0),
spatial_merge_size=2,
seq_lens=torch.tensor([segment_input_ids.shape[1], segment_input_ids.shape[1]]),
)
torch.testing.assert_close(packed[:, :, : segment_input_ids.shape[1]], standalone)
torch.testing.assert_close(packed[:, :, segment_input_ids.shape[1] :], standalone)
def test_qwen35_mrope_rejects_image_length_grid_mismatch():
input_ids = torch.tensor([[10, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4]])
with pytest.raises(ValueError, match="Image token group length"):
build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
def test_qwen35_mrope_rejects_video_tokens():
input_ids = torch.tensor([[10, 99]])
mm_token_type_ids = torch.tensor([[0, 2]])
with pytest.raises(ValueError, match="video MRoPE"):
build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
+37 -72
View File
@@ -1,85 +1,50 @@
import sys
import types
import pytest
import torch
from prime_rl.trainer.models.layers import cp_mamba
from prime_rl.trainer.models.nemotron_h import NemotronHConfig
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
pytestmark = [pytest.mark.gpu]
class _FakeMixer(torch.nn.Module):
def __init__(self):
super().__init__()
self.intermediate_size = 1
self.conv_dim = 3
self.num_heads = 1
self.n_groups = 1
self.ssm_state_size = 1
self.head_dim = 1
self.chunk_size = 1
self.time_step_limit = None
self.variance_epsilon = 1e-5
self.activation = "silu"
self.in_proj = torch.nn.Linear(1, 5, bias=False)
self.in_proj.weight.data.copy_(torch.tensor([[1.0], [1.0], [1.0], [1.0], [1.0]]))
self.A_log = torch.nn.Parameter(torch.zeros(1))
self.D = torch.nn.Parameter(torch.ones(1))
self.dt_bias = torch.nn.Parameter(torch.zeros(1))
self.conv1d = torch.nn.Conv1d(3, 3, kernel_size=2, groups=3, bias=False)
self.conv1d.weight.data.fill_(1.0)
self.norm = types.SimpleNamespace(
weight=torch.ones(1, device="cuda"), variance_epsilon=self.variance_epsilon, group_size=1
)
self.out_proj = torch.nn.Identity()
@pytest.fixture
def mamba():
torch.manual_seed(0)
config = NemotronHConfig(
hidden_size=256,
hybrid_override_pattern="M",
mamba_num_heads=8,
mamba_head_dim=64,
n_groups=2,
ssm_state_size=64,
conv_kernel=4,
chunk_size=64,
)
return NemotronHMamba2(config).cuda().to(torch.bfloat16)
def _install_fake_scan(monkeypatch, seen_seq_idx: list[torch.Tensor]) -> None:
def fake_scan(hidden_states, time_step, A, B, C, **kwargs):
assert kwargs["return_final_states"] is False
seen_seq_idx.append(kwargs["seq_idx"].clone())
return hidden_states
def test_mamba_resets_conv_and_scan_at_packed_boundaries(mamba):
cu_seqlens = torch.tensor([0, 3, 8], dtype=torch.int32, device="cuda")
first = torch.randn(1, 8, 256, device="cuda", dtype=torch.bfloat16, requires_grad=True)
second = first.detach().clone()
second[:, :3] *= 20
ssd_combined = types.ModuleType("mamba_ssm.ops.triton.ssd_combined")
ssd_combined.mamba_chunk_scan_combined = fake_scan
monkeypatch.setitem(sys.modules, "mamba_ssm", types.ModuleType("mamba_ssm"))
monkeypatch.setitem(sys.modules, "mamba_ssm.ops", types.ModuleType("mamba_ssm.ops"))
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton", types.ModuleType("mamba_ssm.ops.triton"))
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton.ssd_combined", ssd_combined)
first_output = mamba(first, cu_seqlens)
second_output = mamba(second, cu_seqlens)
torch.testing.assert_close(first_output[:, 3:], second_output[:, 3:])
first_output[:, 3:].float().square().sum().backward()
assert torch.count_nonzero(first.grad[:, :3]) == 0
def test_mamba_cp_forward_resets_conv_and_scan_at_packed_boundaries(monkeypatch):
"""Changing document A must not change document B under Ulysses CP."""
seen_seq_idx: list[torch.Tensor] = []
_install_fake_scan(monkeypatch, seen_seq_idx)
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
mixer = _FakeMixer().cuda()
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32, device="cuda")
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]], device="cuda")
second = first.clone()
second[0, 1, 0] = 200.0
first_out = cp_mamba.mamba_cp_forward(mixer, first, None, 0, 1, cu_seqlens)
second_out = cp_mamba.mamba_cp_forward(mixer, second, None, 0, 1, cu_seqlens)
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32, device="cuda"))
assert torch.equal(seen_seq_idx[1], seen_seq_idx[0])
torch.testing.assert_close(first_out[:, 2:], second_out[:, 2:])
def test_mamba_cp_forward_builds_seq_idx_for_uneven_packs(monkeypatch):
seen_seq_idx: list[torch.Tensor] = []
_install_fake_scan(monkeypatch, seen_seq_idx)
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
def test_mamba_builds_sequence_ids_for_uneven_packs(mamba):
cu_seqlens = torch.tensor([0, 1, 4, 6], dtype=torch.int32, device="cuda")
hidden_states = torch.arange(6, dtype=torch.float32, device="cuda").reshape(1, 6, 1)
cp_mamba.mamba_cp_forward(_FakeMixer().cuda(), hidden_states, None, 0, 1, cu_seqlens)
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 1, 1, 1, 2, 2]], dtype=torch.int32, device="cuda"))
hidden_states = torch.randn(1, 6, 256, device="cuda", dtype=torch.bfloat16)
packed = mamba(hidden_states, cu_seqlens)
separate = torch.cat(
[
mamba(hidden_states[:, start:end], torch.tensor([0, end - start], dtype=torch.int32, device="cuda"))
for start, end in [(0, 1), (1, 4), (4, 6)]
],
dim=1,
)
torch.testing.assert_close(packed, separate, rtol=1e-2, atol=1e-2)
+57 -43
View File
@@ -8,7 +8,7 @@ from torch import nn
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import load_dcp_from_hf
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM, eager_reference
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
@@ -16,7 +16,20 @@ from prime_rl.trainer.models.layers import norms
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
# Every layer is built through `DeepseekV4Attention.__init__`, which refuses to construct without
# the kernel it would dispatch to, so the whole file needs tilelang even though nothing here calls it.
pytestmark = [
pytest.mark.gpu,
pytest.mark.skipif(
dsv4_attention.dsv4_sparse_attn is None,
reason="the fused sparse attention kernel did not import; tilelang ships in the `gpu` extra, on linux only",
),
]
requires_fp8_indexer = pytest.mark.skipif(
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9,
reason="the indexer kernel quantizes to Triton fp8e4nv (e4m3), only supported on Hopper (SM90) and newer",
)
# Deliberately heterogeneous: one layer of every attention type, hash-routed bootstrap
# layers ahead of standard MoE ones, and a sliding window narrow enough that the compressed
@@ -26,7 +39,9 @@ MODEL = dict(
hidden_size=128,
moe_intermediate_size=64,
num_hidden_layers=5,
num_attention_heads=4,
# The smallest head count `DeepseekV4Attention.__init__` accepts: the kernel's tiler pads the
# head axis to a power of two and its backward GEMM needs 32 rows.
num_attention_heads=32,
num_key_value_heads=1,
head_dim=32,
q_lora_rank=64,
@@ -65,8 +80,13 @@ MODEL = dict(
rms_norm_eps=1e-6,
)
MODEL_BATCH, MODEL_SEQ = 2, 32
MODULE_BATCH = 2
# Shared: model construction only writes transformers' private `_attn_implementation_internal`
# and `_experts_implementation_internal`, idempotently, so deep-copy before any other mutation.
MODEL_CONFIG = DeepseekV4Config(**MODEL)
# The Lightning Indexer scores one packed row, which makes every batch axis here 1.
BATCH = 1
MODEL_SEQ = 32
SLIDING_LAYER, CSA_LAYER, HCA_LAYER = 0, 1, 2
COMPRESS_RATE = MODEL["compress_rates"]["compressed_sparse_attention"]
@@ -127,29 +147,26 @@ def _randomize(module: nn.Module) -> None:
buffer.copy_(_tid2eid(buffer.shape[0], router.num_experts, router.top_k))
def _prime_config(attn_impl: str = "eager") -> DeepseekV4Config:
"""The toy config. It defaults to eager because the kernel cannot tile 4 attention heads."""
return DeepseekV4Config(**MODEL, _attn_impl=attn_impl)
def get_prime_model(dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> nn.Module:
def get_prime_model(dtype: torch.dtype = torch.bfloat16) -> nn.Module:
"""A prime-rl model with non-degenerate weights and the LM head training code wraps it in."""
with torch.device("cuda"), default_dtype(dtype):
model = DeepseekV4ForCausalLM._from_config(_prime_config(attn_impl))
model = DeepseekV4ForCausalLM._from_config(MODEL_CONFIG)
_randomize(model)
eager_reference.use_eager_attention(model)
inject_prime_lm_head(model, chunk_size=None)
return model
def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> nn.Module:
def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16) -> nn.Module:
"""One attention layer of the same config the whole-model tests use.
`DeepseekV4Attention` reads no MoE or hyper-connection field, so the layer this builds is
bit-identical to one from a config carrying only the attention keys.
"""
with torch.device("cuda"), default_dtype(dtype):
module = DeepseekV4Attention(_prime_config(attn_impl), layer_idx=layer_idx)
module = DeepseekV4Attention(MODEL_CONFIG, layer_idx=layer_idx)
_randomize(module)
eager_reference.use_eager_attention(module)
return module
@@ -176,7 +193,7 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedCont
be the one the caller runs at.
"""
with torch.device("cuda"), default_dtype(dtype):
rotary = DeepseekV4RotaryEmbedding(_prime_config())
rotary = DeepseekV4RotaryEmbedding(MODEL_CONFIG)
return PackedContext.build(
rotary_emb=rotary,
seq_lens=torch.tensor(doc_lens, device="cuda"),
@@ -185,6 +202,7 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedCont
)
@requires_fp8_indexer
def test_deepseek_v4_hash_layers_route_on_token_ids():
"""The bootstrap layers read `input_ids`, so identical hidden states still route apart."""
prime_model = get_prime_model()
@@ -193,7 +211,7 @@ def test_deepseek_v4_hash_layers_route_on_token_ids():
counts = []
for token_id in (0, 1):
input_ids = torch.full((MODEL_BATCH, MODEL_SEQ), token_id, device="cuda", dtype=torch.long)
input_ids = torch.full((BATCH, MODEL_SEQ), token_id, device="cuda", dtype=torch.long)
for layer in hash_layers:
layer.mlp.tokens_per_expert.zero_()
position_ids, seq_lens = _single_doc(input_ids)
@@ -204,19 +222,20 @@ def test_deepseek_v4_hash_layers_route_on_token_ids():
assert set(table[0].tolist()) != set(table[1].tolist()), "the two table rows must differ for this to bite"
assert not torch.equal(counts[0], counts[1]), "a hash layer must route the two token ids to different experts"
expected = torch.zeros_like(counts[0][0])
expected[table[0]] = MODEL_BATCH * MODEL_SEQ
expected[table[0]] = BATCH * MODEL_SEQ
torch.testing.assert_close(counts[0][0], expected)
@requires_fp8_indexer
def test_deepseek_v4_backward():
"""Every parameter that can train does, and the Lightning Indexer's still cannot."""
prime_config = _prime_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = DeepseekV4ForCausalLM(prime_config)
model = DeepseekV4ForCausalLM(MODEL_CONFIG)
_randomize(model)
eager_reference.use_eager_attention(model)
inject_prime_lm_head(model)
input_ids = torch.randint(0, MODEL["vocab_size"], (MODEL_BATCH, MODEL_SEQ), device="cuda")
input_ids = torch.randint(0, MODEL["vocab_size"], (BATCH, MODEL_SEQ), device="cuda")
position_ids, seq_lens = _single_doc(input_ids)
output = model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
output["logits"].sum().backward()
@@ -240,8 +259,7 @@ def test_deepseek_v4_backward():
def test_deepseek_v4_weight_conversion_roundtrip():
prime_config = _prime_config()
model = DeepseekV4ForCausalLM(prime_config).to("cuda")
model = DeepseekV4ForCausalLM(MODEL_CONFIG).to("cuda")
original = {name: tensor.clone() for name, tensor in model.state_dict().items()}
state_dict = model.state_dict()
@@ -286,8 +304,7 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
so getting it to reset one buffer too many is an easy mistake with no symptom other than every
bootstrap token routing to expert 0.
"""
prime_config = _prime_config()
model = DeepseekV4ForCausalLM(prime_config).to("cuda")
model = DeepseekV4ForCausalLM(MODEL_CONFIG).to("cuda")
tables = _fill_hash_tables(model)
state_dict = model.convert_to_hf(dict(model.state_dict()))
@@ -299,15 +316,13 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
assert torch.equal(state_dict[f"layers.{layer_idx}.ffn.gate.tid2eid"], table)
model.convert_to_prime(state_dict)
reloaded = DeepseekV4ForCausalLM(prime_config).to("cuda")
reloaded = DeepseekV4ForCausalLM(MODEL_CONFIG).to("cuda")
reloaded.load_state_dict(state_dict)
for layer_idx, table in tables.items():
assert torch.equal(reloaded.model.layers[layer_idx].mlp.router.tid2eid, table)
# And now the loading path itself, on a meta-device model, with the name `load_dcp_from_hf`
# asks the checkpoint for raising a `KeyError` in the stub below if the buffer ever moves.
with torch.device("meta"):
meta_model = DeepseekV4ForCausalLM(prime_config)
meta_model = DeepseekV4ForCausalLM(MODEL_CONFIG)
expected = tables[0]
def fake_dcp_load(state_dict, storage_reader=None):
@@ -393,7 +408,7 @@ def test_deepseek_v4_on_disk_keys_map_to_the_names_vllm_expects():
from vllm.models.deepseek_v4.nvidia.model import _make_deepseek_v4_weights_mapper
with torch.device("meta"):
model = DeepseekV4ForCausalLM._from_config(_prime_config())
model = DeepseekV4ForCausalLM._from_config(MODEL_CONFIG)
on_disk_state_dict = model.convert_to_hf(dict(model.state_dict()))
assert on_disk_state_dict, "vacuous probe: the model produced no weights to map"
@@ -409,14 +424,13 @@ def test_deepseek_v4_on_disk_keys_map_to_the_names_vllm_expects():
def test_deepseek_v4_init_buffers_post_meta_restores_every_rotary():
"""Rotary tables are non-persistent and computed eagerly, so meta loading loses them."""
prime_config = _prime_config()
with torch.device("meta"):
model = DeepseekV4ForCausalLM(prime_config)
model = DeepseekV4ForCausalLM(MODEL_CONFIG)
model.to_empty(device="cuda")
model.init_buffers_post_meta()
reference = 1.0 / (prime_config.rope_theta ** (torch.arange(0, 16, 2, device="cuda", dtype=torch.float) / 16))
reference = 1.0 / (MODEL_CONFIG.rope_theta ** (torch.arange(0, 16, 2, device="cuda", dtype=torch.float) / 16))
torch.testing.assert_close(model.model.rotary_emb.main_inv_freq, reference)
compressors = [layer.self_attn.compressor for layer in model.model.layers if layer.self_attn.compressor]
assert compressors, "config must contain a compressed attention layer"
@@ -638,7 +652,7 @@ def _entry_counts(doc_lens: tuple[int, ...], compress_rate: int) -> list[int]:
def _fp32_hidden_states(seq_len: int) -> tuple[torch.Tensor, torch.Tensor]:
"""Two leaves carrying identical values, one for the packed run and one for the lone runs."""
with torch.device("cuda"):
hidden = torch.randn(MODULE_BATCH, seq_len, MODEL["hidden_size"])
hidden = torch.randn(BATCH, seq_len, MODEL["hidden_size"])
return hidden.clone().requires_grad_(True), hidden.clone().requires_grad_(True)
@@ -665,6 +679,7 @@ def _compare_accumulated_grads(
_assert_relative(param.grad, expected[name], rtol, name)
@requires_fp8_indexer
def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypatch): # noqa: F811
"""The local window stops at document boundaries, on every layer.
@@ -673,19 +688,19 @@ def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypa
`sliding_window` packed positions whatever document they belong to, which at the production
`sliding_window = 128` against 77-token rollouts spans roughly two neighbours on all 43 layers.
Captured from the mask the model actually applies rather than by calling the builder, so it
keeps holding if the masking ever moves.
Captured from the dense mask the reference consumer applies to production's own
`window_indices`, rather than by calling the builder, so it keeps holding if the masking moves.
"""
recorded = []
real_attention = dsv4_attention.eager_attention_with_sinks
real_attention = eager_reference.eager_attention_with_sinks
def record(query, key, value, sinks, attention_mask, **kwargs):
recorded.append(attention_mask)
return real_attention(query, key, value, sinks, attention_mask, **kwargs)
monkeypatch.setattr(dsv4_attention, "eager_attention_with_sinks", record)
monkeypatch.setattr(eager_reference, "eager_attention_with_sinks", record)
# The dense mask is an eager-path artifact; the count below is one call per layer.
# The dense mask is a reference-path artifact; the count below is one call per layer.
prime_model = get_prime_model(torch.float32)
input_ids, position_ids, seq_lens = _packed_inputs(DOC_LENS)
prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
@@ -703,6 +718,7 @@ def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypa
assert torch.equal(local, expected), f"layer {layer_idx}: the local window crosses a document boundary"
@requires_fp8_indexer
def test_model_packed_matches_unpacked(_torch_rms_norm): # noqa: F811
"""The invariant that makes the trainer agree with vLLM, which serves each rollout alone.
@@ -806,7 +822,7 @@ def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expect
packed_input, alone_input = _fp32_hidden_states(sum(doc_lens))
packed_entries = compressor.compress(packed_input, packed)
assert packed_entries.shape == (MODULE_BATCH, sum(counts), compressor.head_dim)
assert packed_entries.shape == (BATCH, sum(counts), compressor.head_dim)
with torch.device("cuda"):
weight = torch.randn_like(packed_entries)
@@ -819,9 +835,7 @@ def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expect
alone = compressor.compress(
alone_input[:, _doc_slice(doc_lens, index)], _packed_context((doc_lens[index],), torch.float32)
)
assert alone.shape == (MODULE_BATCH, count, compressor.head_dim), (
f"document {index} compressed to the wrong count"
)
assert alone.shape == (BATCH, count, compressor.head_dim), f"document {index} compressed to the wrong count"
torch.testing.assert_close(
packed_entries[:, entries],
alone,
@@ -838,7 +852,7 @@ def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expect
@pytest.mark.parametrize(
("layer_idx", "doc_lens"),
[
(CSA_LAYER, MID_WINDOW_DOCS),
pytest.param(CSA_LAYER, MID_WINDOW_DOCS, marks=requires_fp8_indexer),
(HCA_LAYER, EXACT_MULTIPLE_DOCS),
(SLIDING_LAYER, MID_WINDOW_DOCS),
],
@@ -1,5 +1,7 @@
import copy
import math
from collections.abc import Callable
from unittest.mock import MagicMock
import pytest
import torch
@@ -10,7 +12,7 @@ from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_referenc
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
from prime_rl.utils.utils import default_dtype
@@ -31,6 +33,19 @@ requires_sparse_attn_kernel = pytest.mark.skipif(
reason="the fused sparse attention kernel did not import; tilelang ships in the `gpu` extra, on linux only",
)
# The kernels' shared tiles fit only the datacenter Hopper and Blackwell SMs. The opt-in limit does
# not follow capability order, so this enumerates rather than compares: sm120 allows well under half
# of what sm90 does.
requires_datacenter_gpu = pytest.mark.skipif(
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] not in (9, 10),
reason="the fused sparse attention kernels need the shared memory of a datacenter Hopper or Blackwell GPU",
)
requires_fp8_indexer = pytest.mark.skipif(
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9,
reason="the indexer kernel quantizes to Triton fp8e4nv (e4m3), only supported on Hopper (SM90) and newer",
)
@pytest.fixture(autouse=True)
def _seed_rng():
@@ -60,12 +75,21 @@ def _randomize(module: nn.Module) -> None:
param.normal_(mean=0.0, std=0.02)
def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype, config: DeepseekV4Config) -> PackedContext:
def _packed_context(
doc_lens: tuple[int, ...],
dtype: torch.dtype,
config: DeepseekV4Config,
cp_rank: int = 0,
cp_world_size: int = 1,
) -> PackedContext:
"""The context `DeepseekV4Model` would hand its attention layers for a row of `doc_lens`.
A single-element `doc_lens` gives back the single-document context, which is what the unpacked
half of a packing comparison runs at. `dtype` types the mask and the rotary tables, and has to
be the one the caller runs at.
`doc_lens` always describes the whole row, `cp_world_size` shards included: the context
parallel tests below hand it the same layout every rank sees and vary only `cp_rank`.
"""
with torch.device("cuda"), default_dtype(dtype):
rotary = DeepseekV4RotaryEmbedding(config)
@@ -74,6 +98,8 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype, config: Deeps
seq_lens=torch.tensor(doc_lens, device="cuda"),
dtype=dtype,
device=torch.device("cuda"),
cp_rank=cp_rank,
cp_world_size=cp_world_size,
)
@@ -115,21 +141,9 @@ def _compare_accumulated_grads(
_assert_relative(param.grad, expected[name], rtol, name)
def _set_attn_impl(module: nn.Module, impl: str) -> None:
"""Pin the CSA attention implementation on every attention layer `module` owns.
`modules()` yields `module` itself, so this covers a lone attention layer as well as a model
holding several of them.
"""
for submodule in module.modules():
if isinstance(submodule, DeepseekV4Attention):
submodule.attn_impl = impl
# The real DeepSeek V4-Flash attention shapes, written out as a literal so nothing here depends on a local HF
# cache. This file runs these shapes and no others: the kernel does not tile smaller ones, and the
# sparse path it serves only exists at this size. The MoE fields are shrunk to nothing, since
# `DeepseekV4Attention` reads none of them.
# cache. This file runs these shapes and no others: the sparse path the kernel serves only exists at
# this size. The MoE fields are shrunk to nothing, since `DeepseekV4Attention` reads none of them.
V4FLASH_MODEL = dict(
vocab_size=64,
hidden_size=4096,
@@ -172,52 +186,42 @@ V4FLASH_MODEL = dict(
},
)
# The hand-built tensors of the first section describe the same CSA layer `V4FLASH_MODEL` does, so
# they are read off it rather than written out again: 64 heads over 512 channels, each query
# gathering `sliding_window + index_topk = 128 + 512` slots from a single KV group, in bfloat16.
# Shared by every test here: `DeepseekV4Attention` and `PackedContext.build` only read it.
V4FLASH_CONFIG = DeepseekV4Config(**V4FLASH_MODEL)
# Read off `V4FLASH_MODEL` so the hand-built tensors below describe the same CSA layer it does.
HEADS = V4FLASH_MODEL["num_attention_heads"]
DIM = V4FLASH_MODEL["head_dim"]
KV_GROUP = V4FLASH_MODEL["num_key_value_heads"]
TOPK = V4FLASH_MODEL["sliding_window"] + V4FLASH_MODEL["index_topk"]
SM_SCALE = DIM**-0.5
# Three shapes. The first is aligned to both of the backward's tile sizes and the second to
# neither: `preprocess` tiles the query axis at 32 and `postprocess` tiles the KV axis at 64, so a
# remainder tile in either is a distinct code path. `200 % 32 = 8` and `1000 % 64 = 40`. The third
# carries a batch, which nothing else here does: `Q` and `Indices` are indexed by batch and the
# `dKV[by, Indices[by, ...]]` atomics scatter per batch entry, so a batch stride dropped anywhere
# in that chain is invisible at batch 1. Sequence lengths stay modest because the float32 oracle
# materializes a `(batch, seq_len, topk, head_dim)` gather, roughly 640 KB per token even before
# its backward.
# The first is aligned to both of the backward's tile sizes (32 in `preprocess`, 64 in
# `postprocess`), the second to neither, and the third carries a batch, which nothing else here
# does. Sequence lengths stay modest because the float32 oracle materializes the whole gather.
SHAPES = [(1, 256, 1024), (1, 200, 1000), (3, 128, 768)]
SHAPE_IDS = ["aligned", "misaligned", "batched"]
# A quarter of the gather slots are masked, which is what a real query with a short window or a
# saturated top-k looks like: the masked slots still cost a GEMM column.
# What a real query with a short window or a saturated top-k looks like; a masked slot still
# costs a GEMM column.
MASKED_FRACTION = 0.25
# Bounds on the largest absolute deviation against each tensor's own scale, not element-wise:
# every entry is a sum over hundreds of terms, so the near-zero entries are the ones whose
# summands cancelled, and an element-wise relative bound would read out that cancellation noise.
# The kernel returns bfloat16, so its output cannot agree with a float32 oracle any more closely
# than bfloat16 rounding allows: one ulp at full scale is 2**-8 = 3.9e-3.
# Bounds on the largest deviation against each tensor's own scale, not element-wise: every entry
# sums hundreds of terms, so an element-wise bound would read out the near-zero entries'
# cancellation noise. The kernel returns bfloat16, one ulp of which is 2**-8 at full scale.
OUT_RTOL = 1e-2
# The LSE is float32 throughout on both sides.
LSE_RTOL = 5e-7
DQ_RTOL = 1e-2
# The vendored kernel this one forked from rounds `P` and `dP` to bfloat16 before the `dKV` GEMMs
# while the float32 oracle keeps them in float32. The rest is the bfloat16 `kv` the two sides
# share. Neither effect needs a looser bound than the other gradients get: what used to need one
# was the oracle's own bfloat16 leaf, see `_float32_leaves`.
# while the oracle keeps them in float32, on top of the bfloat16 `kv` both sides share.
DKV_RTOL = 1e-2
# The sink gradient is a full reduction over every query in the row, so it cancels harder than
# anything else here.
DSINK_RTOL = 1e-2
# Compiled against eager. The forward and the log-sum-exp are bit-identical, but `dKV` is not
# comparable that way on either side: the backward scatters it with `atomic_addx4`, so its
# summation order is whatever the scheduler picks and the same eager call against itself moves by
# the same amount.
# Compiled against eager, where the forward and the log-sum-exp are bit-identical. `dKV` is not,
# because `atomic_addx4` leaves its summation order to the scheduler, on both sides.
COMPILE_RTOL = 1e-2
@@ -320,6 +324,7 @@ def _reference_lse(q: torch.Tensor, kv: torch.Tensor, indices: torch.Tensor, sin
@pytest.mark.parametrize(("batch", "seq_len", "seq_len_kv"), SHAPES, ids=SHAPE_IDS)
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_kernel_forward_matches_the_dense_reference(batch, seq_len, seq_len_kv):
"""Output and log-sum-exp against the float32 gather oracle, which has identical semantics."""
q, kv, indices, sinks = _inputs(batch, seq_len, seq_len_kv)
@@ -339,6 +344,7 @@ def test_kernel_forward_matches_the_dense_reference(batch, seq_len, seq_len_kv):
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_kernel_pads_a_slot_count_its_tile_does_not_divide():
"""A caller states the slots it means and the kernel covers the difference to its own tile.
@@ -363,6 +369,7 @@ def test_kernel_pads_a_slot_count_its_tile_does_not_divide():
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_fully_masked_query_reads_as_zero_keys():
"""A query with no keys at all must emit exactly zero, on the sink term alone.
@@ -440,6 +447,7 @@ def test_tilelang_zero_fills_an_out_of_range_gather():
@pytest.mark.parametrize(("batch", "seq_len", "seq_len_kv"), SHAPES, ids=SHAPE_IDS)
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_kernel_backward_matches_autograd_through_the_reference(batch, seq_len, seq_len_kv):
"""All three differentiable inputs, each against its own bound.
@@ -468,6 +476,7 @@ def test_kernel_backward_matches_autograd_through_the_reference(batch, seq_len,
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_kernel_traces_under_torch_compile():
"""`torch.compile(fullgraph=True)` through the op, forward and backward.
@@ -523,15 +532,13 @@ V4FLASH_DOC_LENS = [(517, 1019), (3,), (300,), (3, 129, 1021), (2600,)]
V4FLASH_DOC_IDS = ["two-docs", "no-entries", "one-short-doc", "three-docs", "saturated-topk"]
def _v4flash_config(attn_impl: str = "kernel") -> DeepseekV4Config:
return DeepseekV4Config(**V4FLASH_MODEL, _attn_impl=attn_impl)
def v4flash_attention(layer_idx: int, dtype: torch.dtype = torch.float32, attn_impl: str = "kernel") -> nn.Module:
def v4flash_attention(layer_idx: int, dtype: torch.dtype = torch.float32, eager: bool = False) -> nn.Module:
"""One attention layer at the real DeepSeek V4 Flash shapes, 126M parameters of it."""
with torch.device("cuda"), default_dtype(dtype):
module = DeepseekV4Attention(_v4flash_config(attn_impl), layer_idx=layer_idx)
module = DeepseekV4Attention(V4FLASH_CONFIG, layer_idx=layer_idx)
_randomize(module)
if eager:
eager_reference.use_eager_attention(module)
return module
@@ -547,26 +554,19 @@ def _v4flash_hidden_states(seq_len: int) -> tuple[torch.Tensor, torch.Tensor]:
def _record_attention(monkeypatch) -> dict[str, torch.Tensor]:
"""Capture what each attention path is handed and what it returns, from real forwards.
"""Capture what the kernel is handed and what it returns, from real forwards.
Both implementations are module-level functions the layer looks up by name, so patching them
`dsv4_sparse_attn` is a module-level function the layer looks up by name, so patching it
records the call the layer actually made rather than a reconstruction of it.
"""
recorded: dict[str, torch.Tensor] = {}
real_eager = dsv4_attention.eager_attention_with_sinks
real_kernel = dsv4_attention.dsv4_sparse_attn
def eager(query, key, value, sinks, attention_mask, **kwargs):
recorded["mask"] = attention_mask
recorded["eager"] = real_eager(query, key, value, sinks, attention_mask, **kwargs)
return recorded["eager"]
def kernel(q, kv_buf, indices, sinks, scale):
recorded["kv_buf"], recorded["indices"] = kv_buf, indices
recorded["kernel"] = real_kernel(q, kv_buf, indices, sinks, scale)
return recorded["kernel"]
monkeypatch.setattr(dsv4_attention, "eager_attention_with_sinks", eager)
monkeypatch.setattr(dsv4_attention, "dsv4_sparse_attn", kernel)
return recorded
@@ -636,6 +636,15 @@ def _selected_positions(indices: torch.Tensor, n_positions: int) -> torch.Tensor
@requires_sparse_attn_kernel
def test_deepseek_v4_refuses_a_shape_the_kernel_cannot_tile():
"""The constructor refuses a head count the kernels cannot tile, rather than the first forward."""
config = DeepseekV4Config(**{**V4FLASH_MODEL, "num_attention_heads": 16})
with pytest.raises(ValueError, match="cannot run the fused sparse-attention kernel"):
DeepseekV4Attention(config, layer_idx=V4FLASH_CSA_LAYER)
@requires_sparse_attn_kernel
@requires_datacenter_gpu
@pytest.mark.parametrize("doc_lens", V4FLASH_DOC_LENS, ids=V4FLASH_DOC_IDS)
@pytest.mark.parametrize("layer_idx", V4FLASH_LAYERS, ids=V4FLASH_LAYER_IDS)
def test_sparse_indices_address_exactly_the_keys_the_dense_mask_admits(doc_lens, layer_idx, monkeypatch):
@@ -659,14 +668,14 @@ def test_sparse_indices_address_exactly_the_keys_the_dense_mask_admits(doc_lens,
"""
module = v4flash_attention(layer_idx, dtype=torch.bfloat16)
layer_type = V4FLASH_MODEL["layer_types"][layer_idx]
packed = _packed_context(doc_lens, torch.bfloat16, _v4flash_config())
packed = _packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG)
hidden_states = _v4flash_hidden_states(sum(doc_lens))[0].detach().to(torch.bfloat16)
recorded = _record_attention(monkeypatch)
if module.compressor is not None:
real_compressor = module.compressor.forward
def compressor(hidden_states, q_residual, packed):
def compressor(hidden_states, q_residual, packed, **kwargs):
compressed_kv, recorded["picks"] = real_compressor(hidden_states, q_residual, packed)
return compressed_kv, recorded["picks"]
@@ -693,6 +702,7 @@ def test_sparse_indices_address_exactly_the_keys_the_dense_mask_admits(doc_lens,
@requires_sparse_attn_kernel
@requires_datacenter_gpu
@pytest.mark.parametrize("doc_lens", V4FLASH_DOC_LENS, ids=V4FLASH_DOC_IDS)
@pytest.mark.parametrize("layer_idx", V4FLASH_LAYERS, ids=V4FLASH_LAYER_IDS)
def test_sparse_indices_are_in_range_and_never_repeat_a_key(doc_lens, layer_idx, monkeypatch):
@@ -707,7 +717,7 @@ def test_sparse_indices_are_in_range_and_never_repeat_a_key(doc_lens, layer_idx,
"""
module = v4flash_attention(layer_idx, dtype=torch.bfloat16)
layer_type = V4FLASH_MODEL["layer_types"][layer_idx]
packed = _packed_context(doc_lens, torch.bfloat16, _v4flash_config())
packed = _packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG)
hidden_states = _v4flash_hidden_states(sum(doc_lens))[0].detach().to(torch.bfloat16)
recorded = _record_attention(monkeypatch)
@@ -733,6 +743,7 @@ def test_sparse_indices_are_in_range_and_never_repeat_a_key(doc_lens, layer_idx,
@requires_sparse_attn_kernel
@requires_datacenter_gpu
@pytest.mark.parametrize("doc_lens", V4FLASH_DOC_LENS, ids=V4FLASH_DOC_IDS)
def test_absent_slots_are_marked_negative_rather_than_pointed_at_a_pad_row(doc_lens, monkeypatch):
"""An unused gather slot must hold `IGNORE_SLOT` (-1), never a position that `kv_buf` actually has.
@@ -754,7 +765,7 @@ def test_absent_slots_are_marked_negative_rather_than_pointed_at_a_pad_row(doc_l
this asserts the contract directly.
"""
module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
packed = _packed_context(doc_lens, torch.bfloat16, _v4flash_config())
packed = _packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG)
hidden_states = _v4flash_hidden_states(sum(doc_lens))[0].detach().to(torch.bfloat16)
recorded = _record_attention(monkeypatch)
@@ -809,6 +820,7 @@ EAGER_KERNEL_RTOL, EAGER_KERNEL_GRAD_RTOL = 1e-2, 5e-2
@pytest.mark.parametrize("doc_lens", EAGER_KERNEL_DOC_LENS, ids=EAGER_KERNEL_DOC_IDS)
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
"""The fused kernel against the naive dense softmax, single-document and packed.
@@ -832,7 +844,7 @@ def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
seq_len = sum(doc_lens)
kernel_module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
eager_module = copy.deepcopy(kernel_module).float()
_set_attn_impl(eager_module, "eager")
eager_reference.use_eager_attention(eager_module)
with torch.device("cuda"):
base = torch.randn(1, seq_len, V4FLASH_MODEL["hidden_size"], dtype=torch.bfloat16)
@@ -848,8 +860,8 @@ def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
monkeypatch.setattr(dsv4_attention, "dsv4_sparse_attn", counting_kernel)
kernel_output, _ = kernel_module(kernel_input, packed=_packed_context(doc_lens, torch.bfloat16, _v4flash_config()))
eager_output, _ = eager_module(eager_input, packed=_packed_context(doc_lens, torch.float32, _v4flash_config()))
kernel_output, _ = kernel_module(kernel_input, packed=_packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG))
eager_output, _ = eager_module(eager_input, packed=_packed_context(doc_lens, torch.float32, V4FLASH_CONFIG))
assert calls == [seq_len], f"the forward never reached the kernel, calls={calls}"
_assert_relative(kernel_output, eager_output, EAGER_KERNEL_RTOL, "attention output")
@@ -868,6 +880,7 @@ def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
"""The fused kernel path, end to end through one CSA layer, must respect documents.
@@ -883,7 +896,7 @@ def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
a fallback would leave this test asserting a property of the gather reference instead.
"""
module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, _v4flash_config())
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, V4FLASH_CONFIG)
with torch.device("cuda"):
hidden = torch.randn(1, sum(KERNEL_DOC_LENS), V4FLASH_MODEL["hidden_size"], dtype=torch.bfloat16)
packed_input, alone_input = hidden.clone().requires_grad_(True), hidden.clone().requires_grad_(True)
@@ -907,7 +920,7 @@ def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
for index, length in enumerate(KERNEL_DOC_LENS):
span = _doc_slice(KERNEL_DOC_LENS, index)
alone_output, _ = module(
alone_input[:, span], packed=_packed_context((length,), torch.bfloat16, _v4flash_config())
alone_input[:, span], packed=_packed_context((length,), torch.bfloat16, V4FLASH_CONFIG)
)
_assert_relative(packed_output[:, span], alone_output, KERNEL_RTOL, f"document {index}")
(alone_output * weight[:, span]).sum().backward()
@@ -918,12 +931,13 @@ def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
@requires_sparse_attn_kernel
@requires_datacenter_gpu
def test_sparse_attention_kernel_trains_every_parameter(monkeypatch):
"""Every parameter of a CSA layer that can train does, with the kernel in the path.
`test_deepseek_v4_backward` makes this assertion through the assembled model, but only on the
gather path: the kernel does not tile the toy shapes that file runs. This is the same assertion
at module level and at the real Flash shapes, and it is not implied by its neighbour above, which
dense reference, which is what that whole file binds. This is the same assertion at module
level and at the real Flash shapes, and it is not implied by its neighbour above, which
compares two runs of the same path and would pass unchanged if both left a parameter at zero.
The call count is load-bearing rather than decoration: `dsv4_sparse_attn` raises today
@@ -931,7 +945,7 @@ def test_sparse_attention_kernel_trains_every_parameter(monkeypatch):
asserting a property of the gather reference.
"""
module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, _v4flash_config())
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, V4FLASH_CONFIG)
with torch.device("cuda"):
hidden_states = torch.randn(1, sum(KERNEL_DOC_LENS), V4FLASH_MODEL["hidden_size"], dtype=torch.bfloat16)
hidden_states.requires_grad_(True)
@@ -977,6 +991,7 @@ def test_sparse_attention_kernel_trains_every_parameter(monkeypatch):
V4FLASH_HCA_DOCS = (256, 512)
@requires_sparse_attn_kernel
def test_v4flash_hca_attention_packed_matches_unpacked():
"""An HCA layer at production shapes must answer each document as if it stood alone.
@@ -990,13 +1005,13 @@ def test_v4flash_hca_attention_packed_matches_unpacked():
`test_attention_packed_matches_unpacked[hca]` asserts the same invariant at toy shapes and
rate 8.
"""
module = v4flash_attention(V4FLASH_HCA_LAYER, dtype=torch.float32, attn_impl="eager")
module = v4flash_attention(V4FLASH_HCA_LAYER, dtype=torch.float32, eager=True)
assert module.layer_type == "heavily_compressed_attention", (
f"expected the Flash config's HCA layer, got {module.layer_type}"
)
seq_len = sum(V4FLASH_HCA_DOCS)
packed_input, alone_input = _v4flash_hidden_states(seq_len)
packed = _packed_context(V4FLASH_HCA_DOCS, torch.float32, _v4flash_config())
packed = _packed_context(V4FLASH_HCA_DOCS, torch.float32, V4FLASH_CONFIG)
q_residual = module.q_a_norm(module.q_a_proj(packed_input.detach()))
_, picks = module.compressor(packed_input.detach(), q_residual, packed)
@@ -1013,9 +1028,7 @@ def test_v4flash_hca_attention_packed_matches_unpacked():
for index, length in enumerate(V4FLASH_HCA_DOCS):
span = _doc_slice(V4FLASH_HCA_DOCS, index)
alone_output, _ = module(
alone_input[:, span], packed=_packed_context((length,), torch.float32, _v4flash_config())
)
alone_output, _ = module(alone_input[:, span], packed=_packed_context((length,), torch.float32, V4FLASH_CONFIG))
_assert_relative(packed_output[:, span], alone_output, PACKED_RTOL, f"document {index}")
(alone_output * weight[:, span]).sum().backward()
@@ -1071,14 +1084,15 @@ def _assert_within_the_bfloat16_floor(
@requires_sparse_attn_kernel
@requires_datacenter_gpu
@pytest.mark.parametrize("doc_lens", PARITY_DOC_LENS, ids=PARITY_DOC_IDS)
@pytest.mark.parametrize("layer_idx", V4FLASH_LAYERS, ids=V4FLASH_LAYER_IDS)
def test_kernel_and_eager_consumers_agree_on_shared_weights(layer_idx, doc_lens):
"""The two consumers of one `SparseAttnInputs` must compute the same attention, and its gradient.
They are handed the identical index tensor, so this is not about which keys a query reads,
which its neighbours settle on integers. What is at stake is the attention core the layer picks
between: the sink term in the softmax denominator, the scale, the value weighting and the
which its neighbours settle on integers. What is at stake is the attention core itself: the
sink term in the softmax denominator, the scale, the value weighting and the
backward's scatter. A kernel that dropped the sink, weighted a head with another head's
probabilities or lost a term in `dQ` would still hand back finite numbers of the right shape,
and every packing test in this file would still pass, because both halves of those comparisons
@@ -1091,9 +1105,9 @@ def test_kernel_and_eager_consumers_agree_on_shared_weights(layer_idx, doc_lens)
"""
module = v4flash_attention(layer_idx, dtype=torch.bfloat16)
weights = module.state_dict()
eager_bf16 = v4flash_attention(layer_idx, dtype=torch.bfloat16, attn_impl="eager")
eager_bf16 = v4flash_attention(layer_idx, dtype=torch.bfloat16, eager=True)
eager_bf16.load_state_dict(weights)
eager_fp32 = v4flash_attention(layer_idx, dtype=torch.float32, attn_impl="eager")
eager_fp32 = v4flash_attention(layer_idx, dtype=torch.float32, eager=True)
eager_fp32.load_state_dict({name: tensor.float() for name, tensor in weights.items()})
with torch.device("cuda"):
@@ -1107,7 +1121,7 @@ def test_kernel_and_eager_consumers_agree_on_shared_weights(layer_idx, doc_lens)
("eager_fp32", eager_fp32, torch.float32),
):
hidden_states = hidden.to(dtype).clone().requires_grad_(True)
packed = _packed_context(doc_lens, dtype, _v4flash_config())
packed = _packed_context(doc_lens, dtype, V4FLASH_CONFIG)
with _SparseAttnCallCounter() as counter:
output, _ = layer(hidden_states, packed=packed)
assert counter.count == (1 if name == "kernel" else 0), f"{name} made {counter.count} kernel calls"
@@ -1127,3 +1141,118 @@ def test_kernel_and_eager_consumers_agree_on_shared_weights(layer_idx, doc_lens)
assert kernel_grad is None and eager_grad is None, f"{name} trains on one path but not the other"
continue
_assert_within_the_bfloat16_floor(kernel_grad, eager_grad, param.grad, f"{name} gradient")
# Widths that 4 divides. `(517, 1019)` puts the `cp = 2` cut inside the second document, and
# `(300,)` gives 75-token shards at `cp = 4`, narrower than `sliding_window = 128`.
CP_DOC_LENS = [(517, 1019), (300,)]
CP_DOC_IDS = ["two-docs", "one-short-doc"]
CP_WORLD_SIZES = [2, 4]
CP_WORLD_SIZE_IDS = ["cp2", "cp4"]
def _cp_gathered_projections(
module: nn.Module,
doc_lens: tuple[int, ...],
dtype: torch.dtype,
config: DeepseekV4Config,
cp_world_size: int,
) -> list[tuple[str, Callable[[torch.Tensor, int], torch.Tensor]]]:
"""What one attention layer all-gathers, in the order its forward does, per source chunk.
Order identifies a gather, not width: two of a CSA layer's three are 512 wide. Only the
first is rotated, at its own rank's query positions, which is what the rank index is for.
"""
# One context per rank, not one per gather: a rank's gathers all read the same tables.
rope_tables = [
_packed_context(doc_lens, dtype, config, cp_rank=cp_rank, cp_world_size=cp_world_size).position_embeddings[
module.rope_layer_type
]
for cp_rank in range(cp_world_size)
]
def rotated_kv(hidden: torch.Tensor, rank_index: int) -> torch.Tensor:
kv = module.kv_norm(module.kv_proj(hidden)).view(*hidden.shape[:2], 1, module.head_dim)
cos, sin = rope_tables[rank_index]
return apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
def concatenated_projections(compressor: nn.Module) -> Callable[[torch.Tensor, int], torch.Tensor]:
return lambda hidden, _: torch.cat([compressor.kv_proj(hidden), compressor.gate_proj(hidden)], dim=-1)
projections = [("attention kv", rotated_kv)]
if module.compressor is not None:
projections.append((f"{module.layer_type} compress", concatenated_projections(module.compressor)))
indexer = getattr(module.compressor, "indexer", None)
if indexer is not None:
projections.append(("indexer compress", concatenated_projections(indexer.compressor)))
return projections
def _fake_gather_for_cp(
projections: list[tuple[str, Callable[[torch.Tensor, int], torch.Tensor]]],
chunks: tuple[torch.Tensor, ...],
cp_rank: int,
) -> tuple[Callable[..., torch.Tensor], list[tuple[str, Callable[[torch.Tensor, int], torch.Tensor]]]]:
"""A `gather_for_cp` stand-in for `cp_rank`, plus the list of gathers it has yet to see.
The slab at `cp_rank` is the caller's own tensor and the siblings stay attached, so summing
the per-rank backwards is what `_all_gather`'s `_reduce_scatter_sum` computes. Gathers are
matched by position, since two of a CSA layer's three share a width.
"""
pending = list(projections)
def gather(tensor: torch.Tensor, cp_group) -> torch.Tensor:
assert pending, f"rank {cp_rank} gathered more often than its {len(projections)} projections account for"
label, projection = pending.pop(0)
slabs = [projection(chunk, rank_index) for rank_index, chunk in enumerate(chunks)]
assert tensor.shape == slabs[cp_rank].shape, (
f"gather '{label}' was handed a {tuple(tensor.shape)} tensor, expected {tuple(slabs[cp_rank].shape)}"
)
_assert_relative(tensor, slabs[cp_rank], PACKED_RTOL, f"gather '{label}'")
slabs[cp_rank] = tensor
return torch.cat(slabs, dim=1)
return gather, pending
@requires_sparse_attn_kernel
@pytest.mark.parametrize("doc_lens", CP_DOC_LENS, ids=CP_DOC_IDS)
@pytest.mark.parametrize("cp_world_size", CP_WORLD_SIZES, ids=CP_WORLD_SIZE_IDS)
@pytest.mark.parametrize(
"layer_idx",
[pytest.param(V4FLASH_CSA_LAYER, marks=requires_fp8_indexer), V4FLASH_HCA_LAYER, V4FLASH_SLIDING_LAYER],
ids=V4FLASH_LAYER_IDS,
)
def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_size, doc_lens, monkeypatch):
module = v4flash_attention(layer_idx, dtype=torch.float32, eager=True)
seq_len = sum(doc_lens)
with torch.device("cuda"):
hidden_full = torch.randn(1, seq_len, V4FLASH_MODEL["hidden_size"]).requires_grad_(True)
cotangent = torch.randn(1, seq_len, V4FLASH_MODEL["hidden_size"])
out_full, _ = module(hidden_full, packed=_packed_context(doc_lens, torch.float32, V4FLASH_CONFIG))
(out_full * cotangent).sum().backward()
reference_out = out_full.detach()
reference_input_grad = hidden_full.grad.clone()
reference_grads = _take_grads(module)
hidden_full.grad = None
# Views of the one leaf, so every rank's backward accumulates into the same buffers.
chunks = hidden_full.chunk(cp_world_size, dim=1)
n_queries = seq_len // cp_world_size
projections = _cp_gathered_projections(module, doc_lens, torch.float32, V4FLASH_CONFIG, cp_world_size)
for cp_rank, chunk in enumerate(chunks):
gather, pending = _fake_gather_for_cp(projections, chunks, cp_rank)
monkeypatch.setattr(dsv4_attention, "gather_for_cp", gather)
module.set_context_parallel_attributes(MagicMock(), cp_rank, cp_world_size)
packed = _packed_context(doc_lens, torch.float32, V4FLASH_CONFIG, cp_rank=cp_rank, cp_world_size=cp_world_size)
out_rank, _ = module(chunk, packed=packed)
assert not pending, f"rank {cp_rank} never gathered {[label for label, _ in pending]}"
rows = slice(cp_rank * n_queries, (cp_rank + 1) * n_queries)
_assert_relative(out_rank, reference_out[:, rows], PACKED_RTOL, f"rank {cp_rank} output")
(out_rank * cotangent[:, rows]).sum().backward()
_assert_relative(hidden_full.grad, reference_input_grad, PACKED_GRAD_RTOL, "hidden states gradient")
_compare_accumulated_grads(module, reference_grads)
+22
View File
@@ -2,14 +2,36 @@ import pytest
import torch
import torch.nn.functional as F
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher
from prime_rl.trainer.models.layers.activations import ActivationDispatch
from prime_rl.trainer.models.layers.grouped_gemm import BF16GroupedGemm
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.moe import (
GroupedExperts,
MoE,
MoEArgs,
)
from prime_rl.trainer.moe_runtime import configure_moe_runtime
from prime_rl.trainer.parallel_dims import ParallelDims
@pytest.mark.parametrize("selection", [[], [0], "0%", "50%"])
def test_unselected_moe_uses_bf16_without_loading_quantization_backend(selection):
moe = MoE.from_args(MoEArgs(num_experts=2), dim=4, hidden_dim=8, shared_expert=None)
parameters = dict(moe.named_parameters())
model = torch.nn.Module()
model.model = torch.nn.Module()
model.model.layers = torch.nn.ModuleList([torch.nn.Identity(), moe])
config = ModelConfig.model_validate({"moe": {"compute": {"type": "mxfp8", "apply_to": selection}}})
dims = ParallelDims(dp_replicate=1, dp_shard=1, cp=1, pp=1, ep=1, world_size=1)
configure_moe_runtime(model, config, dims)
assert isinstance(moe.experts.grouped_gemm, BF16GroupedGemm)
assert isinstance(moe.token_dispatcher, LocalTokenDispatcher)
assert moe.token_dispatcher.token_group_alignment == moe.experts.grouped_gemm.token_group_alignment
assert all(moe.get_parameter(name) is parameter for name, parameter in parameters.items())
def _grouped_mm_reference(x: torch.Tensor, weights: torch.Tensor, *, offs: torch.Tensor) -> torch.Tensor:
+29 -111
View File
@@ -2,24 +2,17 @@ from unittest.mock import MagicMock
import pytest
import torch
from transformers.models.nemotron_h.configuration_nemotron_h import NemotronHConfig as HFNemotronHConfig
from transformers.models.nemotron_h.modeling_nemotron_h import (
NemotronHAttention,
)
from transformers.models.nemotron_h.modeling_nemotron_h import (
NemotronHForCausalLM as HFNemotronHForCausalLM,
)
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
from prime_rl.trainer.models.nemotron_h.modeling_nemotron_h import NemotronHAttentionLayer, NemotronHMambaLayer
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
from prime_rl.utils.cp import setup_model_cp
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
# Shared small-model hyperparams (satisfy mamba_expand * hidden_size == mamba_num_heads * mamba_head_dim)
_BASE = dict(
attn_implementation="flash_attention_2",
vocab_size=256,
hidden_size=256,
num_attention_heads=4,
@@ -27,13 +20,13 @@ _BASE = dict(
head_dim=64,
max_position_embeddings=128,
intermediate_size=512,
mamba_expand=2,
expand=2,
mamba_num_heads=8,
mamba_head_dim=64,
ssm_state_size=64,
mamba_n_groups=1,
mamba_d_conv=4,
mamba_chunk_size=64,
n_groups=1,
conv_kernel=4,
chunk_size=64,
n_routed_experts=4,
n_shared_experts=1,
moe_intermediate_size=256,
@@ -49,66 +42,11 @@ def _seq_lens(input_ids: torch.Tensor) -> torch.Tensor:
return torch.tensor([input_ids.shape[1]], device=input_ids.device)
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 = "flash_attention_2"
prime_config = NemotronHConfig(
**_BASE,
layers_block_type=["mamba", "moe", "attention", "moe"],
)
prime_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.bfloat16):
hf_model = HFNemotronHForCausalLM._from_config(hf_config)
prime_model = NemotronHForCausalLM._from_config(prime_config)
with torch.no_grad():
state_dict = hf_model.state_dict()
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
def test_nemotron_h_mamba_moe_only():
"""Test Mamba and MoE layers produce identical outputs (attention bypassed)."""
hf_model, prime_model = get_model_pairs()
# Bypass attention layers in both models so only Mamba+MoE are exercised
for layer in hf_model.model.layers:
if isinstance(layer.mixer, NemotronHAttention):
layer.forward = lambda hidden_states, **kwargs: hidden_states
for layer in prime_model.model.layers:
if isinstance(layer, NemotronHAttentionLayer):
layer.forward = lambda hidden_states, **kwargs: hidden_states
torch.manual_seed(42)
with torch.device("cuda"), default_dtype(torch.bfloat16):
input_ids = torch.randint(0, 256, (1, 32))
position_ids = torch.arange(0, 32).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embeddings.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=1000), f"Max grad diff: {grad_diff.abs().max()}"
def test_nemotron_h_reverse():
"""PrimeRL weights convert back to the source checkpoint layout."""
_, prime_model = get_model_pairs()
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
with torch.device("meta"):
prime_model = NemotronHForCausalLM(config)
converted = prime_model.convert_to_hf(dict(prime_model.state_dict()))
assert prime_model.is_hf_state_dict(converted)
@@ -116,34 +54,14 @@ def test_nemotron_h_reverse():
assert not any("mlp.experts.up_proj" in name for name in converted)
def test_nemotron_h():
"""Test full model (Mamba + MoE + Attention) produces close outputs."""
hf_model, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.bfloat16):
input_ids = torch.randint(0, 256, (1, 32))
position_ids = torch.arange(0, 32).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
# Slightly larger tolerance due to different SDPA attention implementations
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
f"Max logits diff: {logits_diff.abs().max()}"
)
def test_nemotron_h_backward():
"""Verify all parameters receive non-zero gradients."""
prime_config = NemotronHConfig(
**_BASE,
layers_block_type=["mamba", "moe", "attention", "moe"],
)
prime_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = NemotronHForCausalLM(prime_config)
inject_prime_lm_head(model)
input_ids = torch.randint(0, 256, (2, 16), device="cuda")
input_ids = torch.randint(0, 256, (1, 16), device="cuda")
output = model(input_ids, seq_lens=_seq_lens(input_ids))
output["logits"].sum().backward()
@@ -158,10 +76,7 @@ def test_nemotron_h_backward():
def test_nemotron_h_weight_conversion_roundtrip():
"""Verify PrimeRL -> HF -> PrimeRL conversion preserves all weights."""
prime_config = NemotronHConfig(
**_BASE,
layers_block_type=["mamba", "moe", "attention", "moe"],
)
prime_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
model = NemotronHForCausalLM(prime_config).to("cuda")
original_sd = {k: v.clone() for k, v in model.state_dict().items()}
@@ -176,46 +91,49 @@ def test_nemotron_h_weight_conversion_roundtrip():
assert torch.equal(original_sd[key], sd[key]), f"Value mismatch for {key}"
def test_nemotron_h_hybrid_override_pattern():
"""Verify hybrid_override_pattern correctly maps to layers_block_type."""
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
assert config.layers_block_type == ["mamba", "moe", "attention", "moe"]
assert config.num_hidden_layers == 4
def test_nemotron_h_layer_types():
expected = ["mamba", "moe", "attention", "moe"]
pattern_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
list_config = NemotronHConfig(**_BASE, layers_block_type=expected)
assert pattern_config.layer_types == expected
assert list_config.layer_types == expected
assert pattern_config.num_hidden_layers == list_config.num_hidden_layers == 4
def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
config = NemotronHConfig(
**(_BASE | {"mamba_n_groups": 2}),
layers_block_type=["mamba", "moe", "attention", "moe"],
**(_BASE | {"n_groups": 2}),
hybrid_override_pattern="ME*E",
)
with torch.device("meta"):
model = NemotronHForCausalLM(config)
mamba_layer = model.model.layers[0]
assert isinstance(mamba_layer, NemotronHMambaLayer)
assert isinstance(mamba_layer.mamba, NemotronHMamba2)
model.model.layers[0] = torch.nn.Sequential(mamba_layer)
cp_group = MagicMock()
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
assert mamba_layer._cp_group is cp_group
assert mamba_layer._cp_rank == 1
assert mamba_layer._cp_world_size == 2
assert mamba_layer.mamba.process_group is cp_group
assert mamba_layer.mamba.context_parallel_rank == 1
assert mamba_layer.mamba.context_parallel_world_size == 2
def test_nemotron_h_no_latent_projection():
"""Verify model works without latent projections (moe_latent_size=None)."""
prime_config = NemotronHConfig(
**{**_BASE, "moe_latent_size": None},
layers_block_type=["mamba", "moe", "attention", "moe"],
hybrid_override_pattern="ME*E",
)
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = NemotronHForCausalLM(prime_config)
inject_prime_lm_head(model)
input_ids = torch.randint(0, 256, (2, 16), device="cuda")
input_ids = torch.randint(0, 256, (1, 16), device="cuda")
output = model(input_ids, seq_lens=_seq_lens(input_ids))
assert output["logits"].shape == (2, 16, 256)
assert output["logits"].shape == (1, 16, 256)
output["logits"].sum().backward()
for name, p in model.named_parameters():
+11 -17
View File
@@ -29,13 +29,13 @@ _BASE = dict(
head_dim=64,
max_position_embeddings=128,
intermediate_size=512,
mamba_expand=2,
expand=2,
mamba_num_heads=8,
mamba_head_dim=64,
ssm_state_size=64,
mamba_n_groups=1,
mamba_d_conv=4,
mamba_chunk_size=64,
n_groups=1,
conv_kernel=4,
chunk_size=64,
n_routed_experts=4,
n_shared_experts=1,
moe_intermediate_size=256,
@@ -48,13 +48,10 @@ _BASE = dict(
def _make_model(device="cuda"):
config = NemotronHConfig(
**_BASE,
layers_block_type=["mamba", "moe", "attention", "moe"],
)
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
config._attn_implementation = "flash_attention_2"
with torch.device(device), default_dtype(torch.bfloat16):
model = NemotronHForCausalLM._from_config(config)
model = NemotronHForCausalLM(config)
inject_prime_lm_head(model, chunk_size=None)
return model
@@ -88,7 +85,7 @@ def test_kl_zero_when_identical():
"""Two identical models should have zero KL mismatch."""
model = _make_model()
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
logprobs = _get_logprobs_vanilla(model, input_ids)
loss_mask = torch.ones(32, dtype=torch.bool, device="cuda")
@@ -121,7 +118,7 @@ def test_kl_positive_after_perturbation():
policy_model.load_state_dict(ref_model.state_dict())
_perturb_model(policy_model, scale=0.05)
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
ref_logprobs = _get_logprobs_vanilla(ref_model, input_ids)
policy_logprobs = _get_logprobs_vanilla(policy_model, input_ids)
@@ -182,14 +179,11 @@ def test_kl_increases_with_larger_perturbation():
def test_kl_with_fused_lm_head():
"""FusedOutputLinear should produce same logprobs as VanillaOutputLinear."""
config = NemotronHConfig(
**_BASE,
layers_block_type=["mamba", "moe", "attention", "moe"],
)
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = NemotronHForCausalLM._from_config(config)
model = NemotronHForCausalLM(config)
# Get logits from vanilla head
inject_prime_lm_head(model, chunk_size=None)
@@ -296,7 +290,7 @@ def test_kl_mismatch_formula_sanity():
ref_model.load_state_dict(model.state_dict())
_perturb_model(model, scale=0.1)
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
trainer_logprobs = _get_logprobs_vanilla(model, input_ids)
inference_logprobs = _get_logprobs_vanilla(ref_model, input_ids)
-174
View File
@@ -1,174 +0,0 @@
import inspect
from unittest.mock import MagicMock
import pytest
import torch
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5Config, Qwen3_5TextConfig, Qwen3_5VisionConfig
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForCausalLM as HFQwen3_5ForCausalLM
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.utils.cp import setup_model_cp
def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig:
config = Qwen3_5TextConfig(
vocab_size=128,
hidden_size=64,
intermediate_size=128,
num_hidden_layers=2,
layer_types=["linear_attention", "full_attention"],
num_attention_heads=4,
num_key_value_heads=2,
head_dim=16,
max_position_embeddings=128,
linear_key_head_dim=8,
linear_value_head_dim=8,
linear_num_key_heads=4,
linear_num_value_heads=8,
linear_conv_kernel_dim=4,
)
config._attn_implementation = attn_impl
return config
def _tiny_vlm_config(attn_impl: str = "flash_attention_2") -> Qwen3_5Config:
text_config = _tiny_text_config(attn_impl)
vision_config = Qwen3_5VisionConfig(
depth=1,
hidden_size=64,
intermediate_size=128,
num_heads=4,
out_hidden_size=text_config.hidden_size,
)
config = Qwen3_5Config(
text_config=text_config,
vision_config=vision_config,
image_token_id=120,
video_token_id=121,
vision_start_token_id=122,
vision_end_token_id=123,
)
config._attn_implementation = attn_impl
config.text_config._attn_implementation = attn_impl
return config
def _tiny_moe_config(attn_impl: str = "flash_attention_2") -> Qwen3_5MoeConfig:
config = Qwen3_5MoeConfig(
vocab_size=128,
hidden_size=64,
num_hidden_layers=2,
layer_types=["linear_attention", "full_attention"],
num_attention_heads=4,
num_key_value_heads=2,
head_dim=16,
max_position_embeddings=128,
linear_key_head_dim=8,
linear_value_head_dim=8,
linear_num_key_heads=4,
linear_num_value_heads=8,
linear_conv_kernel_dim=4,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=4,
num_experts_per_tok=2,
)
config._attn_implementation = attn_impl
return config
@pytest.mark.gpu
def test_qwen3_5_dense_matches_hf_state_keys_on_meta():
config = _tiny_text_config()
with torch.device("meta"):
hf_model = HFQwen3_5ForCausalLM(config)
prime_model = Qwen3_5ForCausalLM(config)
assert set(prime_model.state_dict()) == set(hf_model.state_dict())
for name, tensor in prime_model.state_dict().items():
assert tensor.shape == hf_model.state_dict()[name].shape, name
@pytest.mark.parametrize("attn_impl", ["flash_attention_3", "kernels-community/vllm-flash-attn3"])
def test_qwen3_5_full_attention_uses_custom_class(attn_impl: str):
config = _tiny_text_config(attn_impl=attn_impl)
with torch.device("meta"):
model = Qwen3_5Model(config)
assert isinstance(model.layers[1].self_attn, Qwen3_5GatedFlashAttention)
assert model.config._attn_implementation == "flash_attention_3"
assert "ALL_ATTENTION_FUNCTIONS" not in inspect.getsource(type(model.layers[1].self_attn).forward)
def test_qwen3_5_moe_full_attention_normalizes_fa3_hub_alias():
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeGatedFlashAttention,
Qwen3_5MoeModel,
)
config = _tiny_moe_config(attn_impl="kernels-community/vllm-flash-attn3")
with torch.device("meta"):
model = Qwen3_5MoeModel(config)
assert isinstance(model.layers[1].self_attn, Qwen3_5MoeGatedFlashAttention)
assert model.config._attn_implementation == "flash_attention_3"
def test_qwen3_5_context_parallel_setup_chain_text_and_vlm():
cp_group = MagicMock()
text_model = Qwen3_5ForCausalLM(_tiny_text_config())
linear_layer = text_model.model.layers[0]
text_model.model.layers[0] = torch.nn.Sequential(linear_layer)
setup_model_cp(text_model, cp_group, cp_rank=1, cp_world_size=2)
assert text_model.model._cp_group is cp_group
assert text_model.model._cp_rank == 1
assert text_model.model._cp_world_size == 2
assert linear_layer.linear_attn.cp_group is cp_group
vlm_config = _tiny_vlm_config()
vlm_config.vision_config._attn_implementation = "sdpa"
vlm_config.vision_config._attn_implementation_internal = "sdpa"
with torch.device("meta"):
vlm_model = Qwen3_5ForCausalLM(vlm_config)
setup_model_cp(vlm_model, cp_group, cp_rank=0, cp_world_size=2)
assert vlm_model.model.language_model._cp_group is cp_group
assert vlm_model.model.language_model.layers[0].linear_attn.cp_world_size == 2
def test_setup_model_cp_requires_hook_only_for_hybrid_models():
class HybridLayer(torch.nn.Module):
layer_type = "linear_attention"
class Inner:
layers = torch.nn.Sequential(torch.nn.Sequential(HybridLayer()))
class HybridNoHookModel:
model = Inner()
with pytest.raises(ValueError, match="set_context_parallel_attributes"):
setup_model_cp(HybridNoHookModel(), MagicMock(), cp_rank=0, cp_world_size=2)
class SoftmaxOnlyModel:
pass
setup_model_cp(SoftmaxOnlyModel(), MagicMock(), cp_rank=0, cp_world_size=2)
def test_qwen3_5_ring_patches_dense_flash_attention():
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
originals = {
cls: cls._compute_attention
for cls in (FlashAttention, AfmoeFlashAttention, Qwen3_5MoeGatedFlashAttention, Qwen3_5GatedFlashAttention)
}
try:
substitute_ring_attn(process_group=MagicMock(), heads_k_stride=1)
assert Qwen3_5GatedFlashAttention._compute_attention is not originals[Qwen3_5GatedFlashAttention]
finally:
for cls, method in originals.items():
cls._compute_attention = method
-192
View File
@@ -1,192 +0,0 @@
import pytest
import torch
from transformers import Qwen3_5MoeForCausalLM as HFQwen3_5MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeForCausalLM
from prime_rl.utils.cp import setup_model_cp
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
def get_model_pairs():
config = Qwen3_5MoeConfig(
vocab_size=256,
hidden_size=256,
num_hidden_layers=4,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=64,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=8,
num_experts_per_tok=2,
max_position_embeddings=512,
rms_norm_eps=1e-6,
linear_conv_kernel_dim=4,
linear_key_head_dim=32,
linear_value_head_dim=32,
linear_num_key_heads=4,
linear_num_value_heads=8,
)
config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.bfloat16):
hf_model = HFQwen3_5MoeForCausalLM._from_config(config)
prime_model = PrimeRLQwen3_5MoeForCausalLM._from_config(config)
with torch.no_grad():
state_dict = hf_model.state_dict()
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
def test_qwen3_5_moe():
hf_model, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.bfloat16):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(
input_ids,
position_ids=position_ids,
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=1000), f"Max grad diff: {grad_diff.abs().max()}"
def test_qwen3_5_moe_roundtrip():
"""Verify HF → PrimeRL → HF weight conversion is lossless at the state_dict level."""
hf_model, prime_model = get_model_pairs()
# Get original HF state_dict and the PrimeRL-converted version
original_hf_sd = hf_model.state_dict()
prime_sd = prime_model.state_dict()
assert prime_model.is_hf_state_dict(original_hf_sd)
assert not prime_model.is_prime_state_dict(original_hf_sd)
assert prime_model.is_prime_state_dict(prime_sd)
assert not prime_model.is_hf_state_dict(prime_sd)
# Convert PrimeRL → per-expert HF format
converted_hf_sd = prime_model.convert_to_hf(dict(prime_sd))
# Also convert original HF (fused) to per-expert format for comparison
# First convert original HF → PrimeRL, then back to per-expert HF
orig_prime_sd = dict(original_hf_sd)
prime_model.convert_to_prime(orig_prime_sd)
orig_roundtripped = dict(orig_prime_sd)
prime_model.convert_to_hf(orig_roundtripped)
# All non-expert keys should match exactly, expert keys should match after roundtrip
for key in orig_roundtripped:
assert key in converted_hf_sd, f"Missing key: {key}"
assert torch.equal(orig_roundtripped[key], converted_hf_sd[key]), f"Mismatch at {key}"
def test_qwen3_5_moe_router_replay():
"""When routed_experts are provided, the model uses them instead of computing routing."""
_, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.bfloat16):
input_ids = torch.randint(0, prime_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
seq_lens = torch.tensor([input_ids.shape[1]], device="cuda")
out_normal = prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
num_layers = prime_model.config.num_hidden_layers
topk = prime_model.config.num_experts_per_tok
routed_experts = torch.randint(0, prime_model.config.num_experts, (1, 100, num_layers, topk), device="cuda")
prime_model.zero_grad()
out_replay = prime_model(
input_ids,
position_ids=position_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
)
assert out_replay["logits"].shape == out_normal["logits"].shape
out_replay["logits"].sum().backward()
assert prime_model.model.embed_tokens.weight.grad is not None
def test_qwen3_5_moe_cp_patching():
"""Verify substitute_ring_attn patches Qwen3_5MoeGatedFlashAttention._compute_attention."""
from unittest.mock import MagicMock
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
# substitute_ring_attn rewrites _compute_attention on all three classes;
# snapshot every one so the patch can't leak into later tests via the
# untouched siblings.
originals = {
cls: cls._compute_attention for cls in (FlashAttention, AfmoeFlashAttention, Qwen3_5MoeGatedFlashAttention)
}
try:
mock_group = MagicMock()
substitute_ring_attn(process_group=mock_group, heads_k_stride=1)
assert Qwen3_5MoeGatedFlashAttention._compute_attention is not originals[Qwen3_5MoeGatedFlashAttention]
finally:
for cls, method in originals.items():
cls._compute_attention = method
def test_qwen3_5_moe_context_parallel_setup_hook():
from unittest.mock import MagicMock
config = Qwen3_5MoeConfig(
vocab_size=128,
hidden_size=64,
num_hidden_layers=2,
layer_types=["linear_attention", "full_attention"],
num_attention_heads=4,
num_key_value_heads=2,
head_dim=16,
moe_intermediate_size=64,
shared_expert_intermediate_size=64,
num_experts=4,
num_experts_per_tok=2,
max_position_embeddings=128,
linear_conv_kernel_dim=4,
linear_key_head_dim=8,
linear_value_head_dim=8,
linear_num_key_heads=4,
linear_num_value_heads=8,
)
config._attn_implementation = "flash_attention_2"
with torch.device("meta"):
model = PrimeRLQwen3_5MoeForCausalLM(config)
linear_layer = model.model.layers[0]
model.model.layers[0] = torch.nn.Sequential(linear_layer)
cp_group = MagicMock()
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
assert model.model._cp_group is cp_group
assert model.model._cp_rank == 1
assert model.model._cp_world_size == 2
assert linear_layer.linear_attn.cp_group is cp_group
assert linear_layer.linear_attn.cp_world_size == 2
if __name__ == "__main__":
test_qwen3_5_moe()
@@ -1,192 +0,0 @@
import pytest
import torch
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeTextRotaryEmbedding as HFQwen3_5MoeRotaryEmbedding,
)
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeRotaryEmbedding
from prime_rl.trainer.models.qwen3_5_moe.mrope import build_qwen3_5_mrope_position_ids
def _tiny_config() -> Qwen3_5MoeConfig:
return Qwen3_5MoeConfig(
vocab_size=128,
hidden_size=128,
num_attention_heads=2,
num_key_value_heads=1,
head_dim=64,
num_hidden_layers=1,
rope_parameters={
"rope_type": "default",
"rope_theta": 10000000,
"partial_rotary_factor": 0.25,
"mrope_section": [3, 3, 2],
"mrope_interleaved": True,
},
)
def test_qwen35_mrope_text_only_positions():
input_ids = torch.tensor([[10, 11, 12, 13]])
mm_token_type_ids = torch.zeros_like(input_ids)
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.arange(4).view(1, 1, -1).expand(3, 1, -1)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_single_image_with_surrounding_text():
input_ids = torch.tensor([[10, 11, 99, 99, 99, 99, 12]])
mm_token_type_ids = torch.tensor([[0, 0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.tensor(
[
[[0, 1, 2, 2, 2, 2, 4]],
[[0, 1, 2, 2, 3, 3, 4]],
[[0, 1, 2, 3, 2, 3, 4]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_adjacent_images_consume_multiple_grids():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 99, 99, 99, 99, 11]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.tensor(
[
[[0, 1, 1, 1, 1, 3, 3, 3, 3, 5]],
[[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]],
[[0, 1, 2, 1, 2, 3, 4, 3, 4, 5]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_packed_segments_reset_independently():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 11, 99, 99, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 0, 1, 1, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
seq_lens = torch.tensor([5, 5])
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=seq_lens,
)
expected_segment = torch.tensor(
[
[0, 1, 1, 1, 1],
[0, 1, 1, 2, 2],
[0, 1, 2, 1, 2],
]
)
torch.testing.assert_close(position_ids[:, 0, :5], expected_segment)
torch.testing.assert_close(position_ids[:, 0, 5:], expected_segment)
def test_qwen35_mrope_packed_matches_standalone_segments():
segment_input_ids = torch.tensor([[10, 99, 99, 99, 99, 11]])
segment_token_types = torch.tensor([[0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
standalone = build_qwen3_5_mrope_position_ids(
input_ids=segment_input_ids,
mm_token_type_ids=segment_token_types,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([segment_input_ids.shape[1]]),
)
packed = build_qwen3_5_mrope_position_ids(
input_ids=torch.cat([segment_input_ids, segment_input_ids], dim=1),
mm_token_type_ids=torch.cat([segment_token_types, segment_token_types], dim=1),
image_grid_thw=torch.cat([image_grid_thw, image_grid_thw], dim=0),
spatial_merge_size=2,
seq_lens=torch.tensor([segment_input_ids.shape[1], segment_input_ids.shape[1]]),
)
torch.testing.assert_close(packed[:, :, : segment_input_ids.shape[1]], standalone)
torch.testing.assert_close(packed[:, :, segment_input_ids.shape[1] :], standalone)
def test_qwen35_mrope_rejects_image_length_grid_mismatch():
input_ids = torch.tensor([[10, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4]])
with pytest.raises(ValueError, match="Image token group length"):
build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
def test_qwen35_mrope_rejects_video_tokens():
input_ids = torch.tensor([[10, 99]])
mm_token_type_ids = torch.tensor([[0, 2]])
with pytest.raises(ValueError, match="video MRoPE"):
build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
def test_qwen35_rotary_matches_hf_for_2d_and_3d_positions():
config = _tiny_config()
prime_rotary = Qwen3_5MoeRotaryEmbedding(config)
hf_rotary = HFQwen3_5MoeRotaryEmbedding(config)
hidden_states = torch.randn(1, 6, config.hidden_size)
text_positions = torch.arange(6).unsqueeze(0)
prime_cos, prime_sin = prime_rotary(hidden_states, text_positions)
hf_cos, hf_sin = hf_rotary(hidden_states, text_positions)
torch.testing.assert_close(prime_cos, hf_cos)
torch.testing.assert_close(prime_sin, hf_sin)
mrope_positions = torch.stack(
[
torch.tensor([[0, 1, 2, 2, 2, 4]]),
torch.tensor([[0, 1, 2, 2, 3, 4]]),
torch.tensor([[0, 1, 2, 3, 2, 4]]),
]
)
prime_cos, prime_sin = prime_rotary(hidden_states, mrope_positions)
hf_cos, hf_sin = hf_rotary(hidden_states, mrope_positions)
torch.testing.assert_close(prime_cos, hf_cos)
torch.testing.assert_close(prime_sin, hf_sin)
@@ -1,250 +0,0 @@
import pytest
import torch
from transformers import AutoConfig
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
)
from prime_rl.trainer.model import can_reinit_empty_buffers
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM
from prime_rl.utils.utils import default_dtype
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="flash_attention_2"
)
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
tc.hidden_size = 256
tc.num_hidden_layers = 2
tc.layer_types = ["linear_attention", "full_attention"]
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
tc.num_experts_per_tok = 2
tc.max_position_embeddings = 512
tc.linear_key_head_dim = 32
tc.linear_value_head_dim = 32
tc.linear_num_key_heads = 4
tc.linear_num_value_heads = 8
tc.use_cache = False
tc.rope_parameters["mrope_section"] = [3, 3, 2]
vc = config.vision_config
vc.depth = 2
vc.hidden_size = 128
vc.intermediate_size = 256
vc.num_heads = 4
vc.out_hidden_size = tc.hidden_size
# Special token IDs must fit within the tiny vocab
config.image_token_id = 250
config.video_token_id = 251
config.vision_start_token_id = 252
config.vision_end_token_id = 253
return config
def _make_image_inputs(config, device="cuda", dtype=torch.bfloat16):
"""Create minimal image inputs matching the vision config."""
vc = config.vision_config
patch_dim = vc.in_channels * vc.temporal_patch_size * vc.patch_size * vc.patch_size
image_grid_thw = torch.tensor([[1, 2, 2]], device=device)
num_patches = int(image_grid_thw.prod().item())
pixel_values = torch.randn(num_patches, patch_dim, device=device, dtype=dtype)
num_image_tokens = num_patches // (vc.spatial_merge_size**2)
return pixel_values, image_grid_thw, num_image_tokens
def _make_mm_token_type_ids(input_ids, image_token_id):
mm_token_type_ids = torch.zeros_like(input_ids)
mm_token_type_ids[input_ids == image_token_id] = 1
return mm_token_type_ids
def _seq_lens(input_ids: torch.Tensor) -> torch.Tensor:
return torch.tensor([input_ids.shape[1]], device=input_ids.device)
def test_vlm_forward():
"""Custom VLM produces logits for both text-only and multimodal inputs."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
vocab = config.text_config.vocab_size
# Text-only (avoid special token range 250-253)
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out_text = model(input_ids=input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
assert out_text["logits"].shape == (1, 20, vocab)
# Multimodal
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids_mm = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = _make_mm_token_type_ids(input_ids_mm, config.image_token_id)
out_mm = model(
input_ids=input_ids_mm,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=_seq_lens(input_ids_mm),
)
assert out_mm["logits"].shape == (1, input_ids_mm.shape[1], vocab)
def test_vlm_backward():
"""Gradients flow through both vision scatter and text model."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
out = model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=_seq_lens(input_ids),
)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
assert model.model.visual.patch_embed.proj.weight.grad is not None
def test_vlm_weight_load_from_hf():
"""Weights from HF VLM checkpoint load correctly into custom VLM after conversion.
Text model numerical match is already validated by test_qwen3_5_moe.py::test_qwen3_5_moe.
This test verifies that VLM weight conversion + loading produces a working model.
"""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
hf_model = HFQwen3_5MoeVLM._from_config(config)
prime_model = Qwen3_5MoeForCausalLM(config)
# Copy weights: HF -> PrimeRL (with MoE conversion)
with torch.no_grad():
hf_sd = hf_model.state_dict()
prime_model.convert_to_prime(hf_sd)
prime_model.load_state_dict(hf_sd)
inject_prime_lm_head(prime_model)
# Verify vision encoder weights match exactly (should be untouched by conversion)
for name, param in hf_model.model.visual.named_parameters():
prime_param = dict(prime_model.model.visual.named_parameters())[name]
assert torch.equal(param, prime_param), f"Vision weight mismatch: {name}"
# Verify model produces output after weight loading
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out = prime_model(input_ids=input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
assert out["logits"].shape[2] == config.text_config.vocab_size
assert not torch.isnan(out["logits"]).any()
def test_vlm_weight_roundtrip():
"""HF -> PrimeRL -> HF weight conversion is lossless (vision keys untouched, text keys converted)."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
hf_model = HFQwen3_5MoeVLM._from_config(config)
prime_model = Qwen3_5MoeForCausalLM(config)
hf_sd = hf_model.state_dict()
original_vision_key = "model.visual.blocks.0.mlp.linear_fc1.weight"
original_vision_weight = hf_sd[original_vision_key].clone()
# HF -> PrimeRL
prime_sd = dict(hf_sd)
prime_model.convert_to_prime(prime_sd)
assert any("language_model" in k and "mlp.experts.gate_proj" in k for k in prime_sd)
assert original_vision_key in prime_sd
# PrimeRL -> HF
roundtripped = dict(prime_sd)
prime_model.convert_to_hf(roundtripped)
# Original HF also needs roundtrip for expert format normalization
orig_rt = dict(hf_sd)
prime_model.convert_to_prime(orig_rt)
prime_model.convert_to_hf(orig_rt)
for key in orig_rt:
assert key in roundtripped, f"Missing key: {key}"
assert torch.equal(orig_rt[key], roundtripped[key]), f"Mismatch at {key}"
# Vision weights preserved through the whole roundtrip
assert torch.equal(roundtripped[original_vision_key], original_vision_weight)
def test_vlm_router_replay():
"""routed_experts bypasses router computation in VLM multimodal forward."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
vocab = config.text_config.vocab_size
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
seq_len = input_ids.shape[1]
num_layers = config.text_config.num_hidden_layers
topk = config.text_config.num_experts_per_tok
routed_experts = torch.randint(0, config.text_config.num_experts, (1, seq_len, num_layers, topk), device="cuda")
out = model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
seq_lens=_seq_lens(input_ids),
)
assert out["logits"].shape == (1, seq_len, vocab)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
def test_vlm_meta_device_and_buffer_reinit():
"""Model can be created on meta device and buffers reinitialized."""
config = _tiny_vlm_config()
with torch.device("meta"):
model = Qwen3_5MoeForCausalLM.from_config(config)
assert can_reinit_empty_buffers(model)
model.to_empty(device="cuda")
model.init_buffers_post_meta()
lm_inv = model.model.language_model.rotary_emb.inv_freq
vis_inv = model.model.visual.rotary_pos_emb.inv_freq
assert lm_inv.device.type == "cuda"
assert vis_inv.device.type == "cuda"
assert lm_inv.abs().sum() > 0
assert vis_inv.abs().sum() > 0
+1 -2
View File
@@ -6,7 +6,6 @@ from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaForCausalLM
from prime_rl.trainer.models.nemotron_h import NemotronHForCausalLM
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM
from prime_rl.utils.weights import resolve_wire_dtype
@@ -31,7 +30,7 @@ def test_resolve_wire_dtype():
[
(NemotronHForCausalLM, "model.layers.0.mamba.A_log", "model.layers.0.mamba.in_proj.weight"),
(Qwen3_5ForCausalLM, "model.layers.0.linear_attn.A_log", "model.layers.0.self_attn.q_proj.weight"),
(Qwen3_5MoeForCausalLM, "model.layers.0.linear_attn.norm.weight", "model.layers.0.mlp.experts.gate_proj"),
(Qwen3_5ForCausalLM, "model.layers.0.linear_attn.norm.weight", "model.layers.0.mlp.experts.gate_proj"),
(Glm4MoeForCausalLM, "model.layers.0.mlp.router.selection_bias", "model.layers.0.self_attn.q_proj.weight"),
(GlmMoeDsaForCausalLM, "model.layers.0.mlp.router.selection_bias", "model.layers.0.self_attn.q_proj.weight"),
(DeepseekV4ForCausalLM, "model.layers.0.attn_hc.fn", "model.layers.0.self_attn.q_b_proj.weight"),
Generated
+22 -8
View File
@@ -142,6 +142,7 @@ overrides = [
{ name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'", specifier = ">=9.15" },
{ name = "nvidia-cutlass-dsl", specifier = "==4.6.2" },
{ name = "openenv-core" },
{ name = "tilelang", specifier = "==0.1.12" },
{ name = "torch", marker = "sys_platform != 'linux'", specifier = ">=2.13.0" },
{ name = "torch", marker = "sys_platform == 'linux'", specifier = ">=2.13.0", index = "https://download.pytorch.org/whl/cu130" },
{ name = "transformers", specifier = "==5.6.2" },
@@ -396,6 +397,7 @@ dependencies = [
]
sdist = { url = "https://files.pythonhosted.org/packages/6d/3d/4b9226cd45aa800a6904603dda9b323d728f3c3869952a673f3483b78b19/apache_tvm_ffi-0.1.11.tar.gz", hash = "sha256:153cd2c5a9717804cb0bcd9b2709f22a1e5f80ed05b5a490faf5949b136eedba", size = 2798354, upload-time = "2026-05-04T17:48:43.852Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/05/9d/0f81ca556e5836b3ca64818cdae3f47dc7822bd35d22ddef7a54106d801d/apache_tvm_ffi-0.1.11-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:6ae51cc7df415b5f373a9df4baa1165a65608e519bea81e7dd23428f00eeb689", size = 2418793, upload-time = "2026-05-04T17:47:57.879Z" },
{ url = "https://files.pythonhosted.org/packages/2a/a9/f48e5dd4ae1f6f0c5ffac259c0a9531b7d6a7c0a4c45bc2229d55de6adf8/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:da2c8d07fdc737d1ba75f4de25c29f156905b9dc980f1da90c395b4db525f522", size = 2605176, upload-time = "2026-05-04T17:47:59.676Z" },
{ url = "https://files.pythonhosted.org/packages/36/99/2848df4e8ed5bf51df1d286d1718510584fa61e88adbc9c5b23d71b38f7c/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:78aa1857b04a2ea718317041ab3f01288b3d496e6036eb1b99ebdc9da0fdaef5", size = 2725887, upload-time = "2026-05-04T17:48:01.381Z" },
{ url = "https://files.pythonhosted.org/packages/7d/80/963c991934a4eb0fa0c0178f51963333fe14a96b732009da642b6bf6b42e/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a8b845c8dff498fb981c1dda36c954549204191b485a385845e604966594d0b2", size = 2513121, upload-time = "2026-05-04T17:48:03.43Z" },
@@ -3311,18 +3313,20 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
[[package]]
name = "mamba-ssm"
version = "2.3.1"
source = { registry = "https://pypi.org/simple" }
version = "2.3.2.post1"
source = { git = "https://github.com/state-spaces/mamba?rev=f577286#f577286d052741c35d39cd43bdc3fad27120f22c" }
dependencies = [
{ name = "apache-tvm-ffi" },
{ name = "einops" },
{ name = "ninja" },
{ name = "packaging" },
{ name = "quack-kernels" },
{ name = "setuptools" },
{ name = "tilelang" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
{ name = "transformers" },
{ name = "triton" },
]
sdist = { url = "https://files.pythonhosted.org/packages/34/67/ec89aa703da194a813e35d2ea2de8f74a7ce6991a120a29f3a0c5e30d4b9/mamba_ssm-2.3.1.tar.gz", hash = "sha256:4d529477ad94753962216d583fc8f1c127c717b7d7c875d6bbb9376366d0d761", size = 121707, upload-time = "2026-03-10T09:27:34.798Z" }
[[package]]
name = "markdown"
@@ -3584,6 +3588,7 @@ dependencies = [
]
sdist = { url = "https://files.pythonhosted.org/packages/0e/4a/c27b42ed9b1c7d13d9ba8b6905dece787d6259152f2309338aed29b2447b/ml_dtypes-0.5.4.tar.gz", hash = "sha256:8ab06a50fb9bf9666dd0fe5dfb4676fa2b0ac0f31ecff72a6c3af8e22c063453", size = 692314, upload-time = "2025-11-17T22:32:31.031Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a8/b8/3c70881695e056f8a32f8b941126cf78775d9a4d7feba8abcb52cb7b04f2/ml_dtypes-0.5.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a174837a64f5b16cab6f368171a1a03a27936b31699d167684073ff1c4237dac", size = 676927, upload-time = "2025-11-17T22:31:48.182Z" },
{ url = "https://files.pythonhosted.org/packages/54/0f/428ef6881782e5ebb7eca459689448c0394fa0a80bea3aa9262cba5445ea/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a7f7c643e8b1320fd958bf098aa7ecf70623a42ec5154e3be3be673f4c34d900", size = 5028464, upload-time = "2025-11-17T22:31:50.135Z" },
{ url = "https://files.pythonhosted.org/packages/3a/cb/28ce52eb94390dda42599c98ea0204d74799e4d8047a0eb559b6fd648056/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ad459e99793fa6e13bd5b7e6792c8f9190b4e5a1b45c63aba14a4d0a7f1d5ff", size = 5009002, upload-time = "2025-11-17T22:31:52.001Z" },
]
@@ -5033,6 +5038,7 @@ all = [
{ name = "flash-attn-3", marker = "sys_platform == 'linux'" },
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
{ name = "nixl", marker = "sys_platform == 'linux'" },
@@ -5040,7 +5046,7 @@ all = [
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
{ name = "quack-kernels", marker = "sys_platform == 'linux'" },
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
{ name = "tilelang", marker = "sys_platform == 'linux'" },
{ name = "tilelang" },
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
{ name = "torchao", version = "0.18.0+git5f2baf9d5", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
@@ -5084,12 +5090,13 @@ flash-attn-cute = [
gpu = [
{ name = "dion", marker = "sys_platform == 'linux'" },
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
{ name = "tilelang", marker = "sys_platform == 'linux'" },
{ name = "tilelang" },
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
{ name = "torchao", version = "0.18.0+git5f2baf9d5", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
@@ -5144,6 +5151,7 @@ requires-dist = [
{ name = "flash-linear-attention", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/fla-org/flash-linear-attention" },
{ name = "jaxtyping", specifier = ">=0.3.2" },
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "mamba-ssm", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/state-spaces/mamba?rev=f577286" },
{ name = "modelexpress", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = "==0.3.0" },
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.3.10.post2" },
{ name = "msgspec", specifier = ">=0.18" },
@@ -5214,7 +5222,7 @@ dev = [
{ name = "pytest-asyncio", specifier = ">=0.23" },
{ name = "ruff", specifier = ">=0.12.1" },
]
mamba-ssm = [{ name = "mamba-ssm", marker = "sys_platform == 'linux'", specifier = ">=2.3.0" }]
mamba-ssm = [{ name = "mamba-ssm", marker = "sys_platform == 'linux'", git = "https://github.com/state-spaces/mamba?rev=f577286" }]
[[package]]
name = "prime-rl-configs"
@@ -7139,7 +7147,9 @@ dependencies = [
{ name = "ml-dtypes" },
{ name = "numpy" },
{ name = "psutil" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
{ name = "setuptools", marker = "sys_platform != 'linux'" },
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
{ name = "torch-c-dlpack-ext" },
{ name = "tqdm" },
{ name = "typing-extensions" },
@@ -7147,6 +7157,7 @@ dependencies = [
]
sdist = { url = "https://files.pythonhosted.org/packages/6d/9a/5776adb5b6e03e141c8cff020e16c45b87c9b7a7a5bdfe83416d6cc23933/tilelang-0.1.12.tar.gz", hash = "sha256:595b39581d099a53f875bd8d553863e7e4f58998052b58764f5472cbfbb87043", size = 93565090, upload-time = "2026-07-08T04:22:52.901Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/13/51/4ae1fb532406082a4ebf16c890f5f98db14b8588f2c486334ba23578b4bc/tilelang-0.1.12-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:8741d6cd519782645d55c17abd8986402c62948bc2122d3417c445d11de5dd16", size = 38347295, upload-time = "2026-07-08T04:22:35.691Z" },
{ url = "https://files.pythonhosted.org/packages/d1/53/f281a0bd9ee7e03d6a97828fc0e443321ed26ea2b0bd74bf9f1d9451d30f/tilelang-0.1.12-cp38-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bbeb5573cbe2544a51a5c9a6cc737c5e3b5c2d95411caa3687fd9b08eb9d5f97", size = 50501074, upload-time = "2026-07-08T04:22:39.973Z" },
{ url = "https://files.pythonhosted.org/packages/fb/a4/ff0b14d00d29fe418063cd97490f55aa9cad6f981a6fbbf29124b024637d/tilelang-0.1.12-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:a1701eba4ad603d73f1b128b88f6a2350f1b1161729e5b2d1e540a1ec7a82d52", size = 46281933, upload-time = "2026-07-08T04:22:44.244Z" },
]
@@ -7289,10 +7300,12 @@ name = "torch-c-dlpack-ext"
version = "0.1.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/37/de/921b6491efce5c389a5ef9bbed3d2d6660005840dae488124173180859ab/torch_c_dlpack_ext-0.1.5.tar.gz", hash = "sha256:d06f0357d575d22a168cc77acb9020fc4bae30968ceb6718a055dcbe92bacabe", size = 12913, upload-time = "2026-01-12T11:25:08.484Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b1/67/10d236698525d7b7db4d74ec0a4b01f5b2db33968995fdd9ac6b4635e327/torch_c_dlpack_ext-0.1.5-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:c0f2bd51fcd99c0e5b50314e1985f2728c4941bfa821f065e6c30951d1f995ca", size = 5291237, upload-time = "2026-01-12T11:24:44.011Z" },
{ url = "https://files.pythonhosted.org/packages/87/06/8d760997307a5c3be4384424667bf31aae0a42060838c532c7d846516175/torch_c_dlpack_ext-0.1.5-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3562ee411258676f9c38b8ad39306d1c8d027b6a86f6a87c920d2d009a9d1510", size = 443069, upload-time = "2026-01-12T11:24:45.451Z" },
{ 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" },
]
@@ -8647,6 +8660,7 @@ version = "4.15.4.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8a/8e/0c8f17309549d2e5cde9a3ccefa6365437f1e7bafe71878eaf9478e47b18/z3_solver-4.15.4.0.tar.gz", hash = "sha256:928c29b58c4eb62106da51c1914f6a4a55d0441f8f48a81b9da07950434a8946", size = 5018600, upload-time = "2025-10-29T18:12:03.062Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/63/33/a3d5d2eaeb0f7b3174d57d405437eabb2075d4d50bd9ea0957696c435c7b/z3_solver-4.15.4.0-py3-none-macosx_13_0_arm64.whl", hash = "sha256:407e825cc9211f95ef46bdc8d151bf630e7ab2d62a21d24cd74c09cc5b73f3aa", size = 37052538, upload-time = "2025-10-29T18:11:46.233Z" },
{ url = "https://files.pythonhosted.org/packages/21/c9/bb51a96af0091324c81b803f16c49f719f9f6ea0b0bb52200f5c97ec4892/z3_solver-4.15.4.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e103a6f203f505b8b8b8e5c931cc407c95b61556512d4921c1ddc0b3f41b08e", size = 29268352, upload-time = "2025-10-29T18:11:53.032Z" },
{ url = "https://files.pythonhosted.org/packages/bf/2e/0b49f7e4e53817cfb09a0f6585012b782dfe0b666e8abefcb4fac0570606/z3_solver-4.15.4.0-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:62c7e9cbdd711932301f29919ad9158de9b2f58b4d281dd259bbcd0a2f408ba1", size = 27226534, upload-time = "2025-10-29T18:11:55.59Z" },
]