Skip to content

Add FSDP2 and Ulysses context parallel for Qwen3.5 GatedDeltaNet - #12052

Closed
MegaGimen wants to merge 16 commits into
unslothai:mainfrom
MegaGimen:qwen35-gdn-cp
Closed

MegaGimen wants to merge 16 commits into
unslothai:mainfrom
MegaGimen:qwen35-gdn-cp

Conversation

@MegaGimen

@MegaGimen MegaGimen commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Related issue: #12051
Fixes #315

Unsloth does not support context parallel for Qwen3.5 GatedDeltaNet, and it does not shard that hybrid model with FSDP2.

The conv and the gated delta rule need the full timeline, so a sequence shard cannot stay a sequence shard inside those layers. Full attention can be sharded by heads. One 96GB GPU runs out of memory on the first LoRA step at sequence 32768.

This PR adds unsloth/distributed:

  • apply_fsdp wraps each Qwen3.5 decoder layer with torch.distributed.fsdp.fully_shard.
  • apply_cp all-to-alls full attention across heads (Ulysses) and does the same for GatedDeltaNet, including a, b, the conv weights and A_log.
  • After the all-to-all, full attention runs SDPA. A dense monotonic sequence still uses is_causal. A 2D padding mask, or a position_ids reset that starts a packed segment, blocks keys outside that segment.

Qwen3.5-35B-A3B, LoRA rank 16, 2× RTX PRO 6000, one epoch of two optimizer steps.

Sequence 32768:

Mode Weights after load Epoch Peak Two steps
Original Unsloth (1 GPU) 65.5 GiB OOM on the first forward 94.2 GiB did not finish
FSDP only 34.1 GiB finished 71.2 GiB 52.4 s, then 22.3 s
Context parallel only 65.5 GiB finished 83.7 GiB 28.2 s, then 5.4 s
FSDP + context parallel 34.1 GiB finished 52.2 GiB 24.7 s, then 9.3 s

Sequence 65536:

Mode Weights after load Epoch Peak Two steps
Original Unsloth (1 GPU) 65.5 GiB OOM on the first forward 94.1 GiB did not finish
FSDP only 34.1 GiB OOM on the first forward 94.2 GiB did not finish
Context parallel only 65.5 GiB OOM on the first forward 93.2 GiB did not finish
FSDP + context parallel 34.1 GiB finished 70.2 GiB 52.4 s, then 15.1 s

This is not wired into FastLanguageModel.from_pretrained as a flag. Call apply_fsdp / apply_cp after LoRA.

Test plan

  • PYTHONPATH=. python test_cp_mask.py — a packed segment’s loss produces 0 gradient on the other segment’s values
  • 2-GPU LoRA step at sequence 128, seed 3407, checkpointing off, compared with the single-GPU step

A sequence shard cannot run the recurrent conv and gated delta rule, and one GPU runs out of memory on a long LoRA step.
…tributed

- sync_replicated_grads: average instead of sum (all_gather backward already
  sums each rank's loss), skip FSDP DTensor grads that crashed FSDP+CP.
- GDN CP: use the kernels bound for this model's module (FLA chunk when
  installed), torch conv fallback when causal_conv1d_fn is None (<= 5.5).
- sft_loss: right-pad to a multiple of cp instead of dropping tail tokens.
- local_rank reads LOCAL_RANK; apply_fsdp_checkpoint covers dense Qwen3.5.
- Move test_cp_mask.py to tests/test_context_parallel.py with a CPU gloo
  2-rank vs 1-process loss/grad parity check.
@MegaGimen

Copy link
Copy Markdown
Contributor Author

Thanks for that. Is there anything else you'd like me to change before this can land? @danielhanchen

@MegaGimen

Copy link
Copy Markdown
Contributor Author

I'm working on CP for more models like DeepSeek, Kimi and Gemma

@MegaGimen

Copy link
Copy Markdown
Contributor Author

MiniMax's model is too large to test on the GPU I rent and there's no distilled small version so I decide to extract certain layers that contain the attention operator or anything specific to MiniMax for validation

Backup Bot and others added 9 commits October 24, 2026 02:15
… matrix

The CP path built a dense [B, H/cp, S, S + n_blocks] score matrix and S x S mask per
layer, so activation memory grew quadratically with sequence length. Compute the
sink-softmax attention in query chunks (UNSLOTH_CP_ATTN_CHUNK, default 1024) and
recompute each chunk in backward with checkpoint. Math is unchanged. Not yet
validated on GPU.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
- KDA gate: add the gate_lower_bound form (lower_bound * sigmoid(exp(A_log) * (f_g + dt_bias)))
  matching fla's naive_kda_lowerbound_gate.
- patch_kimi_model: leave K3's own trainable KimiSparseMoeBlock / KimiMoEGate alone
  (latent experts would otherwise be dropped by the Kimi-Linear replacement).
- loader: recognise model_type kimi_k3.
- tests: add _tiny_kimi_k3 (full-rank gate, lower bound, q_lora + output-gated MLA, latent MoE)
  and stop importing the top-level unsloth package, which needs a GPU. Not yet run.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The indexer runs before the attention interface on the local shard, so Ulysses alone
