Skip to content

Context parallel: Ulysses for Kimi-Linear (KDA + MLA), and fix Kimi-Linear MoE gate backward - #15880

Merged
danielhanchen merged 16 commits into
unslothai:mainfrom
MegaGimen:cp-kda
Nov 8, 2026
Merged

danielhanchen merged 16 commits into
unslothai:mainfrom
MegaGimen:cp-kda

Conversation

@MegaGimen

@MegaGimen MegaGimen commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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 Context parallel: Ulysses for Gated DeltaNet hybrids (Qwen3.5, Qwen3-Next) #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

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

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.
# Conflicts:
#	unsloth/context_parallel.py
#	unsloth/utils/ulysses_hybrid.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.
…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.
@MegaGimen

Copy link
Copy Markdown
Contributor Author

Hi @danielhanchen, thanks a lot for the fixes you pushed onto these four PRs (the gate shim, the flash window, the compiled-layer handling and the fp64 tests).

Since #16407 and #16558 landed, the branches conflict with main, and #16558's generic Ulysses now covers the plain-attention parts here: MLA with a custom scale, MiniMax full attention / M2, and most of Gemma 4's sliding-window handling. What is still specific to these PRs:

  • KDA (Kimi-Linear / K3) and Lightning (MiniMax-M1) linear attention under Ulysses
  • DeepSeek V3.2 (DSA indexer) and V4 (single-KV sink attention with compressors), whose forwards need the full sequence before the attention call
  • the Kimi-Linear KimiMoEGate in-place backward fix, which breaks LoRA training even without CP

I'm happy to rebase all four onto current main, drop what #16558 now handles, and keep only the parts above, so each PR gets smaller. Would you prefer that, or would you rather finish them on your side? Either way is fine with me.

One request about credit. #13920 and #16558 overlap with work I posted earlier (#12052 and #15883), and neither mentions it. Whichever way these land, including if they end up re-implemented in another PR, I'd appreciate a reference to these PRs and a co-author trailer on the commits that carry this work:

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

Thanks!

@danielhanchen

Copy link
Copy Markdown
Member

Thanks a lot for the clear breakdown. I'll finish the four on my side: each branch gets current main merged in and is slimmed to the parts generic Ulysses does not cover (KDA for Kimi-Linear / K3, Lightning for MiniMax-M1, the DeepSeek V3.2 indexer and V4 compressor / sink attention, and the KimiMoEGate backward fix), then retested on CPU and on 2 GPUs before landing bottom-up.

Every commit that carries your work will keep the Co-authored-by: Immanuel Sun <[email protected]> trailer, and the descriptions will credit your earlier Qwen3.5 GatedDeltaNet work.

danielhanchen and others added 5 commits November 7, 2026 06:02
Resolved toward main's generic Ulysses (unslothai#16558): Hugging Face attention, Kimi-Linear MLA included,
runs through _ulysses_hf_attention with its own scale and value width, so the MLA value padding is
dropped. The Kimi delta attention mixer path, the every-expert MoE grads and the gate shim are kept
on top of main's attention declarations, registry gates and decoder mask hook.

Co-authored-by: Immanuel Sun <[email protected]>
Main dropped the module's weakref import in unslothai#16558 once its own last use moved out;
install_idle_expert_grad_hook still holds the MoE blocks by weak reference, so every
Kimi-Linear MoE training step under context parallelism raised NameError.

Co-authored-by: Immanuel Sun <[email protected]>
Kimi-Linear's MLA layers call ALL_ATTENTION_FUNCTIONS, so main's generic Ulysses (unslothai#16558)
already runs them with their own scale and narrower value heads. Drop the KimiMLAAttention
class list: the hybrid check accepts the Gated DeltaNet attention classes or any registry
attention next to the Ulysses mixers, and the hooks install the generic wrapper as for
plain attention models. Equivalence: the hub KimiMLAAttention / KimiDecoderLayer under CP2
gloo match one process on main and on this branch (sdpa fp64 with a custom and the default
scale, eager fp32), every parameter gradient, and fail when the CP arm loses the scale.

Co-authored-by: Immanuel Sun <[email protected]>
… evidence

parallel_capabilities refused every Kimi-Linear MoE run under context parallelism: only
qwen3_moe had MoE x cp evidence. The new test runs the hub KimiSparseMoeBlock and
KimiMoEGate (in-place score bias) under Unsloth's shim next to KDA and MLA layers, CP2 and
DP2 x CP2 on gloo, fp64 against one process: every gradient, None vs zero for experts no
rank routed to, the idle expert hook and one AdamW step, for full finetuning, LoRA and LoRA
on the experts, sdpa and eager, with and without HF checkpointing. Those cells now carry it;
Unsloth's checkpoint, FSDP2 x cp, block compile and the router auxiliary loss stay refused.

Kimi names its delta layers self_attn, so the decoder mask hook gives them no padding mask
under CP. CP accepts right padding only and the scan is causal: a right padded batch under
CP2 and CP4 matches a one-process run whose delta layers do mask the padding, and left
padding is refused before any collective.

Co-authored-by: Immanuel Sun <[email protected]>
The floor PEFT (0.18.0) reads model.config.to_dict() when it injects LoRA, so the LoRA
cases of the Kimi CP and remote MoE tests failed there on the stand-in configs. A real
hub config is a PretrainedConfig with to_dict; the stand-ins now have one too.

Co-authored-by: Immanuel Sun <[email protected]>
@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-07T18:35:13.202253Z 52063dc 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: c6912700a6

ℹ️ 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/models/remote_moe_shims.py Outdated
every_expert = get_cp_manager() is not None
if every_expert:
# So the optimizer step can drop the zero gradients of experts no rank routed to.
record_expert_tokens(block, token_counts)

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 Exclude CP-added padding from expert-usage counts

When the input length is not divisible by the CP size, ContextParallelManager._prepare_inputs() appends synthetic padding tokens, and token_counts includes their routes. If one of those tokens is the only token selecting an expert, the idle-gradient hook keeps that expert's zero gradient, so AdamW applies weight decay and advances its state even though the single-process run never invoked it and leaves .grad = None. This changes optimizer updates for full finetuning and expert LoRA. Track and exclude CP-added tokens from this bookkeeping while retaining the empty expert calls required by DDP.

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 1d845dd: the manager records a real-token mask per shard (Ulysses and ring) and the MoE dispatch counts only real routes, still running every expert for DDP.

Comment thread unsloth/context_parallel.py Outdated
Comment on lines +353 to +356
def hook(_optimizer, _args, _kwargs):
drop_idle_expert_grads([b for b in (ref() for ref in blocks) if b is not None], group)

optimizer.__dict__["_unsloth_idle_expert_hook"] = optimizer.register_step_pre_hook(hook)

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 Clear expert counters when AMP skips an optimizer step

With FP16 and a non-fused optimizer, GradScaler can skip the underlying optimizer.step() on overflow. Because the counters are only removed by this step pre-hook, they survive Trainer's subsequent gradient reset and accumulate into the next window. An expert routed only in the discarded window is therefore treated as active on the next successful step and receives weight-decay or momentum updates instead of having .grad = None, diverging from the single-process optimizer. Clear the usage counters when a window's gradients are discarded as well as at successful optimizer steps.

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 1d845dd: a new count window starts when the trainer's global_step changes (it advances on skipped GradScaler steps too) and forgets only experts whose grads are None.

…per gradient window

Two gaps in the idle-expert machinery that keeps AdamW in step with one process under context
parallelism:

- Tokens the manager appends so the length divides the CP size (Ulysses and ring) were counted as
  routed, so an expert picked only by them kept its zero gradient and AdamW decayed it and
  advanced its state, while one process leaves its gradient None. The manager now records a
  real-token mask per shard (sharded with the batch, ring included, and kept through backward
  for checkpoint recompute), and the MoE dispatch counts only real routes. It still runs every
  expert, so DDP sees a gradient for each.
- Counts were cleared only in the optimizer step pre-hook, so a step GradScaler skipped on fp16
  overflow leaked its usage into the next window. The trainer's global_step now starts a new
  window at each training_step that sees it change (constant over accumulation micro-batches,
  advanced also on skipped steps), and the first forward after a real step does the same. A new
  window forgets only experts whose gradients are None, which mirrors one process for
  zero_grad(set_to_none = False) too (zero gradients are stepped there).

Tests (gloo, 2 ranks, against one process): padding-only experts under Ulysses and ring, full
and expert LoRA; a skipped GradScaler step through the CP training_step wrapper with gradient
accumulation, with and without checkpointing, set_to_none True and False.

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. Already looking forward to the next diff.

Reviewed commit: 1d845ddacc

ℹ️ 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 09:05
fla's chunk_kda(use_qk_l2norm_in_kernel = True), which the CUDA path and
the hub model use, scales by rsqrt(sum(x ** 2) + 1e-6); F.normalize clamps
the norm instead, which moved the CPU fallback's gradients by up to 2e-4
relative against the hub model with fla's naive kernels. The test's fp64
reference follows the same formula.

Co-authored-by: Immanuel Sun <[email protected]>
The CP training_step wrapper now clears the per-step real-token masks.

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

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to MegaGimen/unsloth that referenced this pull request Nov 7, 2026
…iMax branch

Brings main in through unslothai#15880. MiniMax's full attention layers (M1) and MiniMax-M2 now run on
main's generic Ulysses route, which wraps any attention that calls ALL_ATTENTION_FUNCTIONS. So the
MiniMaxAttention / MiniMaxM2Attention class lists and _runs_hf_ulysses_attention go. Main already
refuses generic Hugging Face attention under DPO / GRPO, and it applies the router aux loss and
per-expert blockers to generic models. The Lightning mixer forward and its head check stay.

The RL refusal test now checks main's messages: M2 is refused as generic attention and the M1
hybrid as a linear attention hybrid.

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

@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: 4f24f83494

ℹ️ 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 on lines +356 to +358
if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2:
mask = attention_mask[:, -hidden_states.shape[1] :, None]
hidden_states = (hidden_states * mask).to(hidden_states.dtype)

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 Preserve Kimi padding masks before counting expert usage

For full finetuning or expert LoRA on a right-padded Kimi batch, attach_attention_hooks() clears the mask via its decoder/self-attention pre-hooks before this branch, so padded-position activations and MoE routes can differ from the masked single-process forward. real_token_mask() still counts caller-supplied padding (it excludes only CP-appended tokens), so an expert selected only by those changed padding routes keeps a zero CP gradient and receives AdamW decay/state updates even though the reference leaves its gradient None. This occurs even when the sequence length already divides the CP size. Preserve the reference padding behavior/routes for KDA and add a pad-only-expert case to the masked parity test.

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 1e3d6a4: under CP the KDA output is zeroed past each row's real length and the generic attention rebuilds pad rows as one process does (flash: zero; sdpa / eager: pad queries over the row's real keys), so pads route to the same experts; parity incl. AdamW state over 2 steps, CP2 and CP4.

…pert hook to CP steps

Under Ulysses CP the attention hooks drop the caller's padding mask. One process
still runs right padding through the MoE: Kimi delta layers zero it (the hub
unpads and pad_input leaves zero rows), and MLA masks the padded keys (sdpa and
eager: a padding query attends its row's real keys; flash unpads, so the rows
are zero). Under CP the padding got other activations, so it routed to other
experts. An expert only padding picks then had a zero gradient on one side and
None on the other, and AdamW decayed and stepped a different set of experts,
even when the sequence divides the CP size.

The manager now records each row's caller length (only for models whose MoE
counts expert usage, the remote shim), and the Ulysses Kimi delta forward and
the generic Ulysses attention rebuild the single-process padding rows from it.
Real-token outputs and gradients are unchanged. sdpa / eager with a sliding
window and rows without real tokens are left as before.

The idle-expert step pre-hook stays on the optimizer. It now acts only on
blocks a CP forward counted since the last step, and a forward without CP
forgets the counts, so a later trainer reusing the optimizer without CP keeps
every gradient (also after a GradScaler-skipped last CP step).

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

Copy link
Copy Markdown
Member

@codex review

@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: 1e3d6a40f1

ℹ️ 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_hybrid.py Outdated
rows.append(out[row])
continue
# An explicit (all-zero) mask: no causal alignment between the padding queries and real keys.
mask = torch.zeros(1, 1, total - length, length, device = query.device, dtype = query.dtype)

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 Avoid materializing a quadratic padding-row mask

For long right-padded Kimi batches using SDPA, this allocates a dense (total - length) × length mask on every CP rank, despite the main SDPA call using no mask. A 65,536-token row with 32,768 real tokens requests a 2 GiB BF16 mask at each MLA layer, and increasing CP does not reduce that allocation. This introduces an avoidable quadratic memory bottleneck that can make long-context training OOM. Preserve the non-causal padding-query behavior without materializing this matrix, for example by using a broadcastable constant mask or a mask-free SDPA call with is_causal=False.

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 52063dc: the padding queries now call attention with no mask and is_causal = False (every real key precedes them), so nothing quadratic is allocated.

The padding queries follow every real key of their row, so is_causal = False
with no mask gives the masked single-process result; the explicit all-zero
[pad, real] mask grew quadratically with the row length on every CP rank.

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. Keep it up!

Reviewed commit: 52063dc1e3

ℹ️ 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 b61e6ee into unslothai:main Nov 8, 2026
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
…ichever rank fails first (#17151)

## Summary

`Repo tests (CPU, rest)` fails on some PRs at a test #15880 added
yesterday. Today that includes #17129 and #17132, neither of which
touches context parallelism:

```
tests/test_remote_moe_shims.py:920: in test_without_context_parallelism_idle_experts_stall_ddp
E   AssertionError: Regex pattern did not match.
E     Expected regex: 'not close|finished reduction|did not receive grad'
E     Actual message: '-- Process 1 terminated with the following error:
      ...
      File "tests/test_remote_moe_shims.py", line 895, in _moe_ddp_worker
        assert got.grad is not None, name  # a zero gradient, never None, for DDP
    AssertionError: experts.0.gate_proj.weight
```

The test is a negative control. With context parallelism off, each rank
leaves the experts its peer routes to with a `None` gradient, so DDP
without `find_unused_parameters` never reduces that bucket. The test
expects the run to fail, and it does, every time. Which error the test
sees depends on which of the two spawned ranks fails first:

- the rank that **used** an expert holds an unreduced local gradient,
and `assert_close` fails with `not close`, which the regex accepts;
- the rank that left the **same** expert idle reaches `assert got.grad
is not None` first, and that assertion's message is just the parameter
name, which the regex does not accept.

`torch.multiprocessing.spawn` reports whichever process dies first. So
the test passes or fails on scheduling, while the product behaviour it
checks is identical either way. Context parallelism itself is correct.
The positive test next to it, with context parallelism on, passes.

## Change

`tests/test_remote_moe_shims.py`, test only:

- The worker's gradient assertion says what it found: `f"{name}: no
gradient"`.
- The negative control's regex also accepts `no gradient`, with a
comment on why both ranks' errors are the same finding.

The control still fails if context-parallel-off training ever stops
stalling DDP, because then nothing raises at all.

## Testing

| | result |
|---|---|
| main, with rank 0 delayed 3 s before its checks so rank 1 fails first
(the CI case) | fails: `Regex pattern did not match`, `Process 1
terminated` |
| this branch, same delay | passes |
| this branch, `tests/test_remote_moe_shims.py` | 49 passed |
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