Compare commits

...
Author SHA1 Message Date
cea63f9ef3 feat(deepseek_v4): sparse attention kernels (#3479)
Adds a TileLang implementation of the flash-attention style kernel for
DS V4. Based on the similar kernel used for GLM. The kernel is wired
through the DS V4 model and the attention arguments are refactored to
naturally adapt to the shape expected by the efficient kernel (e.g. no
more `attention_mask` realization).

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:11:30 -04:00
6a360c3029 feat(trainer): add runtime gate/up and qkv fusions (#3451)
## Summary

Adds runtime parameter fusions, on by default: `model.fusions` packs
parameters that are always computed together into one tensor, turning
several GEMMs into one. Fusions are runtime-only — checkpoints keep the
canonical parameter names and shapes, so a run can enable or disable one
at any point and still load its own checkpoints.

```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"]   # default; [] disables
raise_on_fail = false          # default: a fusion no module supports logs a warning
shard_fused_on_dim1 = false    # default; experimental zero-copy checkpointing, see Notes
```

- **`gate_up`** — each gated MoE expert's `gate_proj` and `up_proj`
become one `[num_experts, 2 * intermediate_size, hidden_size]` weight.
The forward is a single grouped GEMM whose transpose and chunk are
views; there is no weight reshape.
- **`qkv`** — an attention layer's `q_proj`, `k_proj` and `v_proj` (and
their biases) become one `nn.Linear`. `FlashAttention.project_qkv` is
shared with `LagunaFlashAttention` so both support it.

## Review fixes and verification (2026-09-08)

Review found and fixed three previously unchecked checkpoint cases:

- **Exports and model-only resume:** DCP returns `{}` when no optimizers
are supplied. Both fusion optimizer-state translators now preserve that
empty dictionary instead of raising `KeyError: 'state'`.
- **AdamW resume with optimizer-state CPU offload:** packed parameters
restored their moments but lost scalar state, including AdamW's step
counter. The write-back now restores scalar tensors and non-tensor state
as well as packed moments.
- **Full CPU offload checkpoint save:** splitting packed CPU optimizer
tensors requires CPU collectives. Both training entrypoints now enable
Gloo alongside NCCL when full offload is enabled.

Verified on H200s through Slurm job **232**:

- The complete existing unit suite and Ruff checks passed.
- All **32 distributed checkpoint combinations** passed: AdamW/Muon,
fused/unfused save and load, default/dimension-1 sharding, and
optimizer-state CPU offload on/off. Canonical weights, optimizer state,
and the next update with identical gradients were bitwise exact.
- Full CPU offload completed model-only resume/save and optimizer
resume/save. All **311 model tensors** were exact after model-only
resume; **931 model/master/step tensors** were checked across optimizer
resume, with unchanged weights and correctly incremented counters.
- Expert outputs and matrix-weight gradients, and QKV projections
with/without bias, were exact. BF16 input-gradient relative differences
were about 0.29%; bias-reduction variation also occurred in repeated
unfused calculations.
- All **11 RL/SFT training, resume, and export checks** passed (6 SFT, 5
RL). BF16 and FP8 exports reload in HF, and direct DCP-to-FP8 matches
chained conversion byte-for-byte. RL completed 20 steps with final
reward **0.8362** and passed its mismatch-KL checks.

The dashboard browser checks cannot install OS dependencies on this
cluster because they require sudo. The prior A6000 benchmark CI job was
cancelled without executing any steps; its hardware-specific baseline
was not validated on H200. Blackwell-only MXFP8 was not exercised.

Verification artifacts: `/home/matej/prime-rl-verify/pr3451-20260908/`.
This review changes only the fusion helpers and RL/SFT distributed
initialization; it adds no tests or skill changes.

## Design

A fusion is a function that replaces some of a module's parameters with
one `PackedParameterSpec`, which owns the split sizes, the packing
dimension, and the canonical names it stands in for. Everything else
falls out of that description, so a new fusion adds no machinery:

- **Checkpoints** — state-dict hooks registered alongside the packing
swap the packed entry for its canonical entries on the way out and back
on the way in. The canonical entries are views of the packed storage
when the packing dimension is unsharded (`gate_up`: experts shard on dim
0, pack on dim 1); a DTensor sharded along the packing dimension (`qkv`:
FSDP shards dim 0) is unsharded by the split, so those entries are
replicated copies. Anything that loads into the state dict in place
therefore packs the loaded entries back explicitly
(`write_back_loaded_packed_parameters` after the HF weight load,
`write_back_loaded_packed_optimizer_state` /
`join_loaded_optimizer_state_for_runtime` on resume). DCP therefore
writes `gate_proj`/`up_proj` and `q_proj`/`k_proj`/`v_proj` and never
sees the packed layout. The optimizer has no equivalent hook (its
`state_dict()` hooks fire while state is still keyed by integer param
ids, before DCP maps them to FQNs), so the same translation is applied
explicitly around `get_state_dict` in `AppState`.
- **Muon** — `PackedParameterSpec.muon_matrix_partitions` yields the
split sizes when the packing is on the output dimension. Those go to
Dion's new `matrix_partitions` argument, which orthogonalizes each
logical matrix separately on the one physical parameter, with a
per-partition learning-rate adjustment. A packed parameter therefore
trains exactly as the parameters it replaces would — including
per-projection scaling for grouped-query attention — while keeping a
single momentum tensor. Uses the merged matrix-partition support in the
pinned `samsja/dion@99e5f7e` (samsja/dion#3).

Modules advertise fusions through `supported_fusions`; requesting one
that no module supports logs a warning, or fails at startup with
`raise_on_fail = true`. Fusions are skipped when LoRA is enabled, since
it targets the unfused projections.

## Performance

Qwen3-30B-A3B, 8×H200, EP=8, `seq_len=8192`, torch EP dispatch,
selective AC, compile, no offload. Mean throughput over steps 3–6:

| precision | unfused | fused | |
|---|---|---|---|
| BF16 | 37636 tok/s (MFU 13.3%) | 37352 tok/s (MFU 13.2%) | −0.8% |
| FP8 (`quantization.type=fp8` + `moe.compute.type=deepgemm_fp8`) |
30594 tok/s (MFU 10.8%) | 34062 tok/s (MFU 12.0%) | **+11.3%** |

BF16 is unchanged, as expected: the separate GEMMs already read the same
activation, so there is nothing to save. The gain is under FP8, where
each GEMM quantizes its activation independently — unfused casts the
same tensor 3× for q/k/v and 2× for gate/up, fused casts it once. Peak
memory is unchanged (101.8 → 102.0 GiB).

## Validation

Correctness, on GPU:

- Forward output and all weight gradients of the fused grouped experts
are **bitwise identical** to the unfused module; the packed q/k/v
projections are bitwise identical to the separate ones. Only the MoE
input gradient differs (max abs `1.5e-5` on a `2.4e-3` scale), by one
bf16 accumulation rounding from doing one `[T, 2I]` dgrad instead of two
`[T, I]`.
- Muon updates on a packed parameter are **bitwise identical** to
updating the parameters it replaces, over multiple steps, for both
fusions.
- All four fused/unfused optimizer checkpoint round trips are exact,
including the next optimizer update after each. For `gate_up` the
checkpoint entries alias the packed storage; for `qkv` under FSDP they
are replicated copies of the q/k/v weights and their optimizer state,
materialized transiently on every rank at load and checkpoint time (~1
GB bf16 weights + ~2 GB fp32 Muon momentum for Qwen3-30B-A3B).
`shard_fused_on_dim1 = true` (experimental, default off) shards fused
2-D parameters along dim 1 via FSDP2's `shard_placement_fn`, so the
split stays a local view: the q/k/v weight entries alias the packed
storage and `model.state_dict()` holds 0.1 MiB extra instead of 72 MiB
on the mini model (0 / 144 → 72 / 72 weight entries aliasing; biases
stay copies, having no second dimension). It is not a correctness fix on
its own — biases would still load as zero and the optimizer-offload
resume path replaces its state tensors after the template is built, so
the explicit write-back stays in place with the flag on or off.
Constraints: `hidden_size % dp_shard == 0` (FSDP2 raises otherwise) and
an extra chunk-cat per all-gather of dim-1 shards. #3486 measured the
placement alone and is closed in favour of this flag.
- DCP metadata for a fused EP=2 checkpoint contains 94 `gate_proj` and
94 `up_proj` entries and zero `gate_up_proj` entries.

End to end on SLURM (2 GPUs, EP=2, compiled, Muon, both fusions unless
noted):

| run | result |
|---|---|
| BF16 fake-data training + checkpoint save | ✅ |
| resume: fused ckpt → fused runtime | ✅ |
| resume: fused ckpt → **unfused** runtime | ✅ |
| resume: unfused ckpt → **fused** runtime | ✅ |
| optimizer-state CPU offload, save + resume | ✅ |
| DeepGEMM FP8 expert compute | ✅ |
| pretrained `mini-glm-moe` RL run with vLLM weight reload | ✅ mismatch
KL `0.0001` at both steps |

Plus `ruff format`/`ruff check`, and `pytest tests/unit/train/models
tests/unit/test_configs.py` (`215 passed, 3 skipped`), including a new
`tests/unit/train/models/test_fusions.py`.

## Notes

- `pyproject.toml` and `uv.lock` pin `samsja/dion@99e5f7e`, which
contains the merged matrix-partition support from samsja/dion#3.

## Verification on merged `main` (2026-09-04)

Branch merged with `main` (no conflicts) and re-verified on 8×H200 nodes
via SLURM. `ruff check`/`ruff format --check` clean; `pytest tests/unit
-m "not gpu"`: 536 passed, 1 skipped; `pytest tests/unit -m gpu`: 81
passed, 8 skipped.

**Numerics against an fp32 reference** (`samsja/mini-glm-moe`, single
GPU, no FSDP, 512 random tokens; reference is HF `Glm4MoeForCausalLM` in
fp32 eager). Whole-model outputs are not bitwise identical between fused
and unfused bf16 — the packed GEMMs take a different accumulation path —
but the fused model is exactly as close to fp32 as the unfused one:

| model (bf16) | logits mean abs diff vs fp32 | KL(fp32 ‖ model) | grad
rel. err vs fp32: q/k/v · experts gate/up · rest |
|---|---|---|---|
| unfused | 7.64e-3 | 3.97e-5 | 4.52e-2 · 4.96e-2 · 4.48e-2 |
| fused `qkv` | 7.64e-3 | 3.82e-5 | 4.14e-2 · 4.81e-2 · 4.12e-2 |
| fused `gate_up` | 7.22e-3 | 3.83e-5 | 4.52e-2 · 5.19e-2 · 4.51e-2 |
| fused both | 7.27e-3 | 3.88e-5 | 4.31e-2 · 4.87e-2 · 4.27e-2 |
| HF bf16 sdpa (noise floor) | 7.72e-3 | 4.48e-5 | 4.48e-2 · 5.19e-2 ·
4.46e-2 |

Fused vs unfused state dicts are bitwise identical after loading, and
each packed parameter equals the concatenation of the parameters it
replaces.

**Fake-data training matrix** (`mini-glm-moe`, 2 GPUs, EP=2, Muon,
compile + AC on, `ckpt.interval=5`, 10 steps), all runs complete without
errors:

| run | result |
|---|---|
| fused / unfused, optimizer offload on / off | ✅ losses agree to ≤ 5e-4
relative on every step |
| `shard_fused_on_dim1 = true`: load, resume (both offload paths), fused
↔ unfused resume, 10-step loss vs unfused | ✅ (verified with this code
before the flag existed; see #3486 for the measurements) |
| fused ckpt → fused resume, fused ckpt → unfused resume | ✅ post-resume
losses agree to ≤ 1e-3 relative |
| unfused ckpt → fused resume vs unfused ckpt → unfused resume | ✅ |
| the same three resumes with optimizer-state CPU offload | ✅ |
| DeepGEMM FP8 (`quantization.type=fp8`,
`moe.compute.type=deepgemm_fp8`), fused and unfused | ✅ |

(Resumed runs deliberately diverge from the un-interrupted run:
`FakeDataLoader` reseeds from a batch counter that restarts at 0, so a
resume replays the first batches. Fused and unfused resumes see
identical data and are compared against each other.)

**RL end to end** (`configs/ci/integration/reverse-text-moe/start.toml`,
custom impl, EP=2, 2 trainer GPUs + 1 vLLM GPU, 20 steps, filesystem
weight broadcast): fused `mismatch_kl/all/mean` 1.8e-4–2.2e-4 on every
step vs 1.9e-4–2.1e-4 unfused.

**Fix included in this branch.** Before `fix(trainer): load packed
parameters and their optimizer state explicitly`, the same runs showed
the `qkv` fusion training from zero attention weights: the HF weight
load wrote into the replicated q/k/v copies, every q/k/v tensor in a
fused checkpoint was exactly 0, the fused/unfused step-1 loss differed
by 20% reproducibly under both bf16 and FP8, and the RL run aborted with
no trainable rollouts. A fused resume also lost the Muon momentum of
every packed parameter (verified with lr=0: momentum after resume was
1.00× instead of 1.95× the saved value; both fusions with optimizer CPU
offload, `qkv` without). With the fix, loaded weights are bitwise
identical to the source and momentum is restored on both resume paths.
Full optimizer offload (`model.full_offload`) with fusions was not
exercised. MXFP8 expert compute needs Blackwell and could not be tested
on H200.

## Cluster verification with merged Dion (2026-09-05)

Pinned `samsja/dion@99e5f7e` (merged samsja/dion#3) and refreshed
`uv.lock`; its tree is identical to the prior fork pin. Synced with `uv
sync --all-extras --inexact`, then ran GPU verification through Slurm on
H200s:

- 10 prime-rl fusion/activation-checkpointing tests, 13 Dion single-GPU
tests, and 4 Dion distributed tests passed.
- All **16 distributed checkpoint combinations** passed: fused/unfused
save and load, default/dimension-1 sharding, and optimizer-state offload
on/off. Canonical weights, optimizer state, and the next Muon update
with identical supplied gradients were **bitwise exact**.
- **13 compiled EP=2 training/resume variants** completed on
`samsja/mini-glm-moe` (512-token fake batches): both fusion modes, all
four resume combinations, state offload, dimension-1 sharding, and
DeepGEMM FP8. Fused/unfused BF16 losses differed by at most **0.031%**
across the three initial steps.
- All **406 pretrained model tensors** were bitwise exact in the zero-LR
checkpoint and after its offloaded resume. All 13 variants saved
canonical model/optimizer projection names, with no packed `qkv_proj` or
`gate_up_proj` entries.
- The real **2-step RL run with vLLM weight reloads** completed with
mismatch KL **0.00019046 / 0.00019005**. Fake-data runs use random
inference logprobs, so their mismatch KL is not a trainer/inference
agreement metric.
- H200 module checks: gate/up outputs and matrix-weight gradients, plus
Q/K/V outputs with/without bias, were exact. BF16 MoE input-gradient
relative differences were ~0.29%. Bias reductions in an all-BF16 module
varied ~1.5%, also reproduced by repeating the unfused calculation
itself.

Slurm evidence: 147/148 (test suites), 149 (RL), 150/158 (checkpoint
equivalence), 153 (training matrix), 157 (saved checkpoint inspection).
Job 148's test suites passed before an overly strict ad-hoc BF16 bias
assertion stopped that script; the numerical diagnostic was resolved
separately. Full optimizer offload and Blackwell-only MXFP8 were not
exercised.

## CI collection fix (2026-09-05)

The `reverse_text` integration job failed before running any tests
because importing `prime_rl.utils.weights` first triggered a circular
import through the model registry and `fusions`. Import
`PreTrainedModelPrimeRL` inside `convert_state_dict_to_hf`, its only
use, so loading weight utilities no longer eagerly imports the model
registry.

Reproduced the failing import locally before the fix. After the fix,
standalone collection of `test_reverse_text.py` succeeds (6 tests), the
complete integration suite collects (38 tests), and all 6 fusion unit
tests pass. Ruff lint/format checks and `git diff --check` pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core training paths (FSDP sharding, weight load, DCP optimizer
state, Muon) and defaults fusions on; incorrect packing/load logic would
corrupt weights or momentum on resume, though extensive
checkpoint/resume testing is described in the PR.
> 
> **Overview**
> Adds **runtime parameter fusions** (on by default via
`[trainer.model.fusions]`) that pack related weights into single tensors
so MoE **gate/up** and attention **q/k/v** run as one GEMM each, while
**checkpoints and exports still use canonical names** (`gate_proj`,
`q_proj`, etc.).
> 
> A new **`fusions` module** implements packing (`PackedParameterSpec`),
state-dict hooks, HF/DCP load **write-back** for packed weights, and
explicit **optimizer-state split/join** around distributed checkpoint
save/load (including CPU-offload resume). Optional
**`shard_fused_on_dim1`** wires FSDP2 **`shard_placement_fn`** for
experimental zero-copy fused weight/optimizer I/O.
> 
> **Attention and MoE layers** advertise fusions through
`supported_fusions`; forwards use **`project_qkv`** / a single grouped
**`gate_up`** GEMM when fused. Fusions are **skipped with LoRA**.
**Muon** gets **`matrix_partitions`** from packed params via an updated
**dion** pin. Docs and unit tests cover config and canonical state-dict
behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
52e736c685485fdbca109c86721017ab8065f65d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:47:47 +02:00
samsjaandGitHub 04a61d3b75 fix: warm Muon all-to-all connections during optimizer initialization (#3490)
## Summary

Automatically establish the NCCL peer connections used by Dion's Muon
optimizer immediately after constructing Muon and before returning it to
the trainer.

The warm-up runs only for Muon. It covers the exact main optimizer
process group and, when expert parameters use expert parallelism, the
separate expert-shard process group. Single-rank and non-NCCL groups
remain no-ops; AdamW, SGD, and other optimizers are unchanged.

This is a required correctness workaround for a reproducible multi-node
GLM-4.5-Air first-step deadlock. The source now documents that optimizer
refactors must preserve the warm-up, its process groups, and its
placement between Muon construction and the first optimizer step.

## Failure signature

Pretrained GLM-4.5-Air training with Muon reproducibly stalled while
submitting the first optimizer all-to-all on two nodes. All 16 ranks
reached the collective, but only rank 0 enqueued it successfully; ranks
1–15 remained inside submission until the NCCL watchdog fired.

The clearest controlled failure was job 1182:

- Nodes `qpn01gpu009` and `qpn01gpu011`, 16 GPUs total.
- Pretrained eight-layer GLM-Air reproduction with CP4, EP8/automatic
expert mesh, BF16 compute, and optimizer-state offload.
- First Muon all-to-all was NCCL sequence 67 with 50,331,648 BF16
elements per rank.
- The watchdog fired after 182 seconds.
- Setting `NCCL_CUMEM_ENABLE=0` did not resolve it.

This was not a generic inability of the nodes to communicate: Adam
training and standalone all-reduce/all-to-all controls completed on the
same cluster. Fake-weight and reduced-model tests further isolated the
trigger to Muon's pretrained-model initialization state and first bulk
all-to-all.

## Implementation

`_warmup_muon_mesh` takes the `DeviceMesh`, resolves its single process
group, and performs a bulk BF16 list all-to-all matching Dion's
communication path, waits for completion, and synchronizes CUDA before
releasing its temporary buffers. A scalar collective is intentionally
not used because it may not initialize the same bulk-transfer peer
channels. Meshes with more than one dimension (the replicate-only world
mesh) have no single group and are skipped; Dion's Muon only accepts 1-D
meshes there anyway.

The ordering is part of the fix:

1. Construct the Dion Muon optimizer.
2. Warm Muon's main distributed NCCL group.
3. If expert parameters and EP are active, warm the independent
expert-shard NCCL group.
4. Return the optimizer only after both required warm-ups complete.

The temporary allocation is approximately 12 MiB per peer for send plus
receive buffers. No config flag is introduced because making this
optional would allow the known deadlock to recur.

Patch scope remains one optimizer source file. There are no
trainer-loop, dependency, precision, optimizer-offload, allocator, Dion,
or experiment-config changes.

## Validation

- Ruff lint/format and whitespace checks passed.
- Existing configuration tests passed: 70 passed, 67 deselected.
- Job 1183, reduced pretrained model with early connection warm-up: one
full step passed on all 16 ranks; 42.6 seconds, loss 15.4930, gradient
norm 49.0578, clean exit.
- Job 1184, full 46-layer pretrained GLM-4.5-Air with the earlier
pre-model-load placement: three fake-data steps passed with finite
losses and nonzero gradient norms.
- Job 1185, full 46-layer model with the final optimizer-construction
placement in this PR: three steps passed on all 16 ranks. Losses were
13.2325, 13.1564, and 13.3399; gradient norms were 27.9833, 27.8885, and
31.8815; clean exit.
- The research-prod Air ablations pin the backport of this
implementation. IPO-KL, IPO, DPPO, and IcePop have each subsequently
advanced beyond 400 Muon steps without recurrence of the initialization
deadlock.
- Review follow-up (`dfa07cd7e`): the warm-up now resolves the process
group from the mesh and no-ops on non-1-D meshes. Verified on 2 GPUs
with NCCL: the `dp_shard` path still completes the warm-up collectives,
and the 2-D replicate-only world mesh returns cleanly where the previous
no-arg `get_group()` call raised `RuntimeError`.

Both full-model validations used `qpn01gpu009/011`, 16 GPUs, CP4 + EP8,
optimizer-state offload, BF16 compute, and expandable CUDA allocator
segments. They used fake data with no evaluation or checkpoint overhead.

Job 1185 artifacts are retained at:

```text
/home/outputs/int4-debug/sft-air-full-muon-init-warmup-2n-009-011
```

## Confidence and limitations

Confidence is high that this initialization prevents the observed
first-all-to-all deadlock: the failure was reproducible without it, the
matching warm-up removed it in progressively more production-like tests,
and the final implementation has continued to work in four long-running
RL jobs.

The exact NCCL-native deadlock mechanism remains unproven. The warm-up
changes connection state, allocation history, and startup timing, so
this should be described as a targeted correctness workaround rather
than proof of a particular NCCL defect. Removing or moving it requires
reproducing the original multi-node pretrained GLM-Air Muon case, not
merely passing a standalone collective test.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed initialization for Muon only, but incorrect group
selection or removal could reintroduce multi-node deadlocks or add
startup memory/time on every Muon run.
> 
> **Overview**
> Adds a **correctness workaround** for multi-node Muon training: NCCL
peer channels for bulk all-to-all are established **right after** Dion
`Muon` is built and **before** the first optimizer step, so
GLM-Air-style jobs avoid deadlocking on the initial Muon collective.
> 
> New helper `_warmup_muon_process_group` no-ops for single-rank or
non-NCCL groups; otherwise it runs an async **list** `all_to_all` on ~3
MiB BF16 buffers per rank (matching Dion’s bulk path), waits, and
synchronizes CUDA. Warm-up runs on the main **`dp_shard_cp`** (or world)
process group and, when expert MLP params use EP, separately on
**`dp_shard_mod_ep`**. AdamW, SGD, and other optimizers are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d0b707438f77780e4b5e0ed69237c08435ba3a41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-07 11:20:40 -07:00
26b3131d27 fix(transports): make NCCL respect keep_in_fp32_for_weight_transfer (#3480)
The NCCL weight-broadcast transport hardcoded every tensor to
`bfloat16`, ignoring `keep_in_fp32_for_weight_transfer`. This PR makes
NCCL transport respect the fp32 overrides. This makes NCCL honor the
same declaration the other two transports already respect. Note: NIXL
does its own thing and does not use this shared helper, yet.

- Extracted `resolve_wire_dtype()` so the filesystem and NCCL paths
share one implementation.
- Lifted `NCCLBroadcaster._resolve_dtensors` to a module-level
`resolve_dtensors()`, since a method reachable only through a live
`PyNcclCommunicator` can't be unit tested.
- Added `tests/unit/utils/test_weights.py`, the flag's first test
coverage, parametrized over all six models that declare it.

Ran various experiments with small models to see if this affected KL mismatch in any way, but results were inconclusive. See commit https://github.com/PrimeIntellect-ai/prime-rl/pull/3480/changes/4b152bf3fa551ff5a1fc1752036262d14520c343 for example experiment configs.


---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:57:19 -04:00
32 changed files with 3074 additions and 300 deletions
+19
View File
@@ -6,6 +6,7 @@ This page covers the specialized features layered on top of the core training st
- [Custom Modeling](#custom-modeling)
- [Expert Parallelism Backends](#expert-parallelism-backends)
- [Runtime Fusions](#runtime-fusions)
- [Multimodal Training](#multimodal-training)
- [Supported Families](#supported-families)
- [Enabling VLM Mode](#enabling-vlm-mode)
@@ -82,6 +83,24 @@ token_chunk_size = 4096
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
### Runtime Fusions
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"] # [] disables
```
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning, or fails at startup with `raise_on_fail = true`. Fusions are skipped when LoRA is enabled.
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
## Multimodal Training
### Supported Families
@@ -85,6 +85,17 @@ class CompileConfig(BaseConfig):
"""Compile transformer blocks with ``fullgraph=True``."""
class FusionsConfig(BaseConfig):
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
"""Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable."""
raise_on_fail: bool = False
"""Fail at startup when no module supports a requested fusion, instead of logging a warning and continuing without it."""
shard_fused_on_dim1: bool = False
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
@@ -240,6 +251,9 @@ class ModelConfig(BaseModelConfig):
compile: CompileConfig | None = CompileConfig()
"""Compile the model with ``torch.compile``."""
fusions: FusionsConfig = FusionsConfig()
"""Runtime parameter fusions, on by default."""
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
+1 -1
View File
@@ -252,7 +252,7 @@ torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ 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 == 'aarch64'" },
]
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -64,6 +64,7 @@ DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
"aten::convolution",
"aten::linear",
"aten::mm",
"prime_rl::dsv4_sparse_attn",
"prime_rl::fp8_blockwise_mm",
"prime_rl::grouped_fp8_gemm",
"prime_rl::sparse_mla",
+18 -2
View File
@@ -19,6 +19,11 @@ from torchdata.stateful_dataloader import StatefulDataLoader
from prime_rl.configs.shared import ResumeConfig
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.trainer.models.fusions import (
join_loaded_optimizer_state_for_runtime,
split_packed_optimizer_state_for_checkpoint,
write_back_loaded_packed_optimizer_state,
)
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import format_time, get_logger
@@ -79,9 +84,12 @@ class AppState(Stateful):
# Automatically manages FSDP FQN's, as well as sets the default state dict type to FSDP.SHARDED_STATE_DICT
checkpoint_optimizers = self._get_checkpoint_optimizers()
model_state_dict, optimizer_state_dict = get_state_dict(self.model, checkpoint_optimizers)
# Runtime fusions own one physical state tensor per fused parameter; the checkpoint
# sees it under the canonical names. This dict is also the template dcp_load writes
# into, and load_state_dict packs the loaded entries back into the runtime state.
state_dict = {
"model": model_state_dict,
"optimizers": optimizer_state_dict,
"optimizers": split_packed_optimizer_state_for_checkpoint(self.model, optimizer_state_dict),
}
if self.scheduler is not None:
scheduler_state_dict = self.scheduler.state_dict()
@@ -118,15 +126,23 @@ class AppState(Stateful):
# apply the model side here and flip the wrappers to initialized so
# subsequent steps take the steady-state path.
set_model_state_dict(self.model, model_state_dict=state_dict["model"])
# The template only aliases a packed parameter's state where the packing
# dimension is unsharded, so the loaded logical entries are packed back in.
write_back_loaded_packed_optimizer_state(self.model, checkpoint_optimizers, state_dict["optimizers"])
for optimizer in self.optimizers:
if isinstance(optimizer, OffloadOptimizer):
optimizer.finish_checkpoint_load()
else:
# The runtime state dict read back here keys the fused parameters' state by their
# physical names; the loaded logical entries are packed into it.
_, runtime_optimizer_state_dict = get_state_dict(self.model, checkpoint_optimizers)
set_state_dict(
self.model,
checkpoint_optimizers,
model_state_dict=state_dict["model"],
optim_state_dict=state_dict["optimizers"],
optim_state_dict=join_loaded_optimizer_state_for_runtime(
self.model, state_dict["optimizers"], runtime_optimizer_state_dict
),
)
if self.scheduler is not None:
+17
View File
@@ -42,6 +42,11 @@ from prime_rl.trainer.models import (
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.fusions import (
apply_model_fusions,
get_fsdp_shard_placement_fn,
write_back_loaded_packed_parameters,
)
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
@@ -774,10 +779,12 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
fsdp_config = {
"mp_policy": mp_policy,
"offload_policy": offload_policy,
"reshard_after_forward": config.reshard_after_forward,
"shard_placement_fn": shard_placement_fn,
}
hsdp_mesh = parallel_dims.get_mesh("hsdp")
@@ -819,6 +826,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy=MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32),
offload_policy=offload_policy,
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
fully_shard(
@@ -844,6 +852,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy=mp_policy,
offload_policy=offload_policy,
reshard_after_forward=False,
shard_placement_fn=shard_placement_fn,
)
else:
get_logger().warning("Model uses tied word embeddings, so skipping the last-layer no-reshard optimization.")
@@ -854,6 +863,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy=mp_policy,
offload_policy=offload_policy,
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
if not parallel_dims.ep_enabled:
@@ -1006,6 +1016,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
state_dict,
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
)
write_back_loaded_packed_parameters(model, state_dict)
# Restore weight tying broken by to_empty() for HF models
if not isinstance(model, PreTrainedModelPrimeRL) and model.config.tie_word_embeddings:
model.tie_weights()
@@ -1257,6 +1268,12 @@ def setup_model(
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
if config.fusions.enabled and config.lora is not None:
logger.warning("Skipping runtime model fusions because LoRA targets the unfused projections")
elif config.fusions.enabled:
applied = apply_model_fusions(model, config.fusions.enabled, raise_on_fail=config.fusions.raise_on_fail)
logger.info(f"Applied runtime model fusions: {applied}")
lm_head_chunk_size: int | None = None
if isinstance(config.fused_lm_head_token_chunk_size, int):
lm_head_chunk_size = config.fused_lm_head_token_chunk_size
@@ -23,7 +23,7 @@ Design constraints:
``expert_offset`` so a rank can unstack just its *local* experts into
globally-numbered per-expert keys — no all-gather. Any op that genuinely
needs a full tensor is the caller's responsibility to gather first (via the
trainer's ``_resolve_dtensors``); none of the ops here gather on their own.
trainer's ``resolve_dtensors``); none of the ops here gather on their own.
* **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.
@@ -32,7 +32,7 @@ of the compressed variants is below, tensors flowing downwards:
│ │
└────────── concatenate ──────┘
│
QKᵀ (with {compression,position}-aware masking)
gather each query's slots, then QKᵀ
│
softmax + sink
│
@@ -49,10 +49,11 @@ useful due to the complexities introduced by the compressed attention variants.
necessary attention data is organized into a `PackedContext` object (directly consumed by attention
layers), built from one `seq_lens` and carrying:
- `attention_mask`: causal, local-window, clipped at document boundaries.
- `position_ids`: each token's position within its own document.
- `tok_doc_idx`: which document each token belongs to.
- `position_embeddings`: the RoPE tables, one per rope type, evaluated at `position_ids`.
- `window_indices`: for each query, the indices of the tokens its local window covers, causal
and clipped at document boundaries, with `IGNORE_SLOT` (-1) marking invalid/masked entries.
- `compression_layouts`: one `CompressionLayout` per compress rate in the architecture.
The last of those characterizes the token-compression mechanism of DeepSeek V4. We start with it
@@ -95,14 +96,27 @@ holds it once and shares it across rates.
Compression is only part of the story: every attention layer also reads a local sliding window of
the most recent tokens directly, and the compressed entries are how it reaches anything older.
That window needs a causal sliding-window mask applied per document, `attention_mask`, and every
rotation in the block needs `position_ids` together with the RoPE tables evaluated at them,
`position_embeddings`. None of those belongs to any single compress rate.
That window is enumerated per document by `window_indices`, and every rotation in the block needs
`position_ids` together with the RoPE tables evaluated at them, `position_embeddings`. None of
those belongs to any single compress rate.
`PackedContext.build` takes `seq_lens` and derives every one of its fields from it. Nothing else is
an input, so a position that disagrees with a document boundary, a mask that spans one, or a RoPE
table evaluated at positions other than the ones the causal thresholds count in, cannot be
constructed. It runs once per model forward, since none of this depends on depth.
an input, so a position that disagrees with a document boundary, a window slot that spans one, or a
RoPE table evaluated at positions other than the ones the causal thresholds count in, cannot be
constructed. It runs once per model forward.
[The Index Contract]
All three layer types reach their keys the same way. `SparseAttnInputs` lays out one KV buffer,
kv_buf[b, n, 0, d]: the packed token stream, then this layer's compressed entries, and
nothing else: an absent key needs no position of its own
and one int32 index tensor addressing that position axis, `sliding_window + picks` slots per
query: the local window first, the picks after. `picks` is the indexer's
`min(index_topk, entries)` for CSA, `max_entries_per_doc` for HCA, and zero for a sliding layer,
which reads its window alone. A slot with nothing to read holds `IGNORE_SLOT` (-1), which the
kernel masks on, so a short window and a surplus pick cost only their loads.
"""
from dataclasses import dataclass
@@ -112,11 +126,29 @@ import torch.nn.functional as F
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.layers.norms import RMSNorm, RMSNormConfig
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.
try:
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn import dsv4_sparse_attn, sparse_attn_shape_error
except ImportError:
dsv4_sparse_attn = None # type: ignore
sparse_attn_shape_error = None # type: ignore
def _kernel_blocker(num_heads: int, head_dim: int) -> str | None:
"""Why the fused kernel cannot run at this shape, or ``None`` if it can."""
if dsv4_sparse_attn is None:
return "the tilelang sparse-attention kernel failed to import; install the `gpu` extra"
# CSA gives every query head the same single KV head, so the kernel's `kv_group` is 1. The
# shape constraints themselves are stated once, next to the kernels they come from.
return sparse_attn_shape_error(num_heads, 1, head_dim)
class DeepseekV4GroupedLinear(nn.Linear):
"""Block-diagonal grouped linear, the first half of the output projection.
@@ -142,53 +174,6 @@ class DeepseekV4GroupedLinear(nn.Linear):
return y.reshape(*input_shape, self.n_groups, -1)
def eager_attention_with_sinks(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
sinks: torch.Tensor,
attention_mask: torch.Tensor,
scaling: float,
dropout: float = 0.0,
training: bool = False,
) -> torch.Tensor:
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
attn_weights = attn_weights + attention_mask
sink_logits = sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
combined_logits = torch.cat([attn_weights, sink_logits], dim=-1)
# Row-max subtraction is not free here: without it the exponentials overflow in bf16.
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
scores = F.dropout(probs[..., :-1], p=dropout, training=training).to(value.dtype)
attn_output = torch.matmul(scores, value)
return attn_output.transpose(1, 2).contiguous()
def build_sliding_window_mask(*, tok_doc_idx: Tensor, sliding_window: int, dtype: torch.dtype) -> Tensor:
"""Additive `(1, 1, seq_len, seq_len)` mask over query rows and key columns.
A key is readable when it lies in the query's own document and within the `sliding_window`
tokens up to and including the query.
A padded micro-batch folds its padding into the last document, so the padding is masked as a
continuation of the last document. Causality already keeps it away from every real token, and it
is loss-masked.
"""
seq_len = tok_doc_idx.shape[0]
device = tok_doc_idx.device
tok_idx = torch.arange(seq_len, device=device)
distance = tok_idx[:, None] - tok_idx[None, :]
in_causal_window = (distance >= 0) & (distance < sliding_window)
same_document = tok_doc_idx[:, None] == tok_doc_idx[None, :]
readable = in_causal_window & same_document
mask = torch.zeros(seq_len, seq_len, dtype=dtype, device=device)
return mask.masked_fill_(~readable, torch.finfo(dtype).min)[None, None]
@dataclass(frozen=True)
class CompressionLayout:
"""Per-document compressed-entry layout for one compress rate.
@@ -202,6 +187,8 @@ class CompressionLayout:
entry_tok_idx: Tensor # (n_entries, compress_rate) int64 - token index in the packed sequence, per entry
entry_doc_idx: Tensor # (n_entries,) int64 - which document each entry belongs to
entry_local_idx: Tensor # (n_entries,) int64 - entry index within its own document
first_entry_of_doc: Tensor # (n_docs,) int64 - sequence-global index of each document's first entry
max_entries_per_doc: int # largest entry count any single document contributes
@classmethod
def build(cls, *, cu_seqlens: Tensor, compress_rate: int) -> "CompressionLayout":
@@ -232,6 +219,8 @@ class CompressionLayout:
entry_tok_idx=entry_tok_idx,
entry_doc_idx=entry_doc_idx,
entry_local_idx=entry_local_idx,
first_entry_of_doc=first_entry_of_doc,
max_entries_per_doc=int(counts.max()),
)
@@ -239,29 +228,31 @@ class CompressionLayout:
class PackedContext:
"""Everything an attention layer needs to know about the packed row it is running on.
The mask, the positions, the RoPE tables and the layouts all encode the same document
boundaries and are only correct together. As separate arguments they can contradict each
other: a mask built without document boundaries spans documents while a layout does not, a
sequence-global `position_ids` feeds `causal_threshold` a count that a 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, since
none of this depends on depth.
The window indices, the positions, the RoPE tables and the layouts all encode the same
document boundaries and are only correct together. As separate arguments they can contradict
each other: a window enumerated without document boundaries spans documents while a layout
does not, a sequence-global `position_ids` feeds `causal_threshold` a count that a
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.
"""
attention_mask: Tensor # (1, 1, seq_len, seq_len) additive - causal, local window, document-clipped
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
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.attention_mask.shape[-2] != total_tokens or self.position_ids.shape[-1] != total_tokens:
if self.position_ids.shape[-1] != total_tokens:
raise ValueError(
f"attention_mask covers {self.attention_mask.shape[-2]} query rows and position_ids "
f"{self.position_ids.shape[-1]} tokens, but the row has {total_tokens}"
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
@@ -278,7 +269,7 @@ class PackedContext:
`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 the mask is additive. The row is as wide as `seq_lens` says,
attention runs at, since it types the RoPE tables. The row is as wide as `seq_lens` says,
padding included: both packers fold their padding into the last document.
"""
config = rotary_emb.config
@@ -295,10 +286,14 @@ class PackedContext:
for layer_type in set(config.layer_types)
if layer_type in config.compress_rates
}
# 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)
slots = window_base[:, None] + torch.arange(config.sliding_window, device=device)[None, :]
window_indices = torch.where(slots <= tok_idx[:, None], slots, IGNORE_SLOT).to(torch.int32)
return cls(
attention_mask=build_sliding_window_mask(
tok_doc_idx=tok_doc_idx, sliding_window=config.sliding_window, dtype=dtype
),
position_ids=position_ids,
tok_doc_idx=tok_doc_idx,
position_embeddings={
@@ -307,6 +302,7 @@ class PackedContext:
compression_layouts={
rate: CompressionLayout.build(cu_seqlens=cu_seqlens, compress_rate=rate) for rate in compress_rates
},
window_indices=window_indices,
)
def check_position_ids(self, position_ids: Tensor) -> None:
@@ -350,6 +346,69 @@ class PackedContext:
return same_document & (threshold.unsqueeze(-1) > layout.entry_local_idx[None, None, :])
@dataclass(frozen=True)
class SparseAttnInputs:
"""The KV buffer one attention layer gathers from, and the gather indices addressing it.
`build` constructs the two together so they stay mutually consistent and cannot drift apart.
With `S` tokens in the packed row and `E` compressed entries for this layer's rate, `E` being
zero for a layer that reads no entries at all:
kv_buf[b, n, 0, d]: n in [0, S) -> local token stream
n in [S, S + E) -> compressed entry (n - S)
Every index must be a real key in `[0, n_positions)` or `IGNORE_SLOT` (-1), which marks an absent
key, which `build` enforces.
"""
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]}")
@classmethod
def build(
cls,
*,
kv: Tensor, # (batch, 1, seq_len, head_dim), the rotated local 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
) -> "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
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)
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`.
# 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)
indices = torch.cat([window, picks[:, :, None, :].to(torch.int32)], dim=-1)
return cls(kv_buf=kv_buf, indices=indices)
class DeepseekV4Compressor(nn.Module):
"""Softmax-gated pooling of the token stream into one entry per `compress_rate` tokens, per the
`CompressionLayout` specification. Schematic output:
@@ -360,8 +419,8 @@ class DeepseekV4Compressor(nn.Module):
source tokens of entry `e`'s pooling window, and `d` runs over `head_dim`. Each entry is
RMSNormed and rotated with the `compress` RoPE at its window's first source position, which
is what makes it comparable with the attention block's locally rotated KV stream. `forward`
returns the entries alongside an additive `block_bias` saying which query may read which, for
`DeepseekV4Attention` to concatenate onto its local sliding window.
returns the entries alongside this layer's entry selection: the per-query entry indices the
attention block gathers, with `IGNORE_SLOT` (-1) marking a slot the query has nothing to read into.
`n_series` sets the slots `s` the gate ranges over. With `1` a token joins only its own
window, so windows are disjoint. With `2` the projections emit two `head_dim`-wide series
@@ -476,7 +535,7 @@ class DeepseekV4Indexer(nn.Module):
distance.
Each query gets `min(index_topk, entries)` picks. An early query has fewer entries whose
source tokens all lie at or before it, and its surplus picks come back as `-1`.
source tokens all lie at or before it, and its surplus picks come back as `IGNORE_SLOT` (-1).
"""
def __init__(self, config: DeepseekV4Config):
@@ -511,8 +570,10 @@ class DeepseekV4Indexer(nn.Module):
scores = scores.masked_fill(~readable, float("-inf"))
top_k_indices = scores.topk(top_k, dim=-1).indices
# An early query has fewer than `top_k` readable entries, so top-k still hands back
# masked-out ones. Mark those `-1` rather than letting them leak into attention.
return torch.where(readable.gather(-1, top_k_indices), top_k_indices, torch.full_like(top_k_indices, -1))
# masked-out ones. Mark those `IGNORE_SLOT` (-1) rather than letting them leak into attention.
return torch.where(
readable.gather(-1, top_k_indices), top_k_indices, torch.full_like(top_k_indices, IGNORE_SLOT)
)
def init_weights(self, init_std: float) -> None:
self.compressor.init_weights(init_std)
@@ -522,10 +583,9 @@ class DeepseekV4CSACompressor(DeepseekV4Compressor):
"""Compressed Sparse Attention compressor: the sparse long-range half of a CSA layer.
Two series at a fine compress rate, with overlapping windows. A Lightning Indexer scores
the entries and keeps the `index_topk` best per query, and the returned `block_bias` is
that selection: `0` on the selected entries, `-inf` everywhere else. It needs no separate
causal term, because the indexer only selects entries whose source tokens all lie at or
before the query.
the entries and keeps the `index_topk` best per query, and the returned `top_k_indices` is
that selection, with `IGNORE_SLOT` (-1) marking a surplus pick. It needs no separate causal term,
because the indexer only selects entries whose source tokens all lie at or before the query.
"""
def __init__(self, config: DeepseekV4Config):
@@ -535,18 +595,10 @@ class DeepseekV4CSACompressor(DeepseekV4Compressor):
def forward(
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
) -> tuple[torch.Tensor, torch.Tensor]:
batch, seq_len, _ = hidden_states.shape
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
compressed_len = compressed_kv.shape[2]
# 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.
top_k_indices = self.indexer(hidden_states, q_residual, packed)
# The `-1` sentinels are scattered into one throwaway column that is sliced back off.
safe_indices = torch.where(top_k_indices >= 0, top_k_indices, torch.full_like(top_k_indices, compressed_len))
block_bias = compressed_kv.new_full((batch, 1, seq_len, compressed_len + 1), float("-inf"))
block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
return compressed_kv, block_bias[..., :compressed_len]
return compressed_kv, self.indexer(hidden_states, q_residual, packed)
def init_weights(self, init_std: float) -> None:
super().init_weights(init_std)
@@ -557,8 +609,11 @@ class DeepseekV4HCACompressor(DeepseekV4Compressor):
"""Heavily Compressed Attention compressor: the dense long-range half of an HCA layer.
One series at a coarse compress rate, with disjoint windows. There is no indexer: a query
reads every entry whose source tokens all lie at or before it, and the returned
`block_bias` carries that rule.
reads every entry whose source tokens all lie at or before it. A document's entries are
numbered consecutively, so that set is the contiguous range starting at the document's first
entry, and the picks the layer gathers are arithmetic rather than learned. Every document is
afforded `max_entries_per_doc` picks; a query that has completed fewer entries than that pads
the rest with `IGNORE_SLOT` (-1), as the indexer's surplus picks do.
"""
def __init__(self, config: DeepseekV4Config):
@@ -568,14 +623,17 @@ class DeepseekV4HCACompressor(DeepseekV4Compressor):
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
) -> tuple[torch.Tensor, torch.Tensor]:
"""`q_residual` is part of the compressor contract but unused: HCA has no indexer."""
batch, seq_len, _ = hidden_states.shape
batch = hidden_states.shape[0]
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
compressed_len = compressed_kv.shape[2]
threshold = self.causal_threshold(packed.position_ids)
readable = packed.token_entry_causal_mask(self.compress_rate, threshold).unsqueeze(1)
block_bias = compressed_kv.new_zeros((batch, 1, seq_len, compressed_len))
return compressed_kv, block_bias.masked_fill_(~readable, float("-inf"))
layout = packed.compression_layouts[self.compress_rate]
# `threshold` counts entries within the query's own document, so it selects how far into
# that document's range to read, and the document's own base turns that into an entry index.
threshold = self.causal_threshold(packed.position_ids).unsqueeze(-1) # (1, seq_len, 1)
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)
COMPRESSOR_CLASSES = {
@@ -631,9 +689,57 @@ 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
if blocker is not None:
raise ValueError(f"DeepSeek V4 cannot run the fused sparse-attention kernel: {blocker}")
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,
)
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.
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
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:
@@ -660,29 +766,8 @@ class DeepseekV4Attention(nn.Module):
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)
attention_mask = packed.attention_mask # (1, 1, t, t)
if self.compressor is not None:
# (b, 1, e, d), (b, 1, t, e)
compressed_kv, block_bias = self.compressor(hidden_states, q_residual, packed)
kv = torch.cat([kv, compressed_kv], dim=2) # (b, 1, t + e, d)
# The compressed entries live outside the local window, so the sliding mask says
# nothing about them; `block_bias` carries their per-query causality and the
# indexer's selection. Zero-padding instead would let every query read every one.
attention_mask = torch.cat(
[attention_mask.expand(*block_bias.shape[:-1], -1), block_bias.to(attention_mask.dtype)], dim=-1
) # (b, 1, t, t + e)
attn_output = eager_attention_with_sinks(
q,
kv,
kv,
self.sinks,
attention_mask,
scaling=self.scaling,
dropout=self.attention_dropout,
training=self.training,
) # (b, t, h, 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)
# 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.
@@ -709,6 +794,7 @@ __all__ = [
"DeepseekV4Indexer",
"DeepseekV4IndexerScorer",
"PackedContext",
"build_sliding_window_mask",
"SparseAttnInputs",
"dense_mask_from_indices",
"eager_attention_with_sinks",
]
@@ -1,4 +1,4 @@
from typing import Any
from typing import Any, Literal
from huggingface_hub.dataclasses import strict
from transformers.configuration_utils import PretrainedConfig
@@ -125,6 +125,7 @@ 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,
@@ -181,6 +182,9 @@ 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
@@ -320,15 +324,18 @@ class DeepseekV4Config(PretrainedConfig):
self.rope_parameters = rope_parameters_dict
def to_dict(self) -> dict[str, Any]:
"""Drop the derived `mlp_layer_types` duck-typing shim before serializing.
"""Drop the in-memory-only fields 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.
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.
"""
output = super().to_dict()
output.pop("mlp_layer_types", None)
output.pop("_attn_impl", None)
return output
def validate_layer_type(self) -> None:
@@ -20,7 +20,7 @@ from torch import Tensor
from prime_rl.trainer.models.conversion_ops import StateDict
_FP4_E2M1_LUT = torch.tensor(
FP4_E2M1_LUT = torch.tensor(
[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
dtype=torch.float32,
)
@@ -28,7 +28,7 @@ _FP4_E2M1_LUT = torch.tensor(
def _unpack_mxfp4(packed: Tensor) -> Tensor:
"""Two packed e2m1 nibbles per `int8` byte -> `float32`, doubling the last dim."""
lut = _FP4_E2M1_LUT.to(packed.device)
lut = FP4_E2M1_LUT.to(packed.device)
u8 = packed.contiguous().view(torch.uint8)
low_nibble = (u8 & 0xF).long()
high_nibble = ((u8 >> 4) & 0xF).long()
@@ -0,0 +1,93 @@
"""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.
"""
import torch
import torch.nn.functional as F
from torch import Tensor
def eager_attention_with_sinks(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
sinks: torch.Tensor,
attention_mask: torch.Tensor,
scaling: float,
dropout: float = 0.0,
training: bool = False,
) -> torch.Tensor:
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
attn_weights = attn_weights + attention_mask
sink_logits = sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
combined_logits = torch.cat([attn_weights, sink_logits], dim=-1)
# Row-max subtraction is not free here: without it the exponentials overflow in bf16.
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
scores = F.dropout(probs[..., :-1], p=dropout, training=training).to(value.dtype)
attn_output = torch.matmul(scores, value)
return attn_output.transpose(1, 2).contiguous()
def build_sliding_window_mask(*, tok_doc_idx: Tensor, sliding_window: int, dtype: torch.dtype) -> Tensor:
"""Additive `(1, 1, seq_len, seq_len)` mask over query rows and key columns.
A key is readable when it lies in the query's own document and within the `sliding_window`
tokens up to and including the query.
A padded micro-batch folds its padding into the last document, so the padding is masked as a
continuation of the last document. Causality already keeps it away from every real token, and it
is loss-masked.
"""
seq_len = tok_doc_idx.shape[0]
device = tok_doc_idx.device
tok_idx = torch.arange(seq_len, device=device)
distance = tok_idx[:, None] - tok_idx[None, :]
in_causal_window = (distance >= 0) & (distance < sliding_window)
same_document = tok_doc_idx[:, None] == tok_doc_idx[None, :]
readable = in_causal_window & same_document
mask = torch.zeros(seq_len, seq_len, dtype=dtype, device=device)
return mask.masked_fill_(~readable, torch.finfo(dtype).min)[None, None]
def block_bias_from_indices(top_k_indices: Tensor, n_entries: int, dtype: torch.dtype) -> Tensor:
"""Render the indexer's picks as the dense additive `(batch, 1, seq_len, n_entries)` bias.
`0` on the selected entries, `-inf` everywhere else. The dense and sparse attention paths
both start from the same index tensor, so they cannot disagree about which entries a query
reads.
"""
batch, seq_len, _ = top_k_indices.shape
# The `IGNORE_SLOT` (-1) sentinels are scattered into one throwaway column that is sliced back off.
safe_indices = torch.where(top_k_indices >= 0, top_k_indices, torch.full_like(top_k_indices, n_entries))
block_bias = torch.full((batch, 1, seq_len, n_entries + 1), float("-inf"), dtype=dtype, device=top_k_indices.device)
block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
return block_bias[..., :n_entries]
def dense_mask_from_indices(indices: Tensor, n_positions: int, dtype: torch.dtype) -> Tensor:
"""Render a gather-index tensor as the dense additive `(batch, 1, seq_len, n_positions)` mask.
`indices` is the `(batch, seq_len, 1, n_slots)` int32 tensor addressing the position axis of a
`kv_buf` with `n_positions` positions. The mask is `0` on every position at least one of a
query's slots names and `-inf` everywhere else. A slot holding `IGNORE_SLOT` (-1) marks an absent
key and names no position, so it admits nothing.
This is the fused kernel's oracle. Rendering the index tensor dense and running naive eager
attention over the whole `kv_buf` exercises the index contract and the attention math together.
"""
batch, seq_len, _, _ = indices.shape
slots = indices[:, :, 0, :].to(torch.int64).unsqueeze(1)
# `scatter_` has no negative indexing, so `IGNORE_SLOT` (-1) goes into one throwaway column that
# is sliced back off. Clamping it to a real position instead would admit a key the query cannot read.
safe = torch.where(slots >= 0, slots, n_positions)
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()
@@ -78,7 +78,7 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
# Mirrors HF's `_keep_in_fp32_modules_strict`, with `e_score_correction_bias` renamed to
# the `selection_bias` prime-rl's router keeps it under. The bare `norm` entry subsumes the
# named norms; both are kept so the list stays a one-to-one image of HF's.
_KEEP_IN_FP32_MODULES = (
KEEP_IN_FP32_MODULES = (
"attn_hc",
"ffn_hc",
"hc_head",
@@ -100,11 +100,7 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
supports_gradient_checkpointing = True
_no_split_modules = ["DeepseekV4DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
# V4 attention is eager-only, as in HF: FlashAttention caps the head dim at 256 while
# V4 uses 512, SDPA carries no per-head sink logit, and FlexAttention's BlockMask
# cannot grow to cover the compressed entries the block concatenates onto the KV axis.
# `DeepseekV4Attention` reads no dispatch table, so `config._attn_implementation` is
# inert here; these flags only keep transformers from advertising a backend we lack.
# V4 attention runs its own fused kernel; no transformers backend can serve it.
_supports_flash_attn = False
_supports_sdpa = False
_supports_flex_attn = False
@@ -117,7 +113,7 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
def cp_support(cls, config) -> CPSupport:
return CPSupport(
frozenset(),
"its sliding window is a dense local mask built from post-shard document boundaries, "
"its sliding window is built from post-shard document boundaries, "
"which CP's global (pre-shard) boundaries cannot address",
)
@@ -133,7 +129,7 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return any(module_name in name for module_name in _KEEP_IN_FP32_MODULES)
return any(module_name in name for module_name in KEEP_IN_FP32_MODULES)
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
@@ -233,15 +229,15 @@ 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. Rejected: the
window mask is dense and local, so global boundaries cannot address it.
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 seq_lens_are_pre_shard:
raise NotImplementedError(
"DeepSeek V4 does not support context parallelism: pre-shard document boundaries "
"do not address the local sliding-window mask."
"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."
)
if inputs_embeds is None:
@@ -9,7 +9,7 @@ from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import Deepse
# The rope types whose inverse frequencies are fixed once computed. The two left out,
# `dynamic` and `longrope`, rescale theirs per forward against the running sequence length,
# which the buffers below, written once in `__init__`, never do.
_SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
@@ -63,7 +63,7 @@ class DeepseekV4RotaryEmbedding(nn.Module):
`rope_type` is checkpoint data rather than architecture: V4 ships `default` on `main` and
`default` or `yarn` on `compress`, but the config reads whatever the file says. Anything
outside `_SUPPORTED_ROPE_TYPES` is refused at construction, rather than rotating at
outside `SUPPORTED_ROPE_TYPES` is refused at construction, rather than rotating at
frequencies that were meant to be rescaled and never were.
"""
@@ -78,10 +78,10 @@ class DeepseekV4RotaryEmbedding(nn.Module):
self.rope_type: dict[str, str] = {}
for layer_type in self.layer_types:
self.rope_type[layer_type] = config.rope_parameters[layer_type]["rope_type"]
if self.rope_type[layer_type] not in _SUPPORTED_ROPE_TYPES:
if self.rope_type[layer_type] not in SUPPORTED_ROPE_TYPES:
raise ValueError(
f"rope type {self.rope_type[layer_type]!r} on {layer_type!r} is not supported; "
f"the supported types are {sorted(_SUPPORTED_ROPE_TYPES)}, whose inverse "
f"the supported types are {sorted(SUPPORTED_ROPE_TYPES)}, whose inverse "
"frequencies are computed once here and never rescaled per forward"
)
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(config, device, layer_type=layer_type)
+312
View File
@@ -0,0 +1,312 @@
from collections.abc import Callable, Iterator, Sequence
from typing import Any, NamedTuple
import torch
from torch import nn
from torch.distributed.tensor import Shard
from prime_rl.utils.logger import get_logger
from prime_rl.utils.weights import resolve_fqn
# Replaces some of a module's parameters with a packed one. Advertised by modules
# through their ``supported_fusions``.
RuntimeFusion = Callable[[nn.Module], None]
class PackedParameterSpec:
"""One physical parameter packing several logical parameters along a dimension.
Training allocates, computes on, and optimizes the packed parameter. The logical
parameters keep their canonical names in checkpoints. They alias the packed storage
unless the parameter is a DTensor sharded along the packing dimension, where a split
has to redistribute and yields copies instead.
``name`` and ``logical_names`` are relative to the module the packing is registered
on, and may name parameters of its children. ``dim`` is a non-negative dimension
index into the packed parameter.
"""
def __init__(self, name: str, logical_names: Sequence[str], sizes: Sequence[int], dim: int):
self.name = name
self.logical_names = tuple(logical_names)
self.sizes = tuple(sizes)
self.dim = dim
def split_into_logical_views(self, tensor: torch.Tensor) -> tuple[torch.Tensor, ...]:
"""The logical parameters, in ``logical_names`` order, as views of ``tensor``."""
return tensor.split(self.sizes, dim=self.dim)
def pack_logical_tensors(self, tensors: Sequence[torch.Tensor]) -> torch.Tensor:
return torch.cat(list(tensors), dim=self.dim)
def muon_matrix_partitions(self, parameter: torch.Tensor) -> tuple[int, ...] | None:
"""Muon's partition sizes, or None when the packing is not on the output dimension."""
return self.sizes if self.dim == parameter.ndim - 2 else None
def register_packed_parameter_state_dict_hooks(module: nn.Module, spec: PackedParameterSpec) -> None:
"""Record a packed parameter and keep the module's state dict in canonical form.
The hooks below trade the packed entry for its canonical ones on the way out and
back again on the way in, so checkpoints never see the packed layout. Torch stamps
an attribute onto every hook it registers, so these have to be plain functions.
"""
def split_packed_entry_into_logical_entries(module, state_dict, prefix, local_metadata) -> None:
views = spec.split_into_logical_views(state_dict.pop(f"{prefix}{spec.name}"))
for logical_name, view in zip(spec.logical_names, views):
state_dict[f"{prefix}{logical_name}"] = view
def join_logical_entries_into_packed_entry(module, state_dict, prefix, *load_state_dict_args) -> None:
state_dict[f"{prefix}{spec.name}"] = spec.pack_logical_tensors(
[state_dict.pop(f"{prefix}{logical_name}") for logical_name in spec.logical_names]
)
module.packed_parameter_specs = (*getattr(module, "packed_parameter_specs", ()), spec)
module.register_state_dict_post_hook(split_packed_entry_into_logical_entries)
module.register_load_state_dict_pre_hook(join_logical_entries_into_packed_entry)
def fuse_gate_up_projections(module: nn.Module) -> None:
"""Pack a gated expert's gate and up projections into one grouped-GEMM weight.
The packed weight is ``[num_experts, 2 * hidden_dim, dim]``, so the forward path is a
single grouped GEMM whose transpose and chunk are views.
"""
spec = PackedParameterSpec("gate_up_proj", ("gate_proj", "up_proj"), (module.hidden_dim, module.hidden_dim), dim=1)
module.gate_up_proj = nn.Parameter(
spec.pack_logical_tensors([module.gate_proj, module.up_proj]),
requires_grad=module.gate_proj.requires_grad,
)
module.gate_proj = None
module.up_proj = None
register_packed_parameter_state_dict_hooks(module, spec)
def fuse_qkv_projections(module: nn.Module) -> None:
"""Pack an attention module's query, key and value projections into one linear layer.
The packed weight is ``[q_size + k_size + v_size, hidden_size]``, so the projections
become a single GEMM whose output is split along the last dimension.
"""
projections = {"q_proj": module.q_proj, "k_proj": module.k_proj, "v_proj": module.v_proj}
sizes = tuple(projection.out_features for projection in projections.values())
has_bias = module.q_proj.bias is not None
# Built on meta so the packed parameters assigned below are the only allocation
qkv_proj = nn.Linear(module.q_proj.in_features, sum(sizes), bias=has_bias, device="meta")
for parameter_name in ("weight", "bias") if has_bias else ("weight",):
spec = PackedParameterSpec(
f"qkv_proj.{parameter_name}",
[f"{name}.{parameter_name}" for name in projections],
sizes,
dim=0,
)
tensors = [getattr(projection, parameter_name) for projection in projections.values()]
setattr(
qkv_proj,
parameter_name,
nn.Parameter(spec.pack_logical_tensors(tensors), requires_grad=tensors[0].requires_grad),
)
register_packed_parameter_state_dict_hooks(module, spec)
module.qkv_proj = qkv_proj
# The projections stay in place, emptied. DCP resolves every checkpoint key by
# attribute traversal, so the canonical q/k/v names still need a module to land on.
for projection in projections.values():
projection.weight = None
projection.bias = None
def apply_model_fusions(
model: nn.Module, requested_fusions: Sequence[str], raise_on_fail: bool = True
) -> dict[str, int]:
"""Apply each requested fusion to every module that supports it; returns the module count per fusion."""
fused_module_counts: dict[str, int] = {}
for fusion_name in requested_fusions:
num_fused_modules = 0
for module in model.modules():
fusion: RuntimeFusion | None = getattr(module, "supported_fusions", {}).get(fusion_name)
if fusion is None:
continue
fusion(module)
num_fused_modules += 1
if num_fused_modules == 0:
message = f"The model does not support the {fusion_name!r} runtime fusion"
if raise_on_fail:
raise ValueError(message)
get_logger().warning(f"{message}; continuing without it")
continue
fused_module_counts[fusion_name] = num_fused_modules
return fused_module_counts
def join_module_path(module_path: str, name: str) -> str:
"""Join a module path and a name, tolerating the empty path of the root module."""
return f"{module_path}.{name}" if module_path else name
class PackedParameterInfo(NamedTuple):
fqn: str
"""Fully qualified name of the packed parameter."""
logical_fqns: tuple[str, ...]
"""Fully qualified canonical names of the parameters it packs, in packing order."""
parameter: nn.Parameter
spec: PackedParameterSpec
def get_model_packed_parameters(model: nn.Module) -> Iterator[PackedParameterInfo]:
"""Yield every packed parameter in the model with the canonical names it stands in for."""
for module_path, module in model.named_modules():
for spec in getattr(module, "packed_parameter_specs", ()):
fqn = resolve_fqn(model, join_module_path(module_path, spec.name))
prefix = fqn.removesuffix(spec.name)
yield PackedParameterInfo(
fqn=fqn,
logical_fqns=tuple(f"{prefix}{logical_name}" for logical_name in spec.logical_names),
parameter=module.get_parameter(spec.name),
spec=spec,
)
def get_fsdp_shard_placement_fn(model: nn.Module) -> Callable[[nn.Parameter], Shard | None]:
"""FSDP placement that keeps every packed parameter's packing dimension unsharded.
Splitting a DTensor along an unsharded dimension is a local view, so the canonical
state-dict entries alias the packed storage instead of being replicated copies. FSDP's
default ``Shard(0)`` is kept for everything else, including parameters packed along
dim 0 that have no other dimension to shard.
"""
packing_dim_by_param_id = {
id(packed_info.parameter): packed_info.spec.dim for packed_info in get_model_packed_parameters(model)
}
def shard_placement_fn(parameter: nn.Parameter) -> Shard | None:
if packing_dim_by_param_id.get(id(parameter)) == 0 and parameter.ndim > 1:
return Shard(1)
return None
return shard_placement_fn
def write_back_loaded_packed_parameters(model: nn.Module, state_dict: dict[str, torch.Tensor]) -> None:
"""Write the logical entries of a state dict loaded in place back into the packed parameters.
Loading into ``model.state_dict()`` in place only reaches a packed parameter through
entries that alias it, so the entries that are copies are packed and written back here.
"""
with torch.no_grad():
for packed_info in get_model_packed_parameters(model):
packed_info.parameter.copy_(
packed_info.spec.pack_logical_tensors([state_dict[fqn] for fqn in packed_info.logical_fqns])
)
def split_packed_optimizer_state_for_checkpoint(model: nn.Module, state_dict: dict[str, Any]) -> dict[str, Any]:
"""Expose packed optimizer tensors under their logical names for DCP."""
# DCP returns {} when no optimizers are supplied, including model-only loads.
if not state_dict:
return state_dict
packed_infos = list(get_model_packed_parameters(model))
if not packed_infos:
return state_dict
checkpoint_state_dict = dict(state_dict)
checkpoint_state_dict["state"] = dict(state_dict["state"])
checkpoint_state_dict["param_groups"] = [
{**group, "params": list(group["params"])} for group in state_dict["param_groups"]
]
for packed_info in packed_infos:
if packed_info.fqn in checkpoint_state_dict["state"]:
packed_param_state = checkpoint_state_dict["state"].pop(packed_info.fqn)
logical_param_states: dict[str, dict[str, Any]] = {fqn: {} for fqn in packed_info.logical_fqns}
for state_key, value in packed_param_state.items():
if isinstance(value, torch.Tensor) and value.shape == packed_info.parameter.shape:
for fqn, logical_view in zip(
packed_info.logical_fqns, packed_info.spec.split_into_logical_views(value)
):
logical_param_states[fqn][state_key] = logical_view
else:
for logical_param_state in logical_param_states.values():
logical_param_state[state_key] = value
checkpoint_state_dict["state"].update(logical_param_states)
for group in checkpoint_state_dict["param_groups"]:
param_fqns = []
for param_fqn in group["params"]:
param_fqns.extend(packed_info.logical_fqns if param_fqn == packed_info.fqn else [param_fqn])
group["params"] = param_fqns
return checkpoint_state_dict
def write_back_loaded_packed_optimizer_state(
model: nn.Module, optimizers: Sequence[torch.optim.Optimizer], checkpoint_state_dict: dict[str, Any]
) -> None:
"""Pack the logical optimizer state DCP loaded in place into the optimizers' live state."""
packed_infos = {id(packed_info.parameter): packed_info for packed_info in get_model_packed_parameters(model)}
with torch.no_grad():
for optimizer in optimizers:
for parameter, state in optimizer.state.items():
packed_info = packed_infos.get(id(parameter))
if packed_info is None:
continue
logical_param_states = [checkpoint_state_dict["state"][fqn] for fqn in packed_info.logical_fqns]
for state_key, value in state.items():
loaded_value = logical_param_states[0][state_key]
if isinstance(value, torch.Tensor) and value.shape == packed_info.parameter.shape:
loaded_value = packed_info.spec.pack_logical_tensors(
[logical_param_state[state_key] for logical_param_state in logical_param_states]
)
if isinstance(value, torch.Tensor):
value.copy_(loaded_value)
else:
state[state_key] = loaded_value
def join_loaded_optimizer_state_for_runtime(
model: nn.Module,
checkpoint_state_dict: dict[str, Any],
runtime_state_dict: dict[str, Any],
) -> dict[str, Any]:
"""Pack the logical optimizer state DCP loaded back into the runtime optimizer state."""
if not checkpoint_state_dict:
return checkpoint_state_dict
packed_infos = list(get_model_packed_parameters(model))
if not packed_infos:
return checkpoint_state_dict
restored_state_dict = dict(runtime_state_dict)
restored_state_dict["state"] = dict(runtime_state_dict["state"])
restored_state_dict["param_groups"] = [
{**group, "params": list(group["params"])} for group in checkpoint_state_dict["param_groups"]
]
for packed_info in packed_infos:
if packed_info.fqn in restored_state_dict["state"]:
packed_param_state = restored_state_dict["state"][packed_info.fqn]
logical_param_states = [checkpoint_state_dict["state"][fqn] for fqn in packed_info.logical_fqns]
first_logical_view = packed_info.spec.split_into_logical_views(packed_info.parameter)[0]
for state_key, value in logical_param_states[0].items():
if isinstance(value, torch.Tensor) and value.shape == first_logical_view.shape:
with torch.no_grad():
packed_param_state[state_key].copy_(
packed_info.spec.pack_logical_tensors(
[logical_param_state[state_key] for logical_param_state in logical_param_states]
)
)
else:
packed_param_state[state_key] = value
for group in restored_state_dict["param_groups"]:
param_fqns = group["params"]
if packed_info.logical_fqns[0] not in param_fqns:
continue
first_logical_index = min(param_fqns.index(fqn) for fqn in packed_info.logical_fqns)
group["params"] = [fqn for fqn in param_fqns if fqn not in packed_info.logical_fqns]
group["params"].insert(first_logical_index, packed_info.fqn)
return restored_state_dict
@@ -0,0 +1,7 @@
IGNORE_SLOT = -1
"""A slot is one key a query may read. `IGNORE_SLOT` stands in a slot where the query has no key
at all.
Every query is given the same maximum number of slots, so a query with fewer keys to read leaves
the rest empty, and an empty slot contributes nothing to its attention.
"""
@@ -0,0 +1,222 @@
# Torch-facing layer for the DeepSeek V4 sparse attention kernels: the `prime_rl::dsv4_sparse_attn`
# and `prime_rl::dsv4_sparse_attn_backward` custom ops, their fake (meta) implementations, and the
# autograd rule that ties them together and forms the attention-sink gradient in torch. The
# TileLang kernels themselves live in `dsv4_sparse_attn_fwd.py` and `dsv4_sparse_attn_bwd.py`; this
# module is the only place that knows both exist.
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
# (because nothing loaded the real libcudart globally yet), the self-check fails
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
# ensures dlsym finds it before the stub's own exports.
import ctypes as _ctypes
try:
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
except Exception:
# This is expected on CPU-only machines
pass
import tilelang
import torch
import torch.nn.functional as F
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn_bwd import bwd, postprocess, preprocess
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn_fwd import dsv4_sparse_attn_fwd
LOG2E = 1.44269504
# The forward tiles the gather-slot axis at `block_I = 64` and the backward at `block_size = 32`,
# so the slot count must be a multiple of `lcm(64, 32) = 64`.
SLOT_TILE = 64
def _pad_slots_to_tile(indices: torch.Tensor) -> torch.Tensor:
"""Widen the gather-slot axis to a multiple of the tile, marking the slots that adds absent.
Callers state the slots they mean and this covers the difference, so the tile stays a fact
about these kernels rather than something the modeling code has to lay out for them. An
`IGNORE_SLOT` (-1) slot is masked, so the padding changes no output. Production widths are
usually aligned already (`sliding_window + index_topk = 128 + 512 = 640`), and then this
returns its argument.
"""
remainder = indices.shape[-1] % SLOT_TILE
if remainder == 0:
return indices
return F.pad(indices, (0, SLOT_TILE - remainder), value=IGNORE_SLOT).contiguous()
def sparse_attn_shape_error(heads: int, kv_group: int, dim: int) -> str | None:
"""The reason these kernels cannot serve this shape, or ``None`` if they can.
The forward, the backward and the constructor check in `deepseek_v4/attention.py` all need
the same answer, so the constraints live here only.
"""
# The backward's `preprocess` tiles the channel axis at `block_ND = 32` and reads whole
# tiles, so a `dim` below that (or not a multiple of it) over-reads into the next head and
# silently corrupts `Delta`, hence every gradient. This subsumes `atomic_addx4`'s own
# requirement that four channels be contiguous.
if dim % 32 != 0:
return f"the kernels tile the channel axis at 32 and read whole tiles, but head_dim is {dim}"
# The kernels tile the head axis up to a power of two, at least 16, and index `Sinks`, `Q`,
# `dO`, `Lse` and `dQ` over that padded block. A head count the tiler pads runs off the end
# of all of them; `Q` and `Output` absorb the over-read into the next token's heads, but
# `Sinks` is one row with nothing after it.
head_kv = heads // kv_group
padded_heads = max(tilelang.math.next_power_of_2(head_kv), 16)
if padded_heads != head_kv:
return (
f"the kernels tile {padded_heads} heads per group but this shape has {head_kv}; "
"a head count the tiler pads would read and write past the end of the head axis"
)
# The backward runs `block_H = min(64, padded_H)` rows through a GEMM that needs at least 32.
# At 16 heads the forward compiles and runs, then the backward dies mid-step inside tilelang
# with "warp_row_tiles must be greater than 16", so a forward-only test will not catch this.
if head_kv < 32:
return (
f"the sparse attention backward needs at least 32 heads per group, got {head_kv}; "
"its GEMM over min(64, heads) rows fails to compile below that"
)
return None
@torch.library.custom_op("prime_rl::dsv4_sparse_attn", mutates_args=())
def dsv4_sparse_attn(
q: torch.Tensor,
kv: torch.Tensor,
indices: torch.Tensor,
sinks: torch.Tensor,
sm_scale: float | None = None,
block_I: int = 64,
num_stages: int = 2,
threads: int = 256,
) -> tuple[torch.Tensor, torch.Tensor]:
assert q.is_contiguous(), "q must be contiguous"
assert kv.is_contiguous(), "kv must be contiguous"
assert indices.is_contiguous(), "indices must be contiguous"
batch, seq_len, heads, dim = q.shape
_, _, kv_group, _ = kv.shape
assert kv.shape[-1] == dim, "q and kv must share the full channel dim; DS V4 has no score-only tail"
assert kv.shape[0] == batch
assert q.dtype == torch.bfloat16, (
f"the sparse attention kernel runs in bfloat16 only, but the queries are {q.dtype}"
)
shape_error = sparse_attn_shape_error(heads, kv_group, dim)
assert shape_error is None, shape_error
assert indices.shape[:3] == (batch, seq_len, kv_group)
assert sinks.shape == (heads,)
indices = _pad_slots_to_tile(indices)
topk = indices.shape[-1]
kernel = dsv4_sparse_attn_fwd(
heads,
dim,
topk,
kv_group,
sm_scale,
True,
block_I=block_I,
num_stages=num_stages,
threads=threads,
)
out, lse = kernel(q, kv, indices, sinks.float().contiguous())
return out, lse
# A fake must mirror the op's signature exactly, so it takes every argument even though only `q`,
# the one argument that determines the output shapes, is read.
@dsv4_sparse_attn.register_fake
def _dsv4_sparse_attn_fake(
q: torch.Tensor,
kv: torch.Tensor,
indices: torch.Tensor,
sinks: torch.Tensor,
sm_scale: float | None = None,
block_I: int = 64,
num_stages: int = 2,
threads: int = 256,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(q), q.new_empty(q.shape[:-1], dtype=torch.float32)
@torch.library.custom_op("prime_rl::dsv4_sparse_attn_backward", mutates_args=())
def dsv4_sparse_attn_backward(
q: torch.Tensor,
kv: torch.Tensor,
out: torch.Tensor,
grad_out: torch.Tensor,
indices: torch.Tensor,
lse: torch.Tensor,
sm_scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
assert q.is_contiguous(), "q must be contiguous"
assert kv.is_contiguous(), "kv must be contiguous"
assert indices.is_contiguous(), "indices must be contiguous"
assert lse.is_contiguous(), "lse must be contiguous"
grad_out = grad_out.contiguous()
batch, seq_len, heads, dim = q.shape
_, _, kv_group, _ = kv.shape
assert kv.shape[-1] == dim, "q and kv must share the full channel dim; DS V4 has no score-only tail"
assert kv.shape[0] == batch
# This op is public, so it repeats the forward's shape checks rather than trusting autograd.
shape_error = sparse_attn_shape_error(heads, kv_group, dim)
assert shape_error is None, shape_error
assert indices.shape[:3] == (batch, seq_len, kv_group)
assert lse.shape == (batch, seq_len, heads)
indices = _pad_slots_to_tile(indices)
topk = indices.shape[-1]
preprocess_kernel = preprocess(heads, dim)
bwd_kernel = bwd(heads, dim, topk, kv_group, sm_scale, True)
postprocess_kernel = postprocess(dim, kv_group)
delta = preprocess_kernel(out, grad_out)
dkv = torch.zeros_like(kv, dtype=torch.float32)
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
dkv = postprocess_kernel(dkv)
return dq, dkv, delta
@dsv4_sparse_attn_backward.register_fake
def _dsv4_sparse_attn_backward_fake(
q: torch.Tensor,
kv: torch.Tensor,
out: torch.Tensor,
grad_out: torch.Tensor,
indices: torch.Tensor,
lse: torch.Tensor,
sm_scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
return torch.empty_like(q), torch.empty_like(kv), torch.empty_like(lse)
def _dsv4_sparse_attn_setup_context(ctx, inputs, output) -> None:
q, kv, indices, sinks, sm_scale, _block_I, _num_stages, _threads = inputs
out, lse = output
ctx.save_for_backward(q, kv, out, indices, lse, sinks)
ctx.sm_scale = sm_scale
ctx.mark_non_differentiable(lse)
def _dsv4_sparse_attn_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.Tensor | None):
q, kv, out, indices, lse, sinks = ctx.saved_tensors
dq, dkv, delta = dsv4_sparse_attn_backward(
q.detach(),
kv.detach(),
out.detach(),
grad_out,
indices,
lse.detach(),
ctx.sm_scale,
)
# dp_k/dsink = -p_k * p_sink, so do[d]/dsink = -p_sink * o[d] and the head's sink gradient
# contracts to -p_sink * Delta. The sink logit is unscaled, hence no sm_scale factor.
p_sink = torch.exp2(sinks.float().view(1, 1, -1) * LOG2E - lse)
dsink = -(p_sink * delta).sum(dim=(0, 1)).to(sinks.dtype)
return dq, dkv, None, dsink, None, None, None, None
dsv4_sparse_attn.register_autograd(_dsv4_sparse_attn_autograd_backward, setup_context=_dsv4_sparse_attn_setup_context)
@@ -0,0 +1,326 @@
"""
[DeepSeek V4 Sparse Attention: Backward]
Gradients for the forward in `dsv4_sparse_attn_fwd.py`, whose shapes, index letters and masking
rule carry over unchanged. Three kernels:
preprocess Delta, a per-query-head reduction over the channel axis
bwd dQ, and dKV scattered into a float32 buffer
postprocess casts that buffer back to bfloat16
Beyond the forward's tensors:
dO[b, s, h, d] (B, S, H, D) incoming output gradient, bfloat16
Delta[b, s, h] (B, S, H) float32
dQ[b, s, h, d] (B, S, H, D) bfloat16
dKV[b, n, g, d] (B, N, G, D) float32 until `postprocess`
[What it computes]
With `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` and `scale = D ** -0.5` as in the forward:
Delta[b,s,h] = Output[b,s,h,d] dO[b,s,h,d]
p[b,s,h,k] = exp2(scale * Q[b,s,h,d] key[b,s,k,d] * log2(e) - Lse[b,s,h])
dp[b,s,h,k] = dO[b,s,h,d] key[b,s,k,d]
ds[b,s,h,k] = scale * p[b,s,h,k] * (dp[b,s,h,k] - Delta[b,s,h])
dQ[b,s,h,d] = ds[b,s,h,k] key[b,s,k,d]
dkey[b,s,k,d] = ds[b,s,h,k] Q[b,s,h,d] + p[b,s,h,k] dO[b,s,h,d]
`dkey` has two terms because `V == K`: a gathered position is read once as a key inside the logit
and once as a value inside the output. Per tile of `block_size` slots the block runs five GEMMs,
two rebuilding `p` and `dp`, one for `dQ`, and two accumulating into the `dkey` tile.
`p` is recovered from `Lse` with a single `exp2`, never by a second max pass. The sink needs no
handling here: it is already inside the `Z` that `Lse` encodes, so this `p` is the shrunken
probability the forward produced. No sink gradient is formed in this file; `Delta` is returned so a
caller can build one from it.
[dQ is local, dKV is a scatter]
A block owns one query position, so that query's `dQ` accumulates in registers and is written once.
`dKV` is the opposite: many queries gather the same KV position `n` and they live in different
blocks, so the tile is scattered with `atomic_addx4`, four contiguous channels at a time. That is
why `dKV` is float32 while everything else here is bfloat16, and why `postprocess` exists.
Masked slots skip the store rather than adding their exact zero, and no predicate is written for
it: TileLang already guards the atomic on both bounds, `0 <= idx < N`, and a masked slot's index is
negative.
[How the loop runs]
The grid is `(query position, batch, head block)`, the third axis also carrying the KV head when
`G > 1`, and at `H <= 64` it is a single block covering every query head. The block walks the `K`
slots in tiles of `block_size`, half the forward's tile, and per tile:
1. gather `KV_shared[k,d]`, and seed `acc_p` to `0` or `-inf` from the mask
2. `acc_p[h,k] += Q_shared[h,d] KV_shared[k,d]` onto that seed, then `exp2(... - Lse)` in place,
so a masked slot stays `-inf` and becomes exactly zero. This is `p`.
3. `acc_dp[h,k] = dO_shared[h,d] KV_shared[k,d]`, then `p * (dp - Delta) * scale` in place: `ds`
4. `acc_dq[h,d] += ds[h,k] KV_shared[k,d]`
5. `acc_dkv[k,d] = ds[h,k] Q_shared[h,d] + p[h,k] dO_shared[h,d]`, two GEMMs into one tile
6. scatter `acc_dkv` into `dKV`, in `split_store` passes through a staging buffer that holds
`block_size // split_store` slots
`acc_dq` accumulates over every tile and is written once after the loop, while `acc_dkv` is cleared
each tile because step 6 has already sent it to memory. Steps 2 and 3 leave float32 fragments,
which are cast to bfloat16 and staged in shared memory before feeding the GEMMs of steps 4 and 5.
The TileLang scaffolding is vendored from tile-ai/tilelang (Apache 2.0) and modified for dynamic
shapes. As in the forward there is no score-only channel tail, and `Delta` is exposed as an output
rather than kept internal so the caller can form the per-head sink gradient from it.
"""
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
# (because nothing loaded the real libcudart globally yet), the self-check fails
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
# ensures dlsym finds it before the stub's own exports.
import ctypes as _ctypes
try:
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
except Exception:
# This is expected on CPU-only machines
pass
import tilelang
from tilelang import language as T
@tilelang.jit(out_idx=[-1])
def preprocess(
H,
D,
block_ND=32,
num_stages=5,
dtype=T.bfloat16,
accum_dtype=T.float32,
):
assert dtype == T.bfloat16
assert accum_dtype == T.float32
B = T.dynamic("B")
S = T.dynamic("S")
shape = [B, S, H, D]
@T.prim_func
def preprocess_kernel(
O: T.Tensor(shape, dtype),
dO: T.Tensor(shape, dtype),
Delta: T.Tensor([B, S, H], accum_dtype),
):
with T.Kernel(H, T.ceildiv(S, block_ND), B) as (bx, by, bz):
o = T.alloc_fragment([block_ND, block_ND], accum_dtype)
do = T.alloc_fragment([block_ND, block_ND], accum_dtype)
delta = T.alloc_fragment([block_ND], accum_dtype)
acc = T.alloc_fragment([block_ND, block_ND], accum_dtype)
T.clear(acc)
for k in T.Pipelined(T.ceildiv(D, block_ND), num_stages=num_stages):
T.copy(O[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], o)
T.copy(dO[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], do)
for i, j in T.Parallel(block_ND, block_ND):
acc[i, j] += o[i, j] * do[i, j]
T.reduce_sum(acc, delta, 1)
T.copy(delta, Delta[bz, by * block_ND : (by + 1) * block_ND, bx])
return preprocess_kernel
@tilelang.jit(out_idx=[-1])
def postprocess(
D,
kv_group=1,
block_N=64,
threads=128,
dtype=T.bfloat16,
accum_dtype=T.float32,
):
assert dtype == T.bfloat16
assert accum_dtype == T.float32
B = T.dynamic("B")
S_kv = T.dynamic("S_kv")
dkv_shape = [B, S_kv, kv_group, D]
@T.prim_func
def postprocess_kernel(
dKV: T.Tensor(dkv_shape, accum_dtype),
dKV_out: T.Tensor(dkv_shape, dtype),
):
with T.Kernel(T.ceildiv(S_kv, block_N), kv_group, B, threads=threads) as (bx, by, bz):
T.copy(
dKV[bz, bx * block_N : (bx + 1) * block_N, by, :],
dKV_out[bz, bx * block_N : (bx + 1) * block_N, by, :],
)
return postprocess_kernel
@tilelang.jit(
out_idx=[-2],
pass_configs={
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
# Avoid TileLang MLA backward NaNs: https://github.com/tile-ai/tilelang/issues/2199
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: False,
},
)
def bwd(
H,
D,
topk,
kv_group=1,
sm_scale=None,
is_causal=True,
block_size=32,
num_stages=0,
threads=256,
indices_dtype=T.int32,
dtype=T.bfloat16,
accum_dtype=T.float32,
):
assert is_causal is True, "non-casual is not supported now"
assert topk % block_size == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
assert dtype == T.bfloat16
assert accum_dtype == T.float32
assert indices_dtype == T.int32
if sm_scale is None:
sm_scale = D ** (-0.5)
sm_scale_mul_reciprocal_log2 = sm_scale * 1.44269504 # log2(e)
B = T.dynamic("B")
S = T.dynamic("S")
S_kv = T.dynamic("S_kv")
H_kv = H // kv_group
q_shape = [B, S, H, D]
k_shape = [B, S_kv, kv_group, D]
o_shape = [B, S, H, D]
indices_shape = [B, S, kv_group, topk]
delta_shape = [B, S, H]
lse_shape = [B, S, H]
H = H_kv
padded_H = max(tilelang.math.next_power_of_2(H_kv), 16)
block_H = min(64, padded_H)
assert padded_H % block_H == 0
NH = padded_H // block_H
BS = block_size
NS = tilelang.cdiv(topk, block_size)
split_store = 2
# The acc_dkv accumulator's per-thread layout (from the GEMMs that produce it) is only
# injective at this chunk granularity. TileLang's LayoutInference pass would reject a smaller
# chunk if the store loop below were written over its natural extent, but that loop instead
# iterates the full BS extent and masks with `if bi_i < chunk`, which bypasses the check: an
# invalid chunk silently emits an aliased address formula and corrupts dKV rather than
# raising. Verified this holds independent of warp specialization/TMA.
chunk = BS // split_store
if chunk < 8 or chunk & (chunk - 1) != 0:
raise ValueError(
f"block_size // split_store must be a power of two >= 8, got block_size={BS}, "
f"split_store={split_store} (chunk={chunk}); see comment above for why this silently "
"corrupts dKV instead of failing loudly if violated."
)
@T.prim_func
def dsv4_sparse_attn_bwd_kernel(
Q: T.Tensor(q_shape, dtype),
KV: T.Tensor(k_shape, dtype),
dO: T.Tensor(o_shape, dtype),
Indices: T.Tensor(indices_shape, indices_dtype),
Lse: T.Tensor(lse_shape, accum_dtype),
Delta: T.Tensor(delta_shape, accum_dtype),
dQ: T.Tensor(q_shape, dtype),
dKV: T.Tensor(k_shape, accum_dtype),
):
with T.Kernel(S, B, kv_group * NH, threads=threads) as (s_i, by, bz):
Q_shared = T.alloc_shared([block_H, D], dtype)
KV_shared = T.alloc_shared([BS, D], dtype)
dO_shared = T.alloc_shared([block_H, D], dtype)
mask = T.alloc_fragment([BS], "bool")
P_shared_cast = T.alloc_shared([block_H, BS], dtype)
dP_shared_cast = T.alloc_shared([block_H, BS], dtype)
dQ_shared = T.alloc_shared([block_H, D], dtype)
acc_p = T.alloc_fragment([block_H, BS], accum_dtype)
acc_dp = T.alloc_fragment([block_H, BS], accum_dtype)
acc_dq = T.alloc_fragment([block_H, D], accum_dtype)
acc_dkv = T.alloc_fragment([BS, D], accum_dtype)
acc_dkv_shared = T.alloc_shared([BS // split_store, D], accum_dtype)
# See dsv4_sparse_attn_fwd: a negative index marks an absent key and is the only
# thing masked on, which makes the kernel work for both full and CP-sharded Q
# without needing a global Q offset. TileLang's guarded gather zero-fills the shared
# tile for such a slot, so no clamp is needed here either.
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, :], Q_shared)
T.copy(dO[by, s_i, bz * block_H : (bz + 1) * block_H, :], dO_shared)
T.clear(acc_dq)
for i_i in T.Pipelined(NS, num_stages=num_stages):
for bi_i in T.Parallel(BS):
mask[bi_i] = Indices[by, s_i, bz // NH, i_i * BS + bi_i] >= 0
for h_i, bi_i in T.Parallel(block_H, BS):
acc_p[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_p.dtype))
for bi_i, d_i in T.Parallel(BS, D):
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, d_i]
T.gemm(Q_shared, KV_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
for h_i, bi_i in T.Parallel(block_H, BS):
acc_p[h_i, bi_i] = T.exp2(
acc_p[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - Lse[by, s_i, bz * block_H + h_i]
)
T.copy(acc_p, P_shared_cast)
T.gemm(
dO_shared, KV_shared, acc_dp, transpose_B=True, policy=T.GemmWarpPolicy.FullCol, clear_accum=True
)
for h_i, bi_i in T.Parallel(block_H, BS):
acc_dp[h_i, bi_i] = (
acc_p[h_i, bi_i] * (acc_dp[h_i, bi_i] - Delta[by, s_i, bz * block_H + h_i]) * sm_scale
)
T.copy(acc_dp, dP_shared_cast)
T.gemm(dP_shared_cast, KV_shared, acc_dq, policy=T.GemmWarpPolicy.FullCol)
T.gemm(
dP_shared_cast,
Q_shared,
acc_dkv,
transpose_A=True,
policy=T.GemmWarpPolicy.FullCol,
clear_accum=True,
)
T.gemm(P_shared_cast, dO_shared, acc_dkv, transpose_A=True, policy=T.GemmWarpPolicy.FullCol)
for s in range(split_store):
for bi_i, d_i in T.Parallel(BS, D):
if bi_i < BS // split_store:
acc_dkv_shared[bi_i, d_i] = acc_dkv[bi_i + s * (BS // split_store), d_i]
# A masked slot accumulates exactly zero, and issuing its atomic would only
# serialize the scatter. No predicate is written here because TileLang already
# emits `if (0 <= idx)` and `if (idx < S_kv)` around the store, so a negative
# index skips it for free and an out-of-range one cannot write past the end of
# dKV. Do not add a predicate back: reading the `mask` fragment here compiles
# cleanly but pins this loop to the four threads owning those elements.
for bi_i, d_i in T.Parallel(BS // split_store, D // 4):
slot_i = i_i * BS + bi_i + s * (BS // split_store)
T.atomic_addx4(
dKV[by, Indices[by, s_i, bz // NH, slot_i], bz // NH, d_i * 4],
acc_dkv_shared[bi_i, d_i * 4],
)
T.copy(acc_dq, dQ_shared)
T.copy(dQ_shared, dQ[by, s_i, bz * block_H : (bz + 1) * block_H, :])
return dsv4_sparse_attn_bwd_kernel
@@ -0,0 +1,277 @@
"""
[DeepSeek V4 Sparse Attention: Forward]
Each query attends to an explicit list of `K` KV positions supplied by the caller, rather than to
a contiguous causal span. This kernel only reads that list; it has no opinion on how the positions
were chosen. Because every query carries a different list, the kernel runs one block per query
position instead of tiling over a block of queries the way dense flash attention does.
Shapes, with the capital of an index letter naming that axis's size:
Q[b, s, h, d] (B, S, H, D) queries, bfloat16
KV[b, n, g, d] (B, N, G, D) keys, bfloat16; V == K here, so one buffer is both
Indices[b, s, g, k] (B, S, G, K) int32 positions into KV's `n` axis
Sinks[h] (H,) float32, one learnable logit per query head
Output[b, s, h, d] (B, S, H, D) bfloat16
Lse[b, s, h] (B, S, H) float32
- `b` batch index
- `s` query position
- `n` KV position
- `k` gather slot, one of the `K` a query reads
- `d` head dimension
- `h` query head index
- `g` KV head index, always of size 1; see below
`G` is always 1: every query head reads the same single KV head. The axis survives from the
vendored scaffolding, where `G > 1` would split the `H` query heads into `G` contiguous blocks of
`H / G`, each reading its own KV head. Nothing exercises that path, and the head-padding case
asserts `G == 1` outright, so the equations below fix `g = 0` and drop it. Note that the parameter
is spelled `kv_group` but counts KV heads; the query heads per KV head are `H / G`, spelled
`head_kv`.
[What it computes]
Write `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` for the gathered keys. Summing over repeated
indices, and with `scale = D ** -0.5`:
logit[b,s,h,k] = scale * Q[b,s,h,d] key[b,s,k,d]
Z[b,s,h] = exp(Sinks[h]) + sum_k exp(logit[b,s,h,k])
p[b,s,h,k] = exp(logit[b,s,h,k]) / Z[b,s,h]
Output[b,s,h,d] = p[b,s,h,k] key[b,s,k,d]
Lse[b,s,h] = log2(Z[b,s,h])
Note: the sink logit is unscaled; `scale` multiplies the dot products and not `Sinks`. And `Lse`
is a base-2 logarithm of a partition function built from natural exponentials, not `ln Z`; that is
what lets the backward recover `p` as `exp2(logit * log2(e) - Lse)` with a single `exp2`.
The sink contributes to the denominator but owns no key, so `sum_k p[b,s,h,k] < 1` and `Output` is
a shrunken combination of the gathered keys. That is how a head attends to nothing in particular.
[What the caller must guarantee]
`K` is fixed when the kernel compiles and is part of its compilation key, so it is sized for the
most keys any query could need and a given query will often have fewer.
Every unused slot must hold a negative index, which is the masking condition:
Indices[b,s,0,k] < 0 .
This is the only masking the kernel performs. It applies no causality test and never compares
`k` against `s`: whatever the caller means by a valid key is encoded entirely in the index values.
That is also what keeps the kernel correct when `s` is a local index that does not correspond to a
global KV position.
Every other entry must be a real position in `[0, N)`. Nothing checks that: a device-side check
would cost a sync, so an out-of-range index silently corrupts that query's softmax.
[How the loop runs]
The grid is `(query position, batch, KV head)`, so with `G == 1` that is one block per query
position per batch index, holding all `H` query heads of that query at once, or a 64-head chunk
when `H > 64` (`REPLICATE_H`). The block walks the `K` slots in tiles of `block_I`,
software-pipelined `num_stages` deep, and per tile:
1. gather `KV_shared[k,d] = KV[b, Indices[b,s,0,k], 0, d]` into one shared tile of keys
2. `acc_s[h,k] = Q_shared[h,d] KV_shared[k,d]`, pre-seeded to `-inf` at masked slots
3. rescale the running max, the denominator and `acc_o` (online softmax)
4. `acc_o[h,d] += acc_s[h,k] KV_shared[k,d]`, reusing that same tile as values
Step 4 reusing step 1's tile is the `V == K` property: the gather is paid for once and feeds both
GEMMs.
The online softmax is seeded from the sink rather than from an empty sum. `m_i` is carried in raw
dot-product units, so seeding it with `Sinks[h] / scale` makes `m_i * scale * log2(e)` equal
`Sinks[h] * log2(e)`, and seeding `sumexp` to `1` is exactly that term's own exponential relative
to that max. `T.reduce_max(..., clear=False)` then keeps the sink as a floor on the running max. A
query whose slots are all masked therefore emits `Output = 0` and a finite
`Lse = Sinks[h] * log2(e)`, where a zero-seeded denominator would divide by zero.
The TileLang scaffolding is vendored from tile-ai/tilelang (Apache 2.0) and modified for dynamic
shapes. The attention itself differs from tilelang's sparse MLA: there is no score-only channel
tail (every channel feeds both the score and the output), and the per-head learnable sink logit is
folded into the online softmax as described above.
"""
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
# (because nothing loaded the real libcudart globally yet), the self-check fails
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
# ensures dlsym finds it before the stub's own exports.
import ctypes as _ctypes
try:
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
except Exception:
# This is expected on CPU-only machines
pass
import tilelang
from tilelang import language as T
LOG2E = 1.44269504
@tilelang.jit(
out_idx=[-2, -1],
pass_configs={
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
},
)
def dsv4_sparse_attn_fwd(
heads,
dim,
topk,
kv_group=1,
sm_scale=None,
is_causal=True,
block_I=64,
num_stages=2,
threads=256,
):
assert dim == tilelang.math.next_power_of_2(dim), f"haven't check padding correctness yet, dim={dim}"
assert is_causal is True, "non-casual is not supported"
assert topk % block_I == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
if sm_scale is None:
sm_scale = (1.0 / dim) ** 0.5
# Both names are kept: the sink logit enters the softmax unscaled, so seeding the running max
# with it means dividing by the raw scale that every `exp2` site below multiplies back in.
sm_scale_mul_reciprocal_log2 = sm_scale * LOG2E
batch = T.dynamic("batch")
seq_len = T.dynamic("seq_len")
seq_len_kv = T.dynamic("seq_len_kv")
head_kv = heads // kv_group
q_shape = [batch, seq_len, heads, dim]
kv_shape = [batch, seq_len_kv, kv_group, dim]
o_shape = [batch, seq_len, heads, dim]
indices_shape = [batch, seq_len, kv_group, topk]
sinks_shape = [heads]
lse_shape = [batch, seq_len, heads]
indices_dtype = T.int32
dtype = T.bfloat16
accum_dtype = T.float32
H = head_kv
padded_H = max(tilelang.math.next_power_of_2(head_kv), 16)
if padded_H != H:
assert kv_group == 1, (
"here we solve the H padding automatically, other wise you should handle Q copy and Output copy"
" with your mask (when kv_group == 1, use g_i * padded_H:(g_i+1) * padded_H would be handled"
" automatically)"
)
BI = block_I
NI = tilelang.cdiv(topk, block_I)
D = dim
if head_kv > 64:
assert head_kv % 64 == 0, "head_kv should be a multiple of 64"
REPLICATE_H = head_kv // 64
else:
REPLICATE_H = 1
H_per_block = padded_H if REPLICATE_H == 1 else 64
@T.prim_func
def main(
Q: T.Tensor(q_shape, dtype), # type: ignore
KV: T.Tensor(kv_shape, dtype), # type: ignore
Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
Sinks: T.Tensor(sinks_shape, accum_dtype), # type: ignore
Output: T.Tensor(o_shape, dtype), # type: ignore
Lse: T.Tensor(lse_shape, accum_dtype), # type: ignore
):
with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as (
bx,
by,
bz,
):
Q_shared = T.alloc_shared([H_per_block, D], dtype)
KV_shared = T.alloc_shared([BI, D], dtype)
mask = T.alloc_fragment([BI], "bool")
acc_o = T.alloc_fragment([H_per_block, D], accum_dtype)
acc_s = T.alloc_fragment([H_per_block, BI], accum_dtype)
S_shared = T.alloc_shared([H_per_block, BI], dtype)
sumexp = T.alloc_fragment([H_per_block], accum_dtype)
sumexp_i = T.alloc_fragment([H_per_block], accum_dtype)
alpha = T.alloc_fragment([H_per_block], accum_dtype)
m_i = T.alloc_fragment([H_per_block], accum_dtype)
m_i_prev = T.alloc_fragment([H_per_block], accum_dtype)
b_i, g_i = by, bz
s_i = bx if REPLICATE_H == 1 else (bx // REPLICATE_H)
# A negative index marks an absent key, and it is the only thing this kernel masks
# on. That preserves causality and varlen masking for both full and CP-sharded Q
# (where local q_i no longer matches the global K position), because the caller has
# already resolved all of it into the index values.
#
# No clamp guards the gather below. TileLang lowers it to `cp_async_gs_conditional`,
# whose condition is `0 <= idx < seq_len_kv` and whose `cp.async` src-size operand is
# 0 when that fails, so PTX zero-fills the shared tile. A masked slot therefore reads
# as a zero key. The backward relies on the same guard; the sibling
# `kernels/sparse_mla_{fwd,bwd}.py` still use a trailing zero sentinel row instead.
H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
H1 = H0 + H_per_block
T.fill(acc_o, 0)
# The online softmax starts from the sink term alone rather than from an empty sum:
# `m_i` carries raw dot-product units, so `m_i * sm_scale_mul_reciprocal_log2` equals
# `sink * log2(e)` and the seed `sumexp` of 1 is exactly that term's own exponential.
# `T.reduce_max(..., clear=False)` then keeps the sink as a floor on the running max.
# A row whose slots are all masked therefore emits `out = 0` and a finite
# `Lse = sink * log2(e)`, where a zero-seeded denominator would divide by zero.
for h_i in T.Parallel(H_per_block):
sumexp[h_i] = 1.0
for h_i in T.Parallel(H_per_block):
m_i[h_i] = Sinks[H0 + h_i] / sm_scale
T.copy(Q[b_i, s_i, H0:H1, :], Q_shared)
for i_i in T.Pipelined(NI, num_stages=num_stages):
for bi_i in T.Parallel(BI):
mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] >= 0
for bi_i, d_i in T.Parallel(BI, D):
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i]
for h_i, bi_i in T.Parallel(H_per_block, BI):
acc_s[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_s.dtype))
T.gemm(
Q_shared,
KV_shared,
acc_s,
transpose_B=True,
policy=T.GemmWarpPolicy.FullRow,
)
T.copy(m_i, m_i_prev)
T.reduce_max(acc_s, m_i, dim=1, clear=False)
for h_i in T.Parallel(H_per_block):
m_i[h_i] = T.max(m_i[h_i], m_i_prev[h_i])
for h_i in T.Parallel(H_per_block):
alpha[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale_mul_reciprocal_log2)
for h_i, bi_i in T.Parallel(H_per_block, BI):
acc_s[h_i, bi_i] = T.exp2(
acc_s[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - m_i[h_i] * sm_scale_mul_reciprocal_log2
)
T.reduce_sum(acc_s, sumexp_i, dim=1)
for h_i in T.Parallel(H_per_block):
sumexp[h_i] = sumexp[h_i] * alpha[h_i] + sumexp_i[h_i]
for h_i, d_i in T.Parallel(H_per_block, D):
acc_o[h_i, d_i] = acc_o[h_i, d_i] * alpha[h_i]
T.copy(acc_s, S_shared)
T.gemm(S_shared, KV_shared, acc_o, policy=T.GemmWarpPolicy.FullRow)
for h_i, d_i in T.Parallel(H_per_block, D):
acc_o[h_i, d_i] /= sumexp[h_i]
for h_i in T.Parallel(H_per_block):
sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale_mul_reciprocal_log2
T.copy(acc_o, Output[b_i, s_i, H0:H1, :])
T.copy(sumexp, Lse[b_i, s_i, H0:H1])
return main
@@ -130,9 +130,7 @@ class LagunaFlashAttention(FlashAttention):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states, key_states, value_states = self.project_qkv(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
+19 -11
View File
@@ -5,6 +5,8 @@ from typing import Literal
import torch
from torch import nn
from prime_rl.trainer.models.fusions import fuse_qkv_projections
from .norms import RMSNorm, RMSNormConfig
from .rotary_emb import apply_rotary_pos_emb
@@ -48,6 +50,8 @@ class AttentionConfig:
class FlashAttention(nn.Module):
"""Flash Attention"""
supported_fusions = {"qkv": fuse_qkv_projections}
_funcs = {
2: flash_attn_varlen_func,
3: flash_attn_3_varlen_func,
@@ -61,15 +65,15 @@ class FlashAttention(nn.Module):
self.scaling = self.head_dim**-0.5
self.is_causal = config.is_causal
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
self.qkv_sizes = (
config.num_attention_heads * self.head_dim,
config.num_key_value_heads * self.head_dim,
config.num_key_value_heads * self.head_dim,
)
self.q_proj = nn.Linear(config.hidden_size, self.qkv_sizes[0], bias=config.attention_bias)
self.k_proj = nn.Linear(config.hidden_size, self.qkv_sizes[1], bias=config.attention_bias)
self.v_proj = nn.Linear(config.hidden_size, self.qkv_sizes[2], bias=config.attention_bias)
self.register_module("qkv_proj", None)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
@@ -91,6 +95,12 @@ class FlashAttention(nn.Module):
if self._flash_attn_version == 4:
self._flash_attn_call = torch._dynamo.disable(self.func)
def project_qkv(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Query, key and value projections, from one packed GEMM when qkv is fused."""
if self.qkv_proj is None:
return self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
return self.qkv_proj(hidden_states).split(self.qkv_sizes, dim=-1)
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
kwargs: dict = {"causal": True}
@@ -119,9 +129,7 @@ class FlashAttention(nn.Module):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states, key_states, value_states = self.project_qkv(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
+30 -12
View File
@@ -13,6 +13,7 @@ from torch import nn
from torch.distributed.tensor import DTensor
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
from prime_rl.trainer.models.layers.grouped_gemm import BF16GroupedGemm, GroupedGemm
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
@@ -82,6 +83,8 @@ def broadcast_expert_bias(
class GroupedExperts(nn.Module):
supported_fusions = {"gate_up": fuse_gate_up_projections}
def __init__(
self,
dim: int,
@@ -98,6 +101,7 @@ class GroupedExperts(nn.Module):
self.hidden_dim = hidden_dim
self.gate_proj = nn.Parameter(torch.empty(num_experts, hidden_dim, dim)) if expert_type == "gated" else None
self.up_proj = nn.Parameter(torch.empty(num_experts, hidden_dim, dim))
self.register_parameter("gate_up_proj", None)
self.down_proj = nn.Parameter(torch.empty(num_experts, dim, hidden_dim))
self.gate_proj_bias = (
nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias and self.gate_proj is not None else None
@@ -107,6 +111,8 @@ class GroupedExperts(nn.Module):
self.grouped_gemm = grouped_gemm or BF16GroupedGemm()
self.activation = ActivationDispatch[activation]
if expert_type == "non_gated":
self.supported_fusions = {}
@property
def token_group_alignment(self) -> int:
@@ -128,19 +134,26 @@ class GroupedExperts(nn.Module):
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
x_bf16 = x.bfloat16()
up_proj = to_local(self.up_proj).transpose(-2, -1)
up = self.grouped_gemm(x_bf16, up_proj.bfloat16(), offs=offsets)
if self.gate_up_proj is None:
up_proj = to_local(self.up_proj).transpose(-2, -1)
up = self.grouped_gemm(x_bf16, up_proj.bfloat16(), offs=offsets)
gate = None
if self.gate_proj is not None:
gate_proj = to_local(self.gate_proj).transpose(-2, -1)
gate = self.grouped_gemm(x_bf16, gate_proj.bfloat16(), offs=offsets)
else:
gate_up_proj = to_local(self.gate_up_proj).transpose(-2, -1)
gate_up = self.grouped_gemm(x_bf16, gate_up_proj.bfloat16(), offs=offsets)
gate, up = gate_up.chunk(2, dim=-1)
if self.up_proj_bias is not None:
up_proj_bias = to_local(self.up_proj_bias)
up = up + broadcast_expert_bias(up_proj_bias, num_tokens_per_expert, up.shape[0]).bfloat16()
gate = None
if self.gate_proj is not None:
gate_proj = to_local(self.gate_proj).transpose(-2, -1)
gate = self.grouped_gemm(x_bf16, gate_proj.bfloat16(), offs=offsets)
if self.gate_proj_bias is not None:
gate_proj_bias = to_local(self.gate_proj_bias)
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
if gate is not None and self.gate_proj_bias is not None:
gate_proj_bias = to_local(self.gate_proj_bias)
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
hidden = self.activation.apply(gate, up)
down_proj = to_local(self.down_proj).transpose(-2, -1)
@@ -151,9 +164,14 @@ class GroupedExperts(nn.Module):
return output.type_as(x)
def init_weights(self, init_std: float):
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
nn.init.trunc_normal_(first_projection, mean=0.0, std=0.02)
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
if self.gate_up_proj is None:
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
nn.init.trunc_normal_(first_projection, mean=0.0, std=0.02)
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
else:
gate_proj, up_proj = self.gate_up_proj.chunk(2, dim=1)
nn.init.trunc_normal_(gate_proj, mean=0.0, std=0.02)
remaining = (up_proj, self.down_proj)
for weight in remaining:
nn.init.trunc_normal_(weight, mean=0.0, std=init_std)
for bias in (self.gate_proj_bias, self.up_proj_bias, self.down_proj_bias):
+51 -1
View File
@@ -1,9 +1,12 @@
import torch
import torch.distributed as dist
from dion import Muon
from torch import nn
from torch.distributed.device_mesh import DeviceMesh
from torch.optim import SGD, AdamW, Optimizer
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
from prime_rl.trainer.models.fusions import get_model_packed_parameters
from prime_rl.trainer.optim.base import OffloadOptimizer as OffloadOptimizer
from prime_rl.trainer.optim.base import OptimizerLike
from prime_rl.trainer.optim.offload import (
@@ -17,6 +20,33 @@ from prime_rl.trainer.sign_sgd import SignSGD
from prime_rl.utils.logger import get_logger
def _warmup_muon_mesh(mesh: DeviceMesh) -> None:
"""Establish NCCL peer connections before Muon's first optimizer step.
This is a correctness workaround, not an optional performance warm-up:
multi-node GLM-Air training can deadlock on Muon's first bulk all-to-all
without it. Optimizer refactors must preserve this initialization.
"""
# get_group() without a mesh dim is only valid for 1-D meshes; the
# replicate-only world mesh is 2-D and has no single group to warm.
if mesh.ndim != 1:
return
group = mesh.get_group()
size = dist.get_world_size(group)
if size <= 1 or dist.get_backend(group) != "nccl":
return
get_logger().info(f"Warming Muon all-to-all connections on group {group.group_name} ({size} ranks)")
device = torch.device("cuda", torch.cuda.current_device())
# Use a bulk list all-to-all, matching Dion's path rather than a scalar
# collective that may leave bulk-transfer peer channels uninitialized.
inputs = [torch.zeros(3 * 1024 * 1024, dtype=torch.bfloat16, device=device) for _ in range(size)]
outputs = [torch.empty_like(tensor) for tensor in inputs]
dist.all_to_all(outputs, inputs, group=group, async_op=True).wait()
torch.cuda.synchronize()
get_logger().info(f"Finished warming Muon all-to-all connections on group {group.group_name}")
def setup_optimizer(
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
@@ -54,6 +84,7 @@ def setup_optimizer(
optimizer_named_params,
parallel_dims,
fused_adamw=config.type == "adamw" and not cpu_offload,
model=model,
)
if full_offload_config is not None:
@@ -80,6 +111,7 @@ def _create_optimizer(
parallel_dims: ParallelDims,
lr: float | None = None,
fused_adamw: bool = False,
model: nn.Module | None = None,
) -> Optimizer:
"""Create optimizer. If lr is None, uses config.lr."""
if lr is None:
@@ -107,7 +139,7 @@ def _create_optimizer(
fused=fused_adamw,
)
case "muon":
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
return _create_muon_optimizer(config, named_params, parallel_dims, model, lr)
case "sign_sgd":
return SignSGD(
params=trainable_params,
@@ -120,6 +152,7 @@ def _create_muon_optimizer(
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
model: nn.Module | None,
lr: float | None = None,
) -> Optimizer:
def muon_enabled(n, p):
@@ -185,8 +218,20 @@ def _create_muon_optimizer(
else:
distributed_mesh = parallel_dims.world_mesh
# Runtime fusions pack several logical matrices into one physical parameter. Muon
# orthogonalizes each of them separately, so a packed parameter trains exactly as the
# matrices it replaces would. Packed biases and frozen parameters are not Muon's.
matrix_partitions = {}
if model is not None:
muon_params = {p for group in param_groups if group["algorithm"] == "muon" for p in group["params"]}
for packed_info in get_model_packed_parameters(model):
partitions = packed_info.spec.muon_matrix_partitions(packed_info.parameter)
if partitions is not None and packed_info.parameter in muon_params:
matrix_partitions[packed_info.parameter] = partitions
optimizer = Muon(
params=param_groups,
matrix_partitions=matrix_partitions,
lr=lr,
mu=config.mu,
betas=(config.betas1, config.betas2),
@@ -196,4 +241,9 @@ def _create_muon_optimizer(
world_mesh=parallel_dims.world_mesh,
fsdp_mesh_dim=1 if parallel_dims.dp_replicate_enabled else 0,
)
# Keep both warm-ups after Muon construction and before its first step. The
# main and expert groups establish independent NCCL peer connections.
_warmup_muon_mesh(distributed_mesh)
if expert_params and parallel_dims.ep_enabled:
_warmup_muon_mesh(parallel_dims.get_mesh("dp_shard_mod_ep"))
return optimizer
+2 -1
View File
@@ -114,7 +114,8 @@ def train(config: TrainerConfig):
# Set precision
setup_torch_distributed(
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
timeout=timedelta(seconds=config.dist_timeout_seconds),
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
)
if config.model.full_offload is not None:
setup_full_cpu_optimizer_offload(config.model.full_offload)
+2 -1
View File
@@ -100,7 +100,8 @@ def train(config: SFTConfig):
# Set precision
setup_torch_distributed(
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
timeout=timedelta(seconds=config.dist_timeout_seconds),
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
)
if config.model.full_offload is not None:
setup_full_cpu_optimizer_offload(config.model.full_offload)
+23 -8
View File
@@ -1,6 +1,6 @@
import pickle
from pathlib import Path
from typing import Callable, Generator, cast
from typing import Callable, Generator
import torch
import torch.distributed as dist
@@ -18,6 +18,7 @@ from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.utils.logger import get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
from prime_rl.utils.vlm import get_layer_prefix
from prime_rl.utils.weights import resolve_wire_dtype
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
@@ -80,6 +81,25 @@ def filter_state_dict_by_layers(
)
def resolve_dtensors(
state_dict: dict[str, Tensor],
keep_in_fp32: Callable[[str], bool] | None,
default_dtype: torch.dtype,
) -> dict[str, Tensor]:
"""Replace every sharded tensor with its full tensor, at the dtype it goes on the wire in.
Only DTensors are touched, since only they need gathering. A buffer is never sharded, so it
goes on the wire in whatever dtype it already holds and its fp32 declaration, if it has one,
is never consulted. TODO: NIXL transport does not use this function; unify logic.
"""
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
# only gather after the downcast as it will be faster
target_dtype = resolve_wire_dtype(keep_in_fp32, key, default_dtype)
state_dict[key] = value.to(target_dtype).full_tensor()
return state_dict
def preprocess_layer_checkpoint(
model: nn.Module,
layer_state_dict: dict[str, Tensor],
@@ -149,18 +169,13 @@ class NCCLBroadcaster:
else:
preprocess_fn = preprocess_layer_checkpoint
keep_in_fp32 = getattr(model, "keep_in_fp32_for_weight_transfer", None)
for layer_id, layer_state_dict in filter_state_dict_by_layers(state_dict, num_layers, layer_prefix):
layer_state_dict = self._resolve_dtensors(layer_state_dict)
layer_state_dict = resolve_dtensors(layer_state_dict, keep_in_fp32, self.dtype)
layer_state_dict = preprocess_fn(model, layer_state_dict, layer_id)
if self.world.is_master:
broadcast_state_dict(layer_state_dict, self.communicator)
def _resolve_dtensors(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
state_dict[key] = cast(DTensor, value.to(self.dtype)).full_tensor()
return state_dict
class NCCLWeightSender(WeightSender):
"""Broadcast weights into the inference engine using NCCL."""
+12 -3
View File
@@ -2,7 +2,7 @@ import json
import re
import warnings
from pathlib import Path
from typing import cast
from typing import Callable, cast
import torch
import torch.distributed as dist
@@ -18,7 +18,6 @@ from transformers.utils import (
SAFE_WEIGHTS_NAME,
)
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
@@ -98,6 +97,8 @@ def convert_state_dict_to_hf(model: nn.Module, state_dict: dict[str, Tensor]) ->
Format detection uses the model's full key set, so a partial dict (one rank's
slice) converts the same way as the full state dict would.
"""
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
full_keys = dict.fromkeys(resolve_fqn(model, key) for key in model.state_dict().keys())
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(full_keys):
# PrimeRL custom model holding weights in prime format: apply the model's
@@ -150,6 +151,14 @@ def partition_weights(state_dict: dict[str, Tensor], world_size: int, dtype: tor
return {key: unit_owner[unit] for key, unit in key_to_unit.items()}
def resolve_wire_dtype(keep_in_fp32: Callable[[str], bool] | None, key: str, default: torch.dtype) -> torch.dtype:
"""The dtype a tensor must travel to the inference engine in.
TODO: NIXL keeps its own inline copy of this rule; unify the handling.
"""
return torch.float32 if keep_in_fp32 is not None and keep_in_fp32(key) else default
def gather_weights_parallel(model: nn.Module, dtype: torch.dtype = torch.bfloat16) -> dict[str, Tensor]:
"""Gather distributed weights cooperatively, each rank keeping a slice on CPU.
@@ -177,7 +186,7 @@ def gather_weights_parallel(model: nn.Module, dtype: torch.dtype = torch.bfloat1
for key, value in model.state_dict().items():
if isinstance(value, DTensor):
# only gather after the downcast to dtype as it will be faster
target_dtype = torch.float32 if keep_in_fp32 is not None and keep_in_fp32(key) else dtype
target_dtype = resolve_wire_dtype(keep_in_fp32, key, dtype)
value = cast(DTensor, value.to(target_dtype)).full_tensor()
if owners[key] != world.rank:
continue
+114 -105
View File
@@ -1,12 +1,3 @@
"""DeepSeek V4 checks that need a GPU.
There is no HF oracle here. `transformers.models.deepseek_v4` only exists from transformers 5.15
and the repo pins an older version, so every assertion is either self-consistency (packed against
unpacked), a closed form written out by hand, or vLLM's own loader. That rules out the parity
archetype the other models in this directory use, where a tiny `HF<X>ForCausalLM` supplies the
expected logits and gradients.
"""
import math
import re
from unittest.mock import MagicMock
@@ -30,7 +21,7 @@ pytestmark = [pytest.mark.gpu]
# 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
# branches are what carries any long-range signal.
_MODEL = dict(
MODEL = dict(
vocab_size=64,
hidden_size=128,
moe_intermediate_size=64,
@@ -72,12 +63,12 @@ _MODEL = dict(
rms_norm_eps=1e-6,
)
_MODEL_BATCH, _MODEL_SEQ = 2, 32
_MODULE_BATCH = 2
MODEL_BATCH, MODEL_SEQ = 2, 32
MODULE_BATCH = 2
_CSA_LAYER, _HCA_LAYER = 1, 2
_COMPRESS_RATE = _MODEL["compress_rates"]["compressed_sparse_attention"]
_HCA_COMPRESS_RATE = _MODEL["compress_rates"]["heavily_compressed_attention"]
SLIDING_LAYER, CSA_LAYER, HCA_LAYER = 0, 1, 2
COMPRESS_RATE = MODEL["compress_rates"]["compressed_sparse_attention"]
HCA_COMPRESS_RATE = MODEL["compress_rates"]["heavily_compressed_attention"]
@pytest.fixture(autouse=True)
@@ -134,27 +125,28 @@ def _randomize(module: nn.Module) -> None:
buffer.copy_(_tid2eid(buffer.shape[0], router.num_experts, router.top_k))
def _prime_config() -> DeepseekV4Config:
return DeepseekV4Config(**_MODEL)
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) -> nn.Module:
def get_prime_model(dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> 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())
model = DeepseekV4ForCausalLM._from_config(_prime_config(attn_impl))
_randomize(model)
inject_prime_lm_head(model, chunk_size=None)
return model
def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16) -> nn.Module:
def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> 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(), layer_idx=layer_idx)
module = DeepseekV4Attention(_prime_config(attn_impl), layer_idx=layer_idx)
_randomize(module)
return module
@@ -194,12 +186,12 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedCont
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()
hash_layers = prime_model.model.layers[: _MODEL["num_hash_layers"]]
hash_layers = prime_model.model.layers[: MODEL["num_hash_layers"]]
assert hash_layers, "config must contain a hash-routed layer"
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((MODEL_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)
@@ -210,7 +202,7 @@ 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]] = MODEL_BATCH * MODEL_SEQ
torch.testing.assert_close(counts[0][0], expected)
@@ -222,7 +214,7 @@ def test_deepseek_v4_backward():
_randomize(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"], (MODEL_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()
@@ -268,11 +260,11 @@ def _fill_hash_tables(model: nn.Module) -> dict[int, torch.Tensor]:
for layer_idx, layer in enumerate(model.model.layers):
if not layer.mlp.is_hash:
continue
table = _tid2eid(_MODEL["vocab_size"], _MODEL["n_routed_experts"], _MODEL["num_experts_per_tok"])
table = _tid2eid(MODEL["vocab_size"], MODEL["n_routed_experts"], MODEL["num_experts_per_tok"])
with torch.no_grad():
layer.mlp.router.tid2eid.copy_(table)
tables[layer_idx] = table
assert len(tables) == _MODEL["num_hash_layers"], "config must contain hash-routed layers"
assert len(tables) == MODEL["num_hash_layers"], "config must contain hash-routed layers"
return tables
@@ -282,7 +274,7 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
It is the one buffer no `init_weights` can reconstruct: an all-zero table is a valid tensor
that routes every token to expert 0, so a rename anywhere along the loading path degrades the
model in silence rather than raising. `test_deepseek_v4_weight_conversion_roundtrip` only ever
roundtrips the zeros the constructor leaves behind, and `_VLLM_MAPPED_NAMES` pins the on-disk
roundtrips the zeros the constructor leaves behind, and `VLLM_MAPPED_NAMES` pins the on-disk
name without saying where it lands, so this carries real values across the whole path.
Three things in sequence, because they are three links in one chain. The conversion emits only
@@ -332,7 +324,7 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
# What vLLM's DeepSeek V4 loader sees, with the layer and expert indices folded away. Written
# out rather than derived: this file has no independent implementation to derive it from, and a
# rename on either side of the boundary is exactly what it exists to catch.
_VLLM_MAPPED_NAMES = {
VLLM_MAPPED_NAMES = {
"lm_head.weight",
"model.embed_tokens.weight",
"model.hc_head_base",
@@ -407,9 +399,9 @@ def test_deepseek_v4_on_disk_keys_map_to_the_names_vllm_expects():
for expert_dtype in ("fp8", "fp4"):
mapper = _make_deepseek_v4_weights_mapper(expert_dtype)
mapped = {re.sub(r"\.\d+\.", ".{i}.", mapper._map_name(key)) for key in on_disk_state_dict}
assert mapped == _VLLM_MAPPED_NAMES, (
f"{expert_dtype}: unexpected {sorted(mapped - _VLLM_MAPPED_NAMES)}, "
f"missing {sorted(_VLLM_MAPPED_NAMES - mapped)}"
assert mapped == VLLM_MAPPED_NAMES, (
f"{expert_dtype}: unexpected {sorted(mapped - VLLM_MAPPED_NAMES)}, "
f"missing {sorted(VLLM_MAPPED_NAMES - mapped)}"
)
@@ -451,29 +443,29 @@ def test_deepseek_v4_init_buffers_post_meta_restores_every_rotary():
# the cos/sin cache is `original_max * factor` rows of fp32, which at the checkpoint's 65536 would
# allocate 268 MB per rope. 4096 still places the correction range at channels 10 to 23, well
# inside the 32 channel pairs, so the ramp is exercised.
_ROPE_FACTOR = 16
_ROPE_ORIGINAL_MAX_POSITION = 4096
_ROPE_BETA_FAST, _ROPE_BETA_SLOW = 32, 1
_ROPE_THETA, _COMPRESS_ROPE_THETA = 10000.0, 160000.0
_ROPE_HEAD_DIM, _ROPE_ROTARY_DIM = 512, 64
_ROPE_MAX_POSITION = _ROPE_ORIGINAL_MAX_POSITION * _ROPE_FACTOR
ROPE_FACTOR = 16
ROPE_ORIGINAL_MAX_POSITION = 4096
ROPE_BETA_FAST, ROPE_BETA_SLOW = 32, 1
ROPE_THETA, COMPRESS_ROPE_THETA = 10000.0, 160000.0
ROPE_HEAD_DIM, ROPE_ROTARY_DIM = 512, 64
ROPE_MAX_POSITION = ROPE_ORIGINAL_MAX_POSITION * ROPE_FACTOR
_ROPE_SCALING = {
ROPE_SCALING = {
"type": "yarn",
"factor": _ROPE_FACTOR,
"beta_fast": _ROPE_BETA_FAST,
"beta_slow": _ROPE_BETA_SLOW,
"original_max_position_embeddings": _ROPE_ORIGINAL_MAX_POSITION,
"factor": ROPE_FACTOR,
"beta_fast": ROPE_BETA_FAST,
"beta_slow": ROPE_BETA_SLOW,
"original_max_position_embeddings": ROPE_ORIGINAL_MAX_POSITION,
}
# The nested `main`/`compress` schema, which HF's own `DeepseekV4Config` and this repo's port both
# write and which vLLM's config shim cannot read. A config.json can also carry the flat legacy
# `rope_scaling` the real checkpoint ships, or no YaRN parameters at all; the nested scaled form
# is asserted here because it is the one the patch has the most normalization to do on.
_ROPE_NESTED_PLAIN = {"rope_type": "default", "partial_rotary_factor": 0.125}
_ROPE_PARAMETERS = {
"main": dict(_ROPE_NESTED_PLAIN),
"compress": {**_ROPE_SCALING, "partial_rotary_factor": 0.125},
ROPE_NESTED_PLAIN = {"rope_type": "default", "partial_rotary_factor": 0.125}
ROPE_PARAMETERS = {
"main": dict(ROPE_NESTED_PLAIN),
"compress": {**ROPE_SCALING, "partial_rotary_factor": 0.125},
}
@@ -498,12 +490,12 @@ def _reference_rope_freqs(original_seq_len: int, base: float) -> torch.Tensor:
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
return torch.clamp(linear_func, 0, 1)
dim = _ROPE_ROTARY_DIM
dim = ROPE_ROTARY_DIM
freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
if original_seq_len > 0:
low, high = find_correction_range(_ROPE_BETA_FAST, _ROPE_BETA_SLOW, dim, base, original_seq_len)
low, high = find_correction_range(ROPE_BETA_FAST, ROPE_BETA_SLOW, dim, base, original_seq_len)
smooth = 1 - linear_ramp_factor(low, high, dim // 2)
freqs = freqs / _ROPE_FACTOR * (1 - smooth) + freqs * smooth
freqs = freqs / ROPE_FACTOR * (1 - smooth) + freqs * smooth
return freqs
@@ -536,10 +528,10 @@ def vllm_rope_builder():
def build(compress_ratio: int):
config = VllmDeepseekV4Config(
rope_theta=_ROPE_THETA,
compress_rope_theta=_COMPRESS_ROPE_THETA,
max_position_embeddings=_ROPE_MAX_POSITION,
rope_parameters={key: dict(value) for key, value in _ROPE_PARAMETERS.items()},
rope_theta=ROPE_THETA,
compress_rope_theta=COMPRESS_ROPE_THETA,
max_position_embeddings=ROPE_MAX_POSITION,
rope_parameters={key: dict(value) for key, value in ROPE_PARAMETERS.items()},
)
patch_rope_parameters(config)
# Model init runs under the model dtype (`vllm/model_executor/model_loader/base_loader.py`),
@@ -547,9 +539,9 @@ def vllm_rope_builder():
with set_default_torch_dtype(torch.bfloat16), set_current_vllm_config(VllmConfig()):
return dsv4_rope.build_deepseek_v4_rope(
config,
head_dim=_ROPE_HEAD_DIM,
rope_head_dim=_ROPE_ROTARY_DIM,
max_position_embeddings=_ROPE_MAX_POSITION,
head_dim=ROPE_HEAD_DIM,
rope_head_dim=ROPE_ROTARY_DIM,
max_position_embeddings=ROPE_MAX_POSITION,
compress_ratio=compress_ratio,
)
@@ -571,10 +563,10 @@ def test_deepseek_v4_vllm_rope_matches_the_reference(vllm_rope_builder):
assert sliding.cos_sin_cache.dtype is torch.float32
assert compressed.cos_sin_cache.dtype is torch.float32
torch.testing.assert_close(_vllm_rope_freqs(sliding), _reference_rope_freqs(0, _ROPE_THETA), atol=1e-6, rtol=0)
torch.testing.assert_close(_vllm_rope_freqs(sliding), _reference_rope_freqs(0, ROPE_THETA), atol=1e-6, rtol=0)
torch.testing.assert_close(
_vllm_rope_freqs(compressed),
_reference_rope_freqs(_ROPE_ORIGINAL_MAX_POSITION, _COMPRESS_ROPE_THETA),
_reference_rope_freqs(ROPE_ORIGINAL_MAX_POSITION, COMPRESS_ROPE_THETA),
atol=1e-6,
rtol=0,
)
@@ -593,38 +585,37 @@ def test_deepseek_v4_vllm_rope_matches_the_reference(vllm_rope_builder):
# Neither length is a multiple of a compress rate, so both compressors have to drop a trailing
# partial window instead of pooling across the boundary.
_DOC_LENS = (14, 18)
DOC_LENS = (14, 18)
# The bf16 expert floor, which four hyper-connected layers amplify into every gradient. Measured
# worst case is 7.4e-3 against each tensor's own scale; treating the packed row as one long
# document instead of two moves the gradients 35x further than that.
_MODEL_GRAD_RTOL = 8e-2
# The bf16 expert floor, which four hyper-connected layers amplify into every gradient. A document
# reading its neighbour moves the gradients far past that floor.
MODEL_GRAD_RTOL = 1e-1
# The per-mechanism cases run in float32. `kv_proj` sees a different number of rows packed than
# alone and cuBLAS may tile the two differently, so they never match bit for bit, and in bfloat16
# that floor would swallow the cross-document leakage these tests exist to catch.
_PACKED_RTOL, _PACKED_ATOL = 1e-5, 1e-6
PACKED_RTOL, PACKED_ATOL = 1e-5, 1e-6
# Gradients are bounded against the tensor's own scale instead: they are sums over the whole row,
# so their near-zero entries are the ones whose summands cancelled, and an element-wise relative
# bound would read out that cancellation noise rather than a document leak.
_PACKED_GRAD_RTOL = 1e-5
PACKED_GRAD_RTOL = 1e-5
# One row folding together every length regime the per-document layout has to get right: 3
# compresses to nothing, 8 is a whole number of windows at both rates, and 13 ends mid-window at
# both. At both rates the per-document entry count lands below the row-global one, so neither
# case is vacuous.
_MIXED_DOCS = (3, 8, 13)
MIXED_DOCS = (3, 8, 13)
# The boundary falls inside a window of both rates, so both drop tokens at it.
_MID_WINDOW_DOCS = (7, 9)
MID_WINDOW_DOCS = (7, 9)
# Whole windows everywhere, so only the numbering, and with it the RoPE position, moves.
_EXACT_MULTIPLE_DOCS = (8, 8)
EXACT_MULTIPLE_DOCS = (8, 8)
def _packed_inputs(doc_lens: tuple[int, ...]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""One packed row: token ids, `position_ids` restarting per document, and flat `seq_lens`."""
total = sum(doc_lens)
input_ids = torch.randint(0, _MODEL["vocab_size"], (1, total), device="cuda")
input_ids = torch.randint(0, MODEL["vocab_size"], (1, total), device="cuda")
position_ids = torch.cat([torch.arange(length, device="cuda") for length in doc_lens]).unsqueeze(0)
return input_ids, position_ids, torch.tensor(doc_lens, device="cuda")
@@ -645,7 +636,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(MODULE_BATCH, seq_len, MODEL["hidden_size"])
return hidden.clone().requires_grad_(True), hidden.clone().requires_grad_(True)
@@ -657,7 +648,7 @@ def _take_grads(module: nn.Module) -> dict[str, torch.Tensor | None]:
def _compare_accumulated_grads(
module: nn.Module, expected: dict[str, torch.Tensor | None], rtol: float = _PACKED_GRAD_RTOL
module: nn.Module, expected: dict[str, torch.Tensor | None], rtol: float = PACKED_GRAD_RTOL
) -> None:
"""Compare the gradients now on `module` against a snapshot taken from an earlier backward.
@@ -692,16 +683,17 @@ def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypa
monkeypatch.setattr(dsv4_attention, "eager_attention_with_sinks", record)
# The dense mask is an eager-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)
input_ids, position_ids, seq_lens = _packed_inputs(DOC_LENS)
prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
assert len(recorded) == _MODEL["num_hidden_layers"]
total = sum(_DOC_LENS)
doc_ids = _doc_ids(_DOC_LENS)
assert len(recorded) == MODEL["num_hidden_layers"]
total = sum(DOC_LENS)
doc_ids = _doc_ids(DOC_LENS)
positions = position_ids[0]
distance = positions[:, None] - positions[None, :]
expected = (doc_ids[:, None] == doc_ids[None, :]) & (distance >= 0) & (distance < _MODEL["sliding_window"])
expected = (doc_ids[:, None] == doc_ids[None, :]) & (distance >= 0) & (distance < MODEL["sliding_window"])
for layer_idx, mask in enumerate(recorded):
# Compressed layers append their own entries as extra columns; those are covered
# separately, so only the local window is compared here.
@@ -709,7 +701,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"
def test_deepseek_v4(_torch_rms_norm): # noqa: F811
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.
End to end over every pathway at once: the local sliding window, the CSA compressor with its
@@ -722,7 +714,7 @@ def test_deepseek_v4(_torch_rms_norm): # noqa: F811
covers the assembled stack.
"""
prime_model = get_prime_model(torch.float32)
input_ids, position_ids, seq_lens = _packed_inputs(_DOC_LENS)
input_ids, position_ids, seq_lens = _packed_inputs(DOC_LENS)
packed = prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)["logits"]
# One random weight drawn over the packed logits and sliced per document, so the packed loss
@@ -732,22 +724,21 @@ def test_deepseek_v4(_torch_rms_norm): # noqa: F811
(packed * weight).sum().backward()
packed_grads = _take_grads(prime_model)
for index, length in enumerate(_DOC_LENS):
span = _doc_slice(_DOC_LENS, index)
for index, length in enumerate(DOC_LENS):
span = _doc_slice(DOC_LENS, index)
alone = prime_model(
input_ids[:, span],
position_ids=torch.arange(length, device="cuda").unsqueeze(0),
seq_lens=torch.tensor([length], device="cuda"),
)["logits"]
# `GroupedExperts` runs the routed experts through `torch._grouped_mm` in bfloat16
# whatever dtype the model runs in, and packing changes which tokens share an expert
# matmul, so the two runs agree only to the bf16 floor. Worst relative deviation
# measured over six seeds is 1.2e-3; a document actually reading its neighbour moves
# the logits by a fraction of their own scale, orders of magnitude above this.
# `GroupedExperts` runs the routed experts through `torch._grouped_mm` in bfloat16 whatever
# dtype the model runs in, and packing changes which tokens share an expert matmul, so the two
# runs agree only to the bf16 floor. A document actually reading its neighbour moves the logits
# by a fraction of their own scale, orders of magnitude above this.
_assert_relative(packed[:, span], alone, 1e-2, f"document {index}")
(alone * weight[:, span]).sum().backward()
_compare_accumulated_grads(prime_model, packed_grads, rtol=_MODEL_GRAD_RTOL)
_compare_accumulated_grads(prime_model, packed_grads, rtol=MODEL_GRAD_RTOL)
def _assert_layout_is_consistent(packed: PackedContext, doc_lens: tuple[int, ...], compress_rate: int) -> None:
@@ -781,7 +772,7 @@ def _assert_layout_is_consistent(packed: PackedContext, doc_lens: tuple[int, ...
@pytest.mark.parametrize(
("layer_idx", "compress_rate", "expected_counts"),
[(_CSA_LAYER, _COMPRESS_RATE, [0, 2, 3]), (_HCA_LAYER, _HCA_COMPRESS_RATE, [0, 1, 1])],
[(CSA_LAYER, COMPRESS_RATE, [0, 2, 3]), (HCA_LAYER, HCA_COMPRESS_RATE, [0, 1, 1])],
ids=["csa", "hca"],
)
def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expected_counts):
@@ -794,11 +785,11 @@ def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expect
document, so the packed loss and the summed per-document losses are literally the same
function of the same numbers.
`_MIXED_DOCS` folds every length regime that matters into one row; see its definition.
`MIXED_DOCS` folds every length regime that matters into one row; see its definition.
"""
module = prime_attention(layer_idx, dtype=torch.float32)
compressor = module.compressor
doc_lens = _MIXED_DOCS
doc_lens = MIXED_DOCS
packed = _packed_context(doc_lens, torch.float32)
counts = _entry_counts(doc_lens, compress_rate)
@@ -813,7 +804,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 == (MODULE_BATCH, sum(counts), compressor.head_dim)
with torch.device("cuda"):
weight = torch.randn_like(packed_entries)
@@ -826,26 +817,30 @@ 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), (
assert alone.shape == (MODULE_BATCH, count, compressor.head_dim), (
f"document {index} compressed to the wrong count"
)
torch.testing.assert_close(
packed_entries[:, entries],
alone,
rtol=_PACKED_RTOL,
atol=_PACKED_ATOL,
rtol=PACKED_RTOL,
atol=PACKED_ATOL,
msg=lambda m, i=index: f"document {i} compresses differently packed than alone: {m}",
)
(alone * weight[:, entries]).sum().backward()
_compare_accumulated_grads(compressor, packed_grads)
torch.testing.assert_close(alone_input.grad, packed_input.grad, rtol=_PACKED_RTOL, atol=_PACKED_ATOL)
torch.testing.assert_close(alone_input.grad, packed_input.grad, rtol=PACKED_RTOL, atol=PACKED_ATOL)
@pytest.mark.parametrize(
("layer_idx", "doc_lens"),
[(_CSA_LAYER, _MID_WINDOW_DOCS), (_HCA_LAYER, _EXACT_MULTIPLE_DOCS)],
ids=["csa", "hca"],
[
(CSA_LAYER, MID_WINDOW_DOCS),
(HCA_LAYER, EXACT_MULTIPLE_DOCS),
(SLIDING_LAYER, MID_WINDOW_DOCS),
],
ids=["csa", "hca", "sliding"],
)
def test_attention_packed_matches_unpacked(layer_idx, doc_lens, _torch_rms_norm): # noqa: F811
"""The same invariant, one whole attention layer at a time rather than one compressor.
@@ -857,16 +852,30 @@ def test_attention_packed_matches_unpacked(layer_idx, doc_lens, _torch_rms_norm)
Sharper than `test_deepseek_v4`, which asserts the same property through the logits at a bf16
floor: this runs in float32 and compares the layer's own output, forward and backward.
A sliding layer has no compressor and so no entry selection at all; it reads nothing but its
own clipped window, which makes it the case where the boundary handling stands alone.
"""
# The kernel's own packing invariant is asserted at the Flash shapes in
# `test_deepseek_v4_kernels.py`.
module = prime_attention(layer_idx, dtype=torch.float32)
packed_input, alone_input = _fp32_hidden_states(sum(doc_lens))
packed = _packed_context(doc_lens, torch.float32)
q_residual = module.q_a_norm(module.q_a_proj(packed_input.detach()))
_, block_bias = module.compressor(packed_input.detach(), q_residual, packed)
assert (block_bias[:, :, _doc_slice(doc_lens, 1)] == 0).any(), (
"vacuous probe: no query of the second document reads a compressed entry"
)
if module.compressor is None:
# The second document opens inside a window, so an unclipped one would reach back into
# the first. Without that the comparison below would hold under no clipping at all.
readable = packed.window_indices[doc_lens[0]] >= 0
assert readable.sum() < module.config.sliding_window, (
"vacuous probe: the second document's first query is not window-clipped at the boundary"
)
else:
q_residual = module.q_a_norm(module.q_a_proj(packed_input.detach()))
_, picks = module.compressor(packed_input.detach(), q_residual, packed)
# (batch, seq_len, n_picks), with `IGNORE_SLOT` (-1) where the query had no entry left to pick.
assert (picks[:, _doc_slice(doc_lens, 1)] >= 0).any(), (
"vacuous probe: no query of the second document picks a compressed entry"
)
packed_output, _ = module(packed_input, packed=packed)
with torch.device("cuda"):
@@ -880,11 +889,11 @@ def test_attention_packed_matches_unpacked(layer_idx, doc_lens, _torch_rms_norm)
torch.testing.assert_close(
packed_output[:, span],
alone_output,
rtol=_PACKED_RTOL,
atol=_PACKED_ATOL,
rtol=PACKED_RTOL,
atol=PACKED_ATOL,
msg=lambda m, i=index: f"document {i} attends differently packed than alone: {m}",
)
(alone_output * weight[:, span]).sum().backward()
_compare_accumulated_grads(module, packed_grads)
torch.testing.assert_close(alone_input.grad, packed_input.grad, rtol=_PACKED_RTOL, atol=_PACKED_ATOL)
torch.testing.assert_close(alone_input.grad, packed_input.grad, rtol=PACKED_RTOL, atol=PACKED_ATOL)
@@ -1,10 +1,3 @@
"""DeepSeek V4 checks that need no GPU, kept out of the `gpu`-marked whole-model module.
The dequantization math is a pure function over hand-built tensors, and the config checks only
ever construct a `DeepseekV4Config`. Neither needs CUDA, and a module-level `pytest.mark.gpu`
cannot be undone per test, so they live here and run in the CPU job.
"""
import torch
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config
File diff suppressed because it is too large Load Diff
+109
View File
@@ -0,0 +1,109 @@
import copy
import pytest
import torch
from torch import nn
from prime_rl.trainer.models.fusions import apply_model_fusions, get_model_packed_parameters
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
from prime_rl.trainer.models.layers.moe import GroupedExperts
NUM_EXPERTS, DIM, HIDDEN = 4, 16, 24
NUM_HEADS, NUM_KV_HEADS, HEAD_DIM = 4, 2, 8
def build_experts(expert_type="gated"):
experts = GroupedExperts(dim=DIM, hidden_dim=HIDDEN, num_experts=NUM_EXPERTS, expert_type=expert_type)
for parameter in experts.parameters():
nn.init.normal_(parameter)
return experts
def build_attention(attention_bias=True):
config = AttentionConfig(
hidden_size=DIM,
head_dim=HEAD_DIM,
num_attention_heads=NUM_HEADS,
num_key_value_heads=NUM_KV_HEADS,
is_causal=True,
attention_bias=attention_bias,
use_qk_norm=False,
rms_norm_eps=1e-6,
)
attention = FlashAttention(config)
for parameter in attention.parameters():
nn.init.normal_(parameter)
return attention
def assert_state_dict_stays_canonical(unfused, fusion):
"""Packing a module must not change what its state dict contains, or how it loads."""
fused = copy.deepcopy(unfused)
apply_model_fusions(fused, [fusion])
expected = unfused.state_dict()
assert set(fused.state_dict()) == set(expected)
for name, tensor in expected.items():
assert torch.equal(fused.state_dict()[name], tensor), name
reloaded = copy.deepcopy(unfused)
apply_model_fusions(reloaded, [fusion])
reloaded.load_state_dict(expected)
for packed_info, reloaded_info in zip(get_model_packed_parameters(fused), get_model_packed_parameters(reloaded)):
assert torch.equal(reloaded_info.parameter, packed_info.parameter), packed_info.fqn
return fused
def test_gate_up_packs_the_output_dimension():
fused = assert_state_dict_stays_canonical(build_experts(), "gate_up")
(packed_info,) = get_model_packed_parameters(fused)
assert packed_info.fqn == "gate_up_proj"
assert packed_info.logical_fqns == ("gate_proj", "up_proj")
assert packed_info.parameter.shape == (NUM_EXPERTS, 2 * HIDDEN, DIM)
assert packed_info.spec.muon_matrix_partitions(packed_info.parameter) == (HIDDEN, HIDDEN)
assert fused.gate_proj is None and fused.up_proj is None
def test_qkv_packs_weights_and_biases():
fused = assert_state_dict_stays_canonical(build_attention(), "qkv")
weight, bias = get_model_packed_parameters(fused)
query_size, key_size = NUM_HEADS * HEAD_DIM, NUM_KV_HEADS * HEAD_DIM
assert weight.fqn == "qkv_proj.weight"
assert weight.logical_fqns == ("q_proj.weight", "k_proj.weight", "v_proj.weight")
assert weight.parameter.shape == (query_size + 2 * key_size, DIM)
assert weight.spec.muon_matrix_partitions(weight.parameter) == (query_size, key_size, key_size)
assert bias.fqn == "qkv_proj.bias"
assert bias.logical_fqns == ("q_proj.bias", "k_proj.bias", "v_proj.bias")
# A one-dimensional parameter has no output dimension to partition
assert bias.spec.muon_matrix_partitions(bias.parameter) is None
def test_qkv_without_bias_packs_only_weights():
fused = assert_state_dict_stays_canonical(build_attention(attention_bias=False), "qkv")
assert [packed_info.fqn for packed_info in get_model_packed_parameters(fused)] == ["qkv_proj.weight"]
def test_qkv_projections_match_the_unpacked_ones():
unfused = build_attention()
fused = copy.deepcopy(unfused)
apply_model_fusions(fused, ["qkv"])
hidden_states = torch.randn(1, 8, DIM)
for fused_projection, unfused_projection in zip(
fused.project_qkv(hidden_states), unfused.project_qkv(hidden_states)
):
assert torch.equal(fused_projection, unfused_projection)
def test_unsupported_fusion_fails_loudly():
with pytest.raises(ValueError, match="does not support"):
apply_model_fusions(build_experts(), ["qkv"])
assert apply_model_fusions(build_experts(), ["qkv"], raise_on_fail=False) == {}
def test_non_gated_experts_have_nothing_to_pack():
with pytest.raises(ValueError, match="does not support"):
apply_model_fusions(build_experts(expert_type="non_gated"), ["gate_up"])
+44
View File
@@ -0,0 +1,44 @@
import pytest
import torch
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4ForCausalLM
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
def test_resolve_wire_dtype():
def keep_in_fp32(key: str) -> bool:
return key.endswith("A_log")
assert resolve_wire_dtype(keep_in_fp32, "layers.0.linear_attn.A_log", torch.bfloat16) is torch.float32
assert resolve_wire_dtype(keep_in_fp32, "layers.0.self_attn.q_proj.weight", torch.bfloat16) is torch.bfloat16
# The default is whatever the transport asked for, not hardcoded bf16.
assert resolve_wire_dtype(keep_in_fp32, "layers.0.self_attn.q_proj.weight", torch.float8_e4m3fn) is (
torch.float8_e4m3fn
)
# A plain transformers model declares nothing, so every key takes the default.
assert resolve_wire_dtype(None, "layers.0.linear_attn.A_log", torch.bfloat16) is torch.bfloat16
@pytest.mark.parametrize(
("model_cls", "fp32_key", "ordinary_key"),
[
(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"),
(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"),
],
)
def test_declared_keys_travel_in_fp32(model_cls, fp32_key, ordinary_key):
keep_in_fp32 = model_cls.keep_in_fp32_for_weight_transfer
assert resolve_wire_dtype(keep_in_fp32, fp32_key, torch.bfloat16) is torch.float32
assert resolve_wire_dtype(keep_in_fp32, ordinary_key, torch.bfloat16) is torch.bfloat16
Generated
+2 -2
View File
@@ -1433,7 +1433,7 @@ wheels = [
[[package]]
name = "dion"
version = "0.1.0"
source = { git = "https://github.com/samsja/dion.git?rev=d891eeb#d891eebbd950a6ff11d9b5f806282e33df83df9d" }
source = { git = "https://github.com/samsja/dion.git?rev=99e5f7e#99e5f7e5f0a7dbe418ce6dfc84196dba052e67c8" }
dependencies = [
{ name = "numpy" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
@@ -5092,7 +5092,7 @@ requires-dist = [
{ name = "deep-gemm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" },
{ name = "deep-gemm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" },
{ name = "dion", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
{ name = "dion", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/samsja/dion.git?rev=99e5f7e" },
{ name = "fastapi", marker = "extra == 'dashboard'", specifier = ">=0.115" },
{ name = "flash-attn", marker = "platform_machine == 'aarch64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl" },
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl" },