would score only local keys. Dedicated DeepseekV32Attention forward under CP:
gather the (128-d) indexer keys, compute top-k per local query in chunks against the
full sequence, gather the indices, Ulysses-scatter q/k/v by head, and run a
query-chunked causal attention restricted to the selected keys. Adds _tiny_deepseek_v32
(index_topk < seq). Not yet run: the no-GPU container cannot hold the test processes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The official moonshotai/Kimi-K3 modeling has no moe_train: KimiSparseMoeBlock raises in
training mode and KimiMoEGate asserts not self.training, so patch_kimi_model's replacement
forward runs. It ignored latent MoE, silently dropping routed_expert_down_proj /
routed_expert_norm / routed_expert_up_proj. Apply them in _kimi_sparse_moe_forward and make
_kimi_moe_gate_forward mirror the official group-limited routing (-inf fill, only when
num_expert_group > topk_group). The K3 test mock now exercises the patched latent path.
Found by the torchtitan session; CPU CP tests pass (K3, Kimi-Linear, V3.2, V4, Gemma4 k_eq_v).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Kimi K3 loads as KimiK3ForConditionalGeneration, whose backbone and lm_head live under
language_model, so base.model raised AttributeError in every align / bench mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every rank loads the full model before fully_shard. For Kimi-Linear-48B (92 GB) the freed
half stayed in PyTorch's caching allocator, and NCCL, which allocates outside it, failed
with "Cuda failure 2 'out of memory'" in fsdp_cp even at 8K. With empty_cache() the
model now trains with CP at 16K (56.9 GiB/GPU) and 32K (60.2 GiB/GPU); single card OOMs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
unsloth/distributed/align_sft.py: one-step LoRA gradient alignment (vanilla / fsdp / cp /
fsdp_cp / compare), --dtype fp32 to separate CP bugs from bf16 rounding, trust_remote_code
for Kimi and Kimi K3.
unsloth/distributed/bench_sft.py: long-sequence peak memory and step time per mode.
scripts/context_parallel/: reproduce_all.sh (download / cpu / align / bench), run_align.sh,
run_bench.sh, run_cpu_tests.py (2-rank gloo vs 1 process), cp_layer_diff.py (per-layer
hidden-state diff, unsloth or plain transformers, bf16 or fp32), make_pad_overlay.py
(DeepSeek-V2-Lite pad token), download_models.py and extract_nonexpert.py (ModelScope).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
align_sft / bench_sft now require --model and --out-dir / --out; download_models.py,
run_align.sh, run_bench.sh and reproduce_all.sh require MODELS_DIR / OUT_DIR / WORK_DIR
and fail fast when they are unset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@MegaGimen

Copy link
Copy Markdown
Contributor Author

Update: CP for DeepSeek / MiniMax / Gemma 4 / Kimi, validated on full checkpoints

This push extends the FSDP2 + Ulysses context-parallel path beyond Qwen3.5 GatedDeltaNet.

What's new

  • DeepSeek: MLA (V2/V3) via Ulysses; V3.2 MLA + DSA indexer (indexer keys all-gathered, top-k computed per query chunk against the full sequence, sparse attention after the head scatter); V4 sliding / CSA / HCA sink attention, now query-chunked (UNSLOTH_CP_ATTN_CHUNK, default 1024) so the score matrix is [H/cp, chunk, S] instead of [H/cp, S, S].
  • MiniMax: M1 Lightning (linear) attention + full attention; M2.
  • Gemma 4: sliding/global attention, KV sharing, PLE, softcapping, attention_k_eq_v, MoE (26B-A4B).
  • Kimi: Kimi-Linear (KDA + MLA + MoE) and Kimi K3 (full-rank gate, gate_lower_bound, output-gated MLA, AttnRes, latent MoE).

Validation

Hardware: 2× RTX PRO 6000 Blackwell (96 GB, PCIe, SYS topology), torch 2.13 + cu130, transformers 5.15.1. All GPU runs are LoRA r=16.

  1. CPU (gloo): 2 ranks vs 1 process on tiny random models, every parameter's gradient within rtol=1e-4, atol=1e-5 (V2, V3.2, V4, MiniMax M1/M2, Gemma 4 incl. a 26B-A4B-shaped k_eq_v + MoE config, Kimi-Linear, K3). V4 / V3.2 are also run with chunk size 4 to exercise the chunked path.
  2. Gradient alignment on full checkpoints (one step, seq 256, cosine of the flattened LoRA gradients vs single-GPU vanilla):
Model cp fsdp_cp
DeepSeek-V2-Lite 1.0000 1.0000
Moonlight-16B-A3B (DeepSeek-V3 MLA) 0.9989 0.9989
Kimi-Linear-48B-A3B 0.9949 0.9977
Kimi-K3-0.40B 0.9944 0.9973
Gemma-4-26B-A4B 0.983 0.983 (fsdp alone: 0.993)
Gemma-4-31B 0.981 0.981
Gemma-4-E4B bf16: 0.16; fp32: loss diff 3.8e-6, cos 1.000 —

Gemma-4-E4B's low bf16 cosine is rounding, not CP: a per-layer hidden-state diff gives ~3e-6 relative error over all 42 layers in fp32, and plain transformers (without unsloth) shows the same bf16 drift.

  1. Long sequences on full checkpoints (peak GiB / step-2 seconds, 16K):
Model 1 GPU FSDP CP FSDP+CP
Kimi-K3-0.40B 54.5 / 0.56 34.1 / 0.75 11.2 / 0.22 6.2 / 0.33
DeepSeek-V2-Lite 36.8 / 8.42 23.7 / 9.69 33.6 / 3.27 19.4 / 4.43
Moonlight-16B 41.0 / 8.56 27.9 / 9.71 36.0 / 3.22 21.7 / 4.52
Gemma-4-E4B 51.8 / 3.86 48.0 / 3.92 33.3 / 3.25 29.5 / 3.93
Gemma-4-26B-A4B 82.2 / 5.57 63.5 / 9.14 66.0 / 4.27 45.6 / 6.22
Gemma-4-31B 94.0 / 21.0 76.0 / 23.2 80.4 / 14.6 54.3 / 16.5
Kimi-Linear-48B OOM 60.5 / 22.7 does not fit 56.9 / 16.1

At 32K, single GPU and FSDP-only both OOM on K3-0.40B, Gemma-4-26B-A4B and Gemma-4-31B, while CP trains them (Gemma-4-31B only with FSDP+CP, 75.7 GiB). CP alone is 2.5-2.7× faster than one GPU on K3 / V2-Lite / Moonlight at 16K (~3.2× at 32K). On DeepSeek-V4-Lite-4L at 16K, the query-chunked attention cuts fsdp_cp peak from 22.1 to 8.6 GiB (1 GPU: 84.2 GiB).

Bugs fixed along the way

  • Kimi K3: the official modeling has no trainable MoE, and the Kimi-Linear MoE replacement silently dropped the latent-MoE projections.
  • sft_loss: multimodal shells (K3) keep the text backbone under language_model.
  • apply_fsdp: every rank loads the full model before sharding; without torch.cuda.empty_cache() NCCL failed with Cuda failure 2 'out of memory' on Kimi-Linear-48B even at 8K.

Known limitations

  • Only LoRA was measured on GPU; full fine-tuning gradients were checked only on the CPU tiny models.
  • DeepSeek-V3.2 and the official-K3 paths (gate_lower_bound, Kimi-Linear MoE replacement) are covered by CPU tests only; no real V3.2 checkpoint fits.
  • DeepSeek-V4 and MiniMax were validated on reduced models (V4: 4 random layers; M1: 4-layer real slice); their configs differ from the released ones in some ratios (e.g. V4 HCA rate 8 vs 128).
  • Gemma 4 gets the memory benefit but only 1.2-1.45× speed with CP alone. Likely cause: FSDP all-gathers and Ulysses all-to-alls cross the inter-socket link on this box while Gemma's mostly sliding-window attention is cheap; not yet profiled.
  • apply_fsdp uses a bf16 MixedPrecisionPolicy, so fsdp modes cannot run in fp32.

Reproduce

MODELS_DIR=<checkpoints> WORK_DIR=<outputs> PYTHON=<python> TORCHRUN=<torchrun> \
  bash scripts/context_parallel/reproduce_all.sh [download] [cpu] [align] [bench]

MODELS_DIR and WORK_DIR are required (no machine-specific defaults). download fetches the eight checkpoints from ModelScope (~290 GB); the default steps are cpu align bench. The individual pieces (run_align.sh, run_bench.sh, run_cpu_tests.py, cp_layer_diff.py) can also be run on their own.

@MegaGimen

Copy link
Copy Markdown
Contributor Author

Hi @danielhanchen, I noticed that #13848, #13920 and #13910 were merged last week and that #12051 was closed as implemented by them. Congrats on landing context parallelism.

I'd like to ask about this PR, since nobody has commented on it so far:

I understand that maintainers sometimes prefer to re-implement a feature inside their own design, and the trainer-integrated version with packing support is a good result. I'm not asking for this PR to be merged as it is. I would appreciate two things:

  1. A short note on how you'd like to handle this PR: close it, or keep part of it.
  2. Some acknowledgement of the earlier work, for example a reference from Context parallel: Ulysses for Gated DeltaNet hybrids (Qwen3.5, Qwen3-Next) #13920 or a co-author/credit line in the release notes.

Separately, I've continued the work for architectures that unsloth/context_parallel.py currently refuses, validated on full checkpoints on 2× RTX PRO 6000 (details in my previous comment):

  • Kimi-Linear and Kimi K3 (KDA linear attention, gated MLA, AttnRes, latent MoE)
  • MiniMax M1 Lightning attention and M2
  • DeepSeek MLA (non-default attention scale), V3.2 DSA indexer, V4 CSA/HCA sink attention
  • Gemma 4 (sliding window, softcapping, KV sharing, attention_k_eq_v, MoE)

If you're interested, I'm happy to port these onto the new unsloth/context_parallel.py / Ulysses framework as separate, smaller PRs, one per model family, with the tests and validation scripts. Please let me know which you'd prefer, or whether there's a different direction you have in mind.

Thanks!

@MegaGimen

Copy link
Copy Markdown
Contributor Author

I've decided to split each model into separate PRs.

@MegaGimen

Copy link
Copy Markdown
Contributor Author

I've adapted my code for different models with your style in your merged PR

danielhanchen added a commit that referenced this pull request Nov 8, 2026
…inear MoE gate backward (#15880)

## Summary

This is the first of four per-family PRs that split up #12052, as I said
there. All four are written against the framework in
`unsloth/context_parallel.py` / `unsloth/utils/ulysses_hybrid.py` from
#13848 / #13920. **Scope: Ulysses only.** Ring is still refused for
these models. Sequence-sharded CP for linear-attention layers (passing
recurrent state between ranks) would be a separate follow-up.

- **KDA under Ulysses.** Each `KimiDeltaAttention` projects on its
sequence shard. One all-to-all moves q, k, v, the forget-gate input and
beta to head shards. Each rank then runs the q/k/v short convs (with its
slice of the conv weights), the KDA gate (its `A_log` / `dt_bias` slice,
including Kimi K3's `gate_lower_bound` form) and the delta rule over the
full sequence. A second all-to-all returns the output before the gated
norm. This is the same scheme as #13920's Gated DeltaNet path; KDA
differs mainly in the per-channel decay, so the gate input is `H × d_k`
wide instead of `H`.
- **MLA full attention** goes through the existing Ulysses attention
exchange. Value heads narrower than query heads are padded and then
sliced, the same way Hugging Face's flash path does it.
- **Remote MoE under CP.** While CP is active, the train-mode remote MoE
dispatch runs unrouted experts on zero tokens. That way every expert
gets a (zero) gradient on every rank; otherwise DDP stalls on parameters
that were unused locally. Such shimmed blocks are no longer refused as
per-expert MoE.
- Packing with KDA under CP is refused.

### Bug fix that also affects training without CP

Kimi-Linear's remote gate (`KimiMoEGate`, in the official
`modeling_kimi.py`) does

```python
scores_for_choice = scores.view(bsz * seq_len, -1)
scores_for_choice += self.e_score_correction_bias.unsqueeze(0)   # in place on the sigmoid output
```

The sigmoid's backward saved `scores`, so **any LoRA step on Kimi-Linear
fails in backward** with `one of the variables needed for gradient
computation has been modified by an inplace operation`. This happens
with or without CP. The gate was also never shimmed, because only
DeepSeek's `MoEGate` name was matched. Now:

- The gate of an inference-only remote MoE block is shimmed even when
the port renames it (requires remote code, so a shared class such as
`nn.Linear` is never patched).
- The gate shim wraps the forward in `saved_tensors_hooks` that save
copies. Routing is unchanged, and this is a no-op without grad. It works
under both reentrant and non-reentrant checkpointing.

## Validation (this branch)

Setup: 2× RTX PRO 6000 (96 GB, PCIe), torch 2.13, transformers 5.15.1,
unsloth_zoo 2026.10.8. A model-level check compares the full-sequence
forward / backward of one rank against `ContextParallelManager`
(`attach_attention_hooks` + `_prepare_inputs` + `apply`, `shift_labels`,
`num_items_in_batch`) on 2 ranks. Gradients are LoRA r=16 with `lora_B ~
N(0, 1e-3)` so that A gradients are non-zero, all-reduced and compared
per parameter.

| check | reference | CP=2 |
|---|---|---|
| Kimi-Linear-48B-A3B, layers sliced to 4 (real weights), fp32, 4096
tok, loss | 14.298470 | 14.298473 |
| same, LoRA grad norm (52 tensors) | 1.1929 | 1.1929 (max per-tensor
rel 2.4e-3) |
| Kimi-Linear-48B-A3B full, bf16, loss | 14.3218 | 14.3255 |

The 2e-3 per-tensor floor comes from fla's Triton kernels using TF32 for
fp32 inputs, so it is not specific to CP. Models without fla kernels
(MiniMax-M2, Gemma 4 in the later PRs) match to about 1e-6.

CPU tests (gloo, 2 ranks): CP=2 vs CP=1 gradients for Kimi-Linear and K3
stand-in layers, a shard-local negative control (fails as expected),
gates, packing / cache refusal, the gate formula, MoE zero gradients,
MLA value padding, and the in-place gate backward (fails without the
fix). `tests/test_remote_moe_shims.py`,
`test_k3_mxfp4_stacked_experts.py`, `test_ulysses_*.py` and
`test_context_parallel.py` pass (166 passed).

## Further validation plan

The earlier implementation of the same algorithm in #12052 was validated
on full checkpoints
([details](#12052 (comment))).
LoRA gradient cosine vs single GPU was 0.9949 (CP) / 0.9977 (FSDP+CP) on
Kimi-Linear-48B-A3B and 0.9944 / 0.9973 on Kimi-K3-0.40B. At 16K,
K3-0.40B went from 54.5 GiB / 0.56 s on one GPU to 11.2 GiB / 0.22 s
with CP, and Kimi-Linear-48B did not fit on one GPU but trained with
FSDP+CP (56.9 GiB). For this port I plan to:

1. Rerun those full-checkpoint checks through
`SFTTrainer(context_parallel_size = 2)`: Kimi-Linear-48B-A3B with FSDP2
+ CP, and Kimi-K3-0.40B (the ported K3 path is so far covered only by
CPU stand-in layers).
2. Measure the longest sequence that trains on one GPU vs CP=2 /
FSDP2+CP=2, which is the main point of CP. The fixed-16K comparison does
not show this.
3. Run with flash-attn installed, which is the configuration users will
hit (see limits).

## Known limits

- The Kimi remote classes do not declare `_supports_sdpa`, so Ulysses
(which refuses eager) needs flash-attn here. My GPU check overrode the
flag in the harness only.
- In this environment fla's TileLang backend failed to JIT-compile the
fp32 KDA backward, so the fp32 check ran with
`FLA_DISABLE_BACKEND_DISPATCH=1` (Triton kernels). bf16 does not need
this.

Related: #12052, #13920.


## Follow-up (rebased onto current main)

Merged current main into this branch and reworked it on top of what main
now has:

- **MLA** goes through main's generic Ulysses attention route; this
branch's own value-head padding and scale plumbing is dropped. The KDA
wrappers and the gate fix are kept.
- **Capability registry:** `kimi_linear` MoE x CP cells (full, LoRA,
LoRA on experts, router aux loss off), each backed by gloo parity tests.
Unsloth gradient checkpointing, FSDP2 x CP and QLoRA stay unverified.
- **CPU KDA fallback** l2-normalises q / k as fla's in-kernel norm does
(`x * rsqrt(sum(x ** 2) + 1e-6)`), not `F.normalize`.
- **Idle experts and AdamW.** Under CP every expert runs (possibly on no
tokens) so DDP sees a gradient for each; a step pre-hook then drops the
gradient of experts no rank routed a token to, as one process leaves
them `None`. Fixed three gaps in that bookkeeping:
- tokens CP appends so the length divides the CP size no longer count as
expert usage;
- a step GradScaler skips no longer leaks its counts into the next
window, and a reused optimizer outside CP is left alone;
- right padding from the caller: pad rows now get the single-process
activations under CP (KDA output zeroed past each row's real length;
attention pad rows rebuilt as the masked forward does, without
materialising a pad x real mask), so they route to the same experts.

### Validation

CPU gloo against one process, with the real hub `modeling_kimi.py`
(fla's naive reference kernels in fp64) as an independent oracle:

| check | result |
|---|---|
| CP2 / CP4, dense and MoE, full / LoRA / LoRA on experts, seam
crossing, right padding | loss and every gradient match (fp64 internals:
worst rel 1e-13) |
| sequence length not divisible by CP, 128 experts, 2 AdamW steps |
parameters and optimizer state (`step`, `exp_avg`, `exp_avg_sq`)
identical |
| shard-local KDA (negative control) | fails: loss 4.730 vs 4.749, all
73 gradients off |
| main, CP2 | refused: `supports Gated DeltaNet linear attention only,
not ['KimiDeltaAttention']` |
| gate LoRA backward on main, no CP | `RuntimeError: ... modified by an
inplace operation`; passes here |

Every CP / Ulysses / registry test that passes on main still passes; the
PR's files pass on transformers 4.57.6 / PEFT 0.18 too. Non-Kimi models:
a sweep of 178 transformers model types under CP gives 0 outcome
changes.

---------

Co-authored-by: Backup Bot <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Nov 8, 2026
**Stacked on #15880:** a PR from a fork cannot target another fork
branch, so the diff also contains that commit. Only the last commit is
new here.

## Summary

Second of the per-family PRs split from #12052. **Scope: Ulysses only.**

- **MiniMax-M1 Lightning attention.** After the local qkv projection, q
/ k / v of each head move to head shards in one all-to-all. Each rank
runs the block-wise decayed linear attention over the full sequence with
its slice of `slope_rate` and the query / key / diagonal decays. A
second all-to-all returns the output before the full-width norm, output
gate and projection.
- **MiniMax full attention and MiniMax-M2 attention** (per-layer qk_norm
on the local shard, partial RoPE) use the existing Ulysses attention
exchange. M2 is accepted without a stateful mixer.
- Packing with Lightning attention under CP is refused.

## Validation (this branch)

Setup: 2× RTX PRO 6000 (96 GB, PCIe), torch 2.13, transformers 5.15.1,
unsloth_zoo 2026.10.8. Model-level check: full-sequence forward on one
rank vs `ContextParallelManager` on 2 ranks. Trainer check:
`SFTTrainer(context_parallel_size = 2, context_parallel_backend =
"ulysses")`, LoRA r=16, the same token row every step.

| check | reference | CP=2 |
|---|---|---|
| MiniMax-M2, 2 layers sliced from the release (real weights), fp32,
loss | 10.667502 | 10.667501 (logits max diff 7e-6) |
| MiniMax-M1, 4 layers sliced from the release (real weights), fp32,
trainer per-step loss | | rel diff <= 1.5e-4 |

16K tokens, bf16, Unsloth gradient checkpointing, steady-state step
(steps 2-3). The baseline is 2-GPU DDP without CP, which uses the same
checkpointing path as CP. Single-GPU Unsloth uses a different
(reentrant, offloaded) checkpoint, so comparing against it would mostly
measure the checkpointing.

| MiniMax-M1, 4 layers | peak / GPU | step | loss (3 steps) | grad norm
|
|---|---|---|---|---|
| DDP, no CP | 9.59 GiB | 1.04 s | 11.6220 / 11.6212 / 11.6167 | 0.074 /
0.089 / 0.141 |
| Ulysses CP=2 | 6.45 GiB | 0.47 s | 11.6219 / 11.6212 / 11.6167 | 0.074
/ 0.089 / 0.141 |

CPU tests (gloo, 2 ranks): CP=2 vs CP=1 gradients for tiny MiniMax-M1
(Lightning blocks of 4 crossing the shard seam) and MiniMax-M2, with
transformers' own forwards as reference. Also a shard-local Lightning
negative control, gates and refusals. All CP test files pass (172
passed).

## Further validation plan

The released MiniMax-M1 (456B) and M2 (230B) do not fit on 2× 96 GB, and
there is no smaller model with the same architecture. So far both were
validated only on real-weight layer slices, as noted in #12052
([comment](#12052 (comment))).
The slices keep every operator type (Lightning blocks, full attention,
MoE), but not the depth or the full expert count. Plan:

1. Larger real-weight slices (e.g. 8-16 layers, including several
full-attention layers in M1's 7:1 pattern) through `SFTTrainer` with
FSDP2 + CP.
2. The full M1 / M2 on a multi-node FSDP2 + CP setup once I have access
to one. I would welcome a run on maintainer hardware if that is easier.
3. Longest trainable sequence, one GPU vs CP=2.

Related: #12052, #13920.


## Follow-up (rebased onto current main)

Merged current main (through the Kimi-Linear layer) into this branch and
slimmed it:

- **MiniMax full attention and MiniMax-M2** go through main's generic
Ulysses attention route; this branch's own attention class list and RL
refusal built on it are dropped. On main the same 17 M2 / full-attention
parity cases already pass.
- **Lightning** (`ulysses_lightning_forward`) is kept: it is the part
main does not have.
- **Capability registry:** `minimax` / `minimax_m2` are MoE families
with x CP cells (full, LoRA, LoRA on experts, router aux loss off), each
citing named gloo parity cases. Unsloth gradient checkpointing, FSDP2 x
CP, block compile, QLoRA and aux loss on stay refused.
- The expert-LoRA test cases now assert the expert adapters attached,
and skip where transformers builds per-expert modules (4.x), where PEFT
matched nothing.

### Validation

CPU gloo, fp64, against one process, with transformers' own
`MiniMaxForCausalLM` (stock router) as an independent oracle:

| check | result |
|---|---|
| CP2 / CP4, seam inside a block and on block boundaries, partial final
block, right padding | loss, every gradient and one AdamW step match
(max grad diff 5.6e-17) |
| shard-local Lightning (negative control) | fails: 30 gradients off,
max 9.0e-2 |
| 9 mutants (decay slices, partial-block decay, undecayed state, qkv
layout, gate order, shard-aligned blocks) | each fails |
| MiniMax-M1 CP2 before this layer | refused: `not
['MiniMaxLightningAttention']`; forced past it: loss 3.8617 vs 3.8663 |
| bf16, CP2 vs one process | loss equal to 4e-16; no error added over
one process |

Every test that passes on the Kimi-Linear layer still passes; registry:
only minimax / minimax_m2 queries move (0 of 136,576 others).

---------

Co-authored-by: Backup Bot <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Nov 8, 2026
… sink attention) (#15882)

**Stacked on #15881:** the diff also contains the Kimi and MiniMax
commits. Only the last commit is new here.

## Summary

Third of the per-family PRs split from #12052. **Scope: Ulysses only.**

- **V2 / V3 MLA (incl. Moonlight)** use the existing Ulysses attention
exchange. The softmax scale no longer has to be 1/sqrt(head_dim):
DeepSeek folds YaRN's mscale into it, so every attention backend now
receives the explicit scale (flash `softmax_scale`, SDPA / xFormers
`scale`).
- **V3.2** (`utils/ulysses_deepseek.py`). The DSA indexer runs before
the attention interface on the local shard, so under Ulysses its forward
is replaced. Indexer keys (one small vector per token) are all-gathered,
top-k is computed per query chunk against the full sequence and then
gathered, and the sparse causal attention runs after the head scatter.
- **V4**: sliding / CSA / HCA sink attention with a single KV head and K
== V. Queries move to head shards. The single KV head cannot be split by
heads, so it is all-gathered, and so are the compressor inputs. The
attention runs in query chunks (`UNSLOTH_CP_ATTN_CHUNK`, default 1024),
so the score matrix is `[H/N, chunk, T]` instead of `[H/N, T, T]`. With
grad, the chunks form one autograd op that saves only its inputs and
recomputes each chunk in backward, under the forward's autocast. Because
it is a single op, it nests inside activation checkpointing of the whole
layer; nested `torch.utils.checkpoint` did not, and failed at 16K.
- V3.2 / V4 configs are exempt from the generic sliding-window /
layer-type refusal under Ulysses, because these forwards build their own
masks. Packing with V3.2 / V4 under CP is refused.

## Validation (this branch)

Setup: 2× RTX PRO 6000 (96 GB, PCIe), torch 2.13, transformers 5.15.1,
unsloth_zoo 2026.10.8. Model-level check: full-sequence forward on one
rank vs `ContextParallelManager` on 2 ranks. Trainer check:
`SFTTrainer(context_parallel_size = 2)`, LoRA r=16, the same token row
every step.

| check | reference | CP=2 |
|---|---|---|
| Moonlight-16B-A3B (full release, V3 MLA), fp32, trainer per-step loss
| | rel diff <= 9e-4 |
| DeepSeek-V4, reduced model (4 random-weight layers: sliding, CSA, HCA,
sliding), fp32, loss | 11.745795 | 11.745359 (per-layer hidden rel <=
3e-6) |
| same reduced V4, fp32, trainer per-step loss | | rel diff <= 4e-3 |

16K tokens, bf16, Unsloth gradient checkpointing, steady-state step:

| model | baseline | CP=2 |
|---|---|---|
| Moonlight-16B-A3B | 2-GPU DDP, no CP: 36.60 GiB, 4.40 s | 34.76 GiB,
1.66 s |
| reduced V4 (4 layers) | single GPU: 73.33 GiB, 1.33 s | CP + FSDP2:
7.06 GiB, 1.24 s |

V4 losses (single vs CP+FSDP2) were 11.7436 / 11.7356 / 11.7222 vs
11.7440 / 11.7387 / 11.7264, and grad norms 0.1316 / 0.1317 / 0.1325 vs
0.1315 / 0.1316 / 0.1325. Most of V4's memory drop comes from the
query-chunked attention, since the single-GPU eager path builds full
`[H, T, T]` scores, plus FSDP2 weight sharding. It does not come from
sequence sharding alone.

**Pre-existing issue, not caused by CP:** DeepSeek-V4 with gradient
checkpointing under plain DDP (2 GPUs, `context_parallel_size = 1`)
fails with `CheckpointError: A different number of tensors was saved
during the original forward and recomputation` (102 vs 100). Under DDP
Unsloth switches to non-reentrant checkpointing, which checks
recomputation, and the MoE routing does not reproduce on recompute.
Single GPU (reentrant) and FSDP2 do not hit it, so the V4 CP number
above uses FSDP2.

CPU tests (gloo, 2 ranks): CP=2 vs CP=1 gradients for tiny V2, V3, V3.2
and V4 with transformers' (eager) forwards as reference; V3.2 / V4 are
also run with 4-row chunks. Also a shard-local V4 negative control,
chunked-attention gradients nested inside checkpointing, V4 gates and
the custom-scale plumbing. All CP test files pass (183 passed).

## Further validation plan

In #12052 the earlier implementation was checked on full checkpoints
([details](#12052 (comment))).
LoRA gradient cosine vs single GPU was 1.0000 on DeepSeek-V2-Lite and
0.9989 on Moonlight-16B-A3B, and at 16K CP alone was 2.5-2.7× faster
than one GPU on V2-Lite / Moonlight. V3.2 and V4 had the same gap as
here: V3.2 had CPU tests only, and V4 used a reduced 4-layer random
model whose ratios differ from the release (e.g. HCA compress rate 8 vs
128). Plan:

1. **V4:** real-weight layer slices of the released checkpoint with its
own config (compress rates 4 / 128, sliding window 128, index_topk 512),
so the CSA / HCA paths see realistic block counts. Then the full model
on multi-node FSDP2 + CP when available.
2. **V3.2:** no small V3.2 exists; build real-weight slices of the
release (MLA + indexer layers) and compare top-k selection and LoRA
gradients against one GPU.
3. **V2-Lite:** rerun the full-checkpoint gradient check on this port in
bf16 (fp32 is blocked by grouped_mm being bf16-only).
4. Longest trainable sequence, one GPU vs CP=2 / FSDP2+CP=2, on
Moonlight and V2-Lite.
5. Report the V4 DDP + checkpointing issue separately with a minimal
reproduction.

Related: #12052, #13920.

---------

Co-authored-by: Backup Bot <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Nov 9, 2026
## Summary

Fourth of the per-family PRs split from #12052. **Scope: Ulysses only.**

- `Gemma4TextAttention` runs on the existing Ulysses attention exchange.
Its per-layer sliding window now reaches the attention dispatcher
(`AttentionContext.sliding_window`). After the exchange each rank holds
the full sequence, so the window applies unchanged.
- **Sliding layers use flex attention.** Without flash-attn, SDPA has no
window: the dispatcher would build a dense `[S, S]` mask and compute
every block. Under Ulysses, sliding layers therefore use a compiled
`flex_attention` with a cached block mask, which is what the stock
non-CP Gemma 4 path uses too. If flex fails, it falls back to SDPA. At
16K (window 1024, head_dim 256) this one op goes from 95.6 ms to 2.8 ms
(forward + backward).
- The generic sliding-window refusal is lifted under Ulysses for
`gemma4_text` only, because Llama-style fast forwards still ignore
windows. The 1.0 scale, KV sharing (shared K / V stay sequence shards
until the exchange), per-layer embeddings, `attention_k_eq_v` and MoE
need no change.
- Head counts are read per layer (`per_layer_config`), since the global
per-layer reads raise on the heterogeneous 26B config. Trainer init also
checks `num_global_key_value_heads` against `context_parallel_size`.
- Multimodal Gemma 4 stays refused (only text buffers are sharded); load
it with `text_only = True`.

## Validation (this branch)

Setup: 2× RTX PRO 6000 (96 GB, PCIe), torch 2.13, transformers 5.15.1,
unsloth_zoo 2026.10.8. Model-level check: full-sequence forward /
backward on one rank vs `ContextParallelManager` on 2 ranks. LoRA r=16
grads with `lora_B ~ N(0, 1e-3)`, all-reduced and compared per
parameter.

| check | reference | CP=2 |
|---|---|---|
| gemma-4-E4B-it (full, text), fp32, loss | 16.780748 | 16.780727 |
| gemma-4-26B-A4B-it, 6 layers sliced from the release (real weights),
fp32, 4096 tok, loss | 40.411522 | 40.411522 |
| same, LoRA grad norm (106 tensors) | 8.7727 | 8.7727 (max per-tensor
rel 6e-6) |

16K tokens, bf16, Unsloth gradient checkpointing, steady-state step,
full models. Baseline: 2-GPU DDP without CP, which uses the same
checkpointing path as CP.

| model | DDP, no CP | Ulysses CP=2 |
|---|---|---|
| gemma-4-E4B-it | 22.29 GiB, 2.95 s | 19.72 GiB, 2.14 s |
| gemma-4-26B-A4B-it | 61.51 GiB, 4.44 s | 57.05 GiB, 2.86 s |

Before the flex change, CP was slower than this baseline (5.45 s and
6.95 s).

**Pre-existing behaviour, not caused by CP:** at 16K in bf16, Gemma 4
trainer metrics are not reproducible from run to run. Two identical
single-GPU 26B runs gave grad norms 113.9 / 23.1 / 20.7 and 115.9 / 58.2
/ 14.0, and DDP without CP differs from single GPU even at step 1 (loss
15.575 vs 15.614). So step-level trainer numbers are not a useful
correctness signal for Gemma 4, and the model-level fp32 checks above
are what this PR relies on. Separately, FSDP2 auto-wrap of Gemma 4 fails
on the tied `embed_tokens` ("shared with a parameter already managed by
another FSDP group").

CPU tests (gloo, 2 ranks): CP=2 vs CP=1 gradients for an E2B-shaped tiny
model (PLE, KV sharing, one KV head, window 4 across the shard seam) and
a 26B-A4B-shaped one (k_eq_v, fewer global KV heads, MoE), with
transformers' forward as reference. Also a shard-local negative control
and gates. On CUDA, flex sliding attention is compared against windowed
SDPA (values and grads). All CP test files pass (187 passed).

## Further validation plan

In #12052 the earlier implementation was checked on full Gemma 4
checkpoints
([details](#12052 (comment))).
LoRA gradient cosine vs single GPU was 0.983 on 26B-A4B and 0.981 on 31B
(bf16 rounding; E4B in fp32 matched to 3.8e-6). At 32K, one GPU and FSDP
alone ran out of memory on 26B-A4B and 31B, while CP trained them (31B
only with FSDP+CP, 75.7 GiB). Plan:

1. A full 26B-A4B fp32 gradient check (only a 6-layer slice so far),
sharded with FSDP2 + CP. This needs the tied-embedding wrap fixed or a
manual `fully_shard` grouping.
2. Gemma-4-31B and E2B with this port.
3. The 32K / longest-sequence runs from #12052 repeated with this port,
now including the flex path.

Related: #12052, #13920.



## Update after rebasing onto main

Main now has generic Ulysses attention for HF attention classes,
including Gemma 4's per-layer sliding window, so the flex sliding-window
dispatch and the `gemma4_text` window exemption described above were
dropped from this branch. What is left is the part main still lacked:

- `_model_heads` returns every distinct (heads, kv heads) pair in the
model. It reads `per_layer_config` first (the global read raises
`AmbiguousGlobalPerLayerAttributeError` on Gemma 4, whose global and
sliding layers have different KV head counts), falls back to the
top-level config, and for older Gemma 4 configs without a per-layer view
adds `num_global_key_value_heads` when `attention_k_eq_v` is set and a
full attention layer exists. Configs whose per-layer view cannot be
built (for example remote-code configs with `num_layers` instead of
`num_hidden_layers`) fall back to the global read.
- `_ulysses_head_plans` checks every pair against the CP size (and TP
split), used both by the backend choice and by the trainer-init check,
so a model whose global layers cannot split falls back to ring or raises
before any collective.
- `parallel_capabilities` gains Gemma 4 MoE cells (full, LoRA, LoRA +
experts at cp2, cp4 and dp2 x cp2, plus a windowed prompt-masked case
and eager checkpointing), backed by `tests/test_ulysses_gemma4.py`
against an fp64 reference. Multimodal Gemma 4 gets an explicit refused
cell: its vision attention is bidirectional, so only the text-only
`Gemma4ForCausalLM` is covered.

### Kaggle 2x T4 (NCCL, CP=2, tiny configs)

Base (merge base) vs head, one process vs CP=2 forward and backward,
with an A/A band from two single-process runs:

| cell | base | head (worst rel) | A/A band |
|---|---|---|---|
| Gemma 4 MoE, fp32 | refused (`num_key_value_heads` is a per-layer
attribute) | 5.2e-06 | 4.6e-06 |
| Gemma 4 MoE, fp16 | refused | 1.7e-02 | 1.9e-02 |
| Gemma 4 head_dim 512, fp32 | refused | 3.5e-05 | 3.7e-05 |
| Gemma 4 head_dim 512, fp16 | refused | 5.4e-02 | 7.1e-02 |
| Gemma 4 MoE, fp32, shard-local negative control | | diverges (1.12) |
|

The Ulysses exchange ran in every accepted cell (4 calls per step).
Under torch.compile the MoE cell recompiled 0 times on the second step,
but two single-process compiled runs already differ by 1.8 there (router
flips), so that cell is not used as a parity signal. DeepSeek V3.2 and
V4 cells inherited from below matched in the same run (fp32 worst
2.8e-07 and 6.8e-07). On CPU, 432 tests across the CP, Ulysses, registry
and Gemma 4 files pass.

---------

Co-authored-by: Backup Bot <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
@danielhanchen

Copy link
Copy Markdown
Member

Thanks a lot for this work. The pieces of this branch have now landed on main in smaller parts:

  • Native FSDP2 sharded loading and Gated DeltaNet hybrid context parallelism were already on main (unsloth/models/fsdp2_load.py, unsloth/ulysses_hybrid.py).
  • The generic Ulysses route on main covers the plain attention families (MLA with a custom scale, MiniMax-M2, DeepSeek V2 / V3, most of Gemma 4).
  • The parts unique to this branch landed through the split PRs: Kimi-Linear / Kimi-K3 KDA, MiniMax-M1 Lightning, DeepSeek V3.2 indexer and V4 compressed sink attention, and Gemma 4 per-layer head counts, each with its own capability cells and CPU and GPU parity checks.

All four squash commits on main are authored by you. Closing this one as superseded by the split, please reopen if something here is still missing on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BurstAttention:An Efficient Distributed Attention Framework for Extremely Long Sequences

2 participants