Skip to content

Context parallel: Ulysses for DeepSeek (V2 / V3 MLA, V3.2 indexer, V4 sink attention) - #15882

Merged
danielhanchen merged 67 commits into
unslothai:mainfrom
MegaGimen:cp-deepseek
Nov 8, 2026
Merged

danielhanchen merged 67 commits into
unslothai:mainfrom
MegaGimen:cp-deepseek

Conversation

@MegaGimen

Copy link
Copy Markdown
Contributor

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). 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.

Backup Bot added 3 commits October 29, 2026 08:51
Extends the Ulysses hybrid path (unslothai#13920) to Kimi delta attention. 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 runs the q/k/v short convs (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.
Kimi's MLA full attention goes through the existing Ulysses attention exchange; value heads
narrower than query heads are padded and sliced like Hugging Face's flash path.

The train-mode remote MoE dispatch now runs unrouted experts on zero tokens while CP is
active, so every expert gets a gradient on every rank (DDP would otherwise stall), and such
shimmed blocks are no longer refused as per-expert MoE. Packing with KDA under CP is refused.

Kimi-Linear's remote gate adds e_score_correction_bias in place to the sigmoid output that the
sigmoid's backward saved, so any LoRA training step (with or without CP) failed in backward with
"modified by an inplace operation". The gate shim now saves copies of the gate's autograd
tensors (saved_tensors_hooks), which keeps routing unchanged and works under both reentrant and
non-reentrant checkpointing. The gate of an inference-only remote block is now shimmed even when
the port renames it (KimiMoEGate), not only DeepSeek's MoEGate.

Tests (CPU gloo, 2 ranks): CP=2 vs CP=1 gradients for Kimi-Linear and K3 stand-in layers, a
shard-local negative control, gates, packing / cache refusal, the gate formula, MoE zero
gradients, MLA value padding, and the in-place gate backward.

Related: unslothai#12052.
Stacked on the Kimi-Linear change.

MiniMax-M1 Lightning attention: q / k / v of each head move to head shards in one all-to-all
after the local qkv projection; 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, and 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.

Tests (CPU 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, a
shard-local Lightning negative control, gates and refusals.

Related: unslothai#12052.
… sink attention)

Stacked on the MiniMax change.

- V2 / V3 MLA (incl. Moonlight) use the existing Ulysses attention exchange. The softmax scale is
  no longer required to be 1/sqrt(head_dim): DeepSeek folds YaRN's mscale into it, and 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 its forward is replaced under Ulysses. Indexer keys (one small vector per token)
  are all-gathered, top-k is computed per query chunk against the full sequence and gathered, and
  the sparse causal attention runs after the head scatter.
- V4: sliding / CSA / HCA sink attention with K == V. Queries move to head shards, the single KV
  head and the compressor inputs are all-gathered, and 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 are one autograd op that saves only its inputs and recomputes
  each chunk in backward (under the forward's autocast), so it nests inside activation
  checkpointing of the whole layer. 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.

Tests (CPU gloo, 2 ranks): CP=2 vs CP=1 gradients for tiny V2, V3, V3.2 and V4 with transformers'
forwards as reference (V3.2 / V4 also with 4-row chunks), a shard-local V4 negative control, V4
gates and the custom-scale plumbing. On full checkpoints the earlier implementation
of these forwards matched single-GPU gradients (V2-Lite, Moonlight cos >= 0.998) and cut V4-Lite
16K fsdp_cp peak memory from 22.1 to 8.6 GiB.

Related: unslothai#12052.
# Conflicts:
#	unsloth/context_parallel.py
#	unsloth/utils/ulysses_hybrid.py
# Conflicts:
#	unsloth/context_parallel.py
#	unsloth/utils/ulysses_hybrid.py
# Conflicts:
#	unsloth/context_parallel.py
…parallel blocks, fp64 CP tests

The gate shim pushed saved_tensors_hooks that cloned every saved tensor. Inside non-reentrant
checkpointing (the DDP / context parallel default) those hooks override the checkpoint's own, so
the gate's fp32 input copy, scores and weights stayed resident through the forward. Copy only the
sigmoid / softmax output that Kimi-Linear edits in place, through a TorchFunctionMode.

_runs_every_expert no longer counts ep_size > 1 blocks, which keep the remote forward.

Tests: KDA / MLA under Ulysses against an fp64 single process reference (CP=2, CP=4, DP2 x CP2,
padded rows, a shard without labels, a label across the seam, LoRA with nonzero B, AdamW) with
negative controls; the in-place gate against an out-of-place oracle under every checkpoint mode;
complementary expert routing over three DDP steps with find_unused_parameters off.
…L refusal test

Lightning attention block by block (lengths below / at / above the block size, seams inside a
block and on block boundaries, partial final blocks, CP 2 and 4) with mutants of the slope and
decay slicing, QKV layout, state decay, block alignment and norm / gate order that must fail.
Whole M1 hybrid and M2 models with padding, a rank without labels, a label across the seam,
nonzero position offsets, GQA / MQA, LoRA, gradient checkpointing, one AdamW step, CP 4 and
DP2 x CP2, plus negative controls (shard-local mixers, shard-local positions, qk-norm after the
exchange). DPO / GRPO refuse Ulysses-only attention while SFT accepts it.
test_minimax_gates expects the per-expert MoE refusal on transformers 4.x.
…nce, fp64 reference tests

- _unsupported_attention: the DeepSeek V3.2 / V4 exemption now covers only their own layer types
  and the sliding window; attention_chunk_size and attn_logit_softcapping still refuse under Ulysses.
- V4 Ulysses forward gathers kv / hidden / q_residual with _GatherSequence: torch.distributed.nn's
  gloo all_gather backward scatters from group ranks as global ranks and fails under DP x CP.
- tests/test_ulysses_deepseek_reference.py: explicit scale through SDPA (dense / packed) vs
  softmax(scale QK^T + mask) V, V3.2 global top-k vs the full-sequence indexer, V3 / V3.2 / V4 at
  release compression ratios vs fp64 single-process references with right padding, an empty-label
  rank, a seam-crossing label, CP 2 / 4, DP 2 x CP 2, LoRA with nonzero B and one AdamW step, chunk
  sizes 1 / irregular / full, and negative controls.
…mizer step

Under context parallelism every expert runs (on no tokens if unrouted) so DDP sees a gradient
for all of them. An expert no rank routed to then had a zero gradient instead of None, and AdamW
decayed it and advanced its moments and step count, unlike the single-process run. The dispatch
now counts routed tokens per expert, and an optimizer step pre-hook (installed by the CP
training_step for SFT and RL trainers) all-reduces the counts of all layers in one collective
and sets .grad = None on experts (and their LoRA adapters) with a global count of 0.
…king

SFT's automatic padding-free choice turned on for DeepSeek V3.2 / V4 (MoE), and the
first Ulysses CP step then raised 'does not support packing for DeepseekV32Attention'.
Block packing / padding-free (and eval packing) when a Kimi delta, Lightning or DeepSeek
V3.2 / V4 module would refuse packed batches, like ring CP already does.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-07T22:01:36.160594Z 9971de6 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 44b170e2fa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/utils/ulysses_deepseek.py Outdated
checkpointing of the whole layer; custom_fwd / custom_bwd replay the forward's autocast state."""

@staticmethod
@torch.amp.custom_fwd(device_type = "cuda")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve older Torch compatibility when importing the module

On PyTorch 2.1–2.3 CUDA installations, torch.amp does not expose custom_fwd or custom_bwd; the existing bindings in unsloth/kernels/utils.py explicitly fall back to torch.cuda.amp for these versions. This decorator is evaluated when context_parallel imports the new module, and models/llama.py imports context_parallel during ordinary Unsloth initialization, so even users with context parallelism disabled now encounter an import-time AttributeError. Apply the compatible AMP bindings here, or defer importing this implementation until after CP's Torch-version check.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3324fe8: the AMP decorators are resolved once at import with the same torch.amp / torch.cuda.amp fallback kernels/utils.py uses (device from DEVICE_TYPE_TORCH), with a test that removes torch.amp.custom_fwd.

Comment thread unsloth/trainer.py Outdated
Comment on lines +1943 to +1945
if cp_backend == "ulysses" and not _packing_gate_deferred:
from .context_parallel import ulysses_packing_blocker as _ulysses_packing_blocker
ulysses_packing_blocker = _ulysses_packing_blocker(model)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply the Ulysses packing blocker to string-loaded models

When SFTTrainer receives a DeepSeek-V3.2 model ID rather than an instantiated model, _packing_gate_deferred is true, so this detector is skipped. V3.2 is not covered by packing_boundary_blocker, and the deferred post-init check only checks whether the forward accepts packing kwargs, not whether its Ulysses attention supports them. Consequently, context_parallel_size=2 with packing=True or padding_free=True retains packed batching and reaches the new attention wrapper's NotImplementedError on the first batch, whereas passing the same model as an instance correctly disables packing. Classify the resolved config/class before constructing the collator, or provide an equivalent deferred CP-specific guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3324fe8: the Ulysses packing blocker also runs on the string path from the resolved config's model type (deepseek_v32 / deepseek_v4), so a model ID gets the same packing outcome and warning as an instance.

…cking

The DeepSeek chunked attention autograd ops decorated their forward and
backward with torch.amp.custom_fwd / custom_bwd in the class body. That
module is imported by plain `import unsloth`, and torch.amp.custom_fwd is
2.4+, so older torch raised AttributeError at import. Resolve the
decorators once, falling back to torch.cuda.amp, and replay autocast on
xpu / npu when that is the device, matching kernels/utils.py.

SFTTrainer given a model ID string skipped the Ulysses packing check,
so DeepSeek-V3.2 under context_parallel_size > 1 kept packed or
padding-free batches and the attention wrapper raised on the first
step. The deferred path now classifies the resolved config's model
types, giving the same outcome and warning as a model instance.

Co-authored-by: Immanuel Sun <[email protected]>
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 3324fe8f7b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen and others added 2 commits November 7, 2026 11:39
…trings too

A model ID string has no modules to walk, so only DeepSeek V3.2 / V4 model
types were recognised; Kimi-Linear and MiniMax-M1 strings kept eval_packing
on although their Ulysses mixers refuse packed batches.

Co-authored-by: Immanuel Sun <[email protected]>
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 61b8e1da01

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen and others added 2 commits November 7, 2026 13:44
Co-authored-by: Immanuel Sun <[email protected]>

# Conflicts:
#	unsloth/context_parallel.py
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 9971de697f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 66ee929 into unslothai:main Nov 8, 2026
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.

2 participants