Skip to content

Context parallel: Ulysses for MiniMax (M1 Lightning hybrid, M2) - #15881

Merged
danielhanchen merged 38 commits into
unslothai:mainfrom
MegaGimen:cp-minimax
Nov 8, 2026
Merged

danielhanchen merged 38 commits into
unslothai:mainfrom
MegaGimen:cp-minimax

Conversation

@MegaGimen

@MegaGimen MegaGimen commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Backup Bot added 2 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.
# Conflicts:
#	unsloth/context_parallel.py
#	unsloth/utils/ulysses_hybrid.py
# 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.
…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.
…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.
danielhanchen and others added 10 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]>
…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]>
…te cases

parallel_capabilities refused every MiniMax run under context parallelism, because minimax and
minimax_m2 were not MoE families there. The float64 parity test against the upstream
full-sequence forward now also covers the cells it backs:
- eager attention;
- HF checkpointing on full finetuning;
- LoRA on the fused expert weights (target_parameters);
- a MiniMax with full attention layers only, which is the generic Ulysses route with no Lightning
  mixer.
Each case checks every gradient (None vs zero included) and one AdamW step, for CP 2 and DP2 x CP2.
The minimax / minimax_m2 x full / lora / lora+experts x aux off x cp cells now cite these cases.
Unsloth's checkpoint, FSDP2 x cp, block compile, QLoRA and the router auxiliary loss stay refused.

The stock routers take their sigmoid / softmax in fp32. On CPU, a shard (a different token count)
can move a routing weight by one fp32 ulp, which is about 6e-7 relative in a LoRA gradient. With
that one cast kept in float64 the M2 LoRA-on-experts case matches to 1e-8, so the parity test runs
the routers that way.

Co-authored-by: Immanuel Sun <[email protected]>
…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]>
…ut fused experts

PEFT matches no parameter silently when target_parameters names a weight the model lacks.
transformers 4.x MiniMax keeps per-expert modules, so on that version the LoRA-on-experts cases
were running attention-only LoRA. They now assert that the expert weights carry adapters, and
they skip where the experts are not fused (CP refuses per-expert modules there anyway).

Co-authored-by: Immanuel Sun <[email protected]>
danielhanchen and others added 3 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

@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-07T21:58:45.643218Z 27f23b2 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: 4a36e7038a

ℹ️ 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 +225 to +227
else:
token_counts_real = token_counts
record_expert_tokens(block, token_counts_real)

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 padded-token routing before classifying idle experts

For right-padded Kimi-Linear batches, the CP attention hooks clear the KDA padding mask, so padded hidden states—and therefore their router selections—can differ from the single-process forward. real_token_mask excludes only CP-appended positions, so the caller's original padding is still counted here. If an expert is selected only by those padding positions in one execution, drop_idle_expert_grads leaves it with None in one run but a zero tensor in the other; AdamW then applies different weight decay, momentum, and step counts despite identical real-token losses. Preserve masked padded-token routing, or make padding activity semantics consistent on both execution paths before recording these counts.

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 the parent branch (1e3d6a4), merged here: pad rows now get the single-process activations under CP, so their routes and expert usage match.

Comment on lines +387 to +388
def hook(_optimizer, _args, _kwargs):
drop_idle_expert_grads([b for b in (ref() for ref in blocks) if b is not None], group)

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 Deactivate the idle-expert hook when CP training is disabled

If the same optimizer is reused by a later trainer with context_parallel_size=1, this registered pre-hook remains active, but _moe_train_dispatch no longer calls record_expert_tokens. The hook consequently uses counts retained from the previous CP phase: after a CP step that used only expert 0, a subsequent non-CP backward through expert 1 has its genuine gradient reset to None at optimizer.step(), silently skipping its update. Scope or unregister the hook and its counters when CP training is disabled instead of applying stale routing data.

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 the parent branch (1e3d6a4), merged here: the hook acts only on blocks a CP forward counted since the last step, and a non-CP training forward clears the counts.

danielhanchen and others added 2 commits November 7, 2026 10:05
…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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: c01c46523c

ℹ️ 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 10:26
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. Breezy!

Reviewed commit: 7e3bf29318

ℹ️ 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

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 27f23b2134

ℹ️ 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 fa82bcc into unslothai:main Nov 8, 2026
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]>
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