Repository navigation
Context parallel: Ulysses for Gemma 4 text models - #15883
Conversation
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.
Stacked on the DeepSeek change. Gemma4TextAttention runs on the existing Ulysses attention exchange. Its per-layer sliding window now reaches the attention dispatcher (AttentionContext.sliding_window), which already windows the flash, torch varlen and SDPA paths; after the exchange each rank holds the full sequence, so the window applies unchanged. Without flash, SDPA would compute the full [S, S] score matrix behind a window mask, so sliding layers instead use a compiled flex_attention block mask (the stock Gemma 4 path is flex too); a flex failure falls back to SDPA. The generic sliding-window / sliding_attention refusal is lifted under Ulysses for gemma4_text only, since Llama-style fast forwards still ignore windows. The scale of 1.0, KV sharing (shared K / V stay sequence shards until the exchange), per-layer embeddings, attention_k_eq_v and MoE need no change. Trainer init also checks num_global_key_value_heads against context_parallel_size. Multimodal Gemma 4 stays refused (only text buffers are sharded). Tests (CPU gloo, 2 ranks): CP=2 vs CP=1 gradients for an E2B-shaped (PLE, KV sharing, one KV head, window 4 across the shard seam) and a 26B-A4B-shaped (k_eq_v, fewer global KV heads, MoE) tiny Gemma 4 with transformers' forward as reference, a shard-local negative control, gates, and (CUDA) flex sliding attention vs windowed SDPA. 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
# 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.
…ckward, refuse window-dropping fast forwards - A flex failure on one call class (dtype, head size, window, block alignment, training) no longer switches flex off process-wide; out-of-memory errors are re-raised. - Training calls run flex forward + backward once per class first, so a backward that cannot compile falls back to dense windowed SDPA instead of failing in loss.backward(). - The Gemma 4 sliding window exemption is refused when an attention module runs Llama's fast forward, which ignores the window. - Tests: window seam at CP=2 / CP=4 vs an fp64 reference (window - 1 kept, window dropped, packed documents), flex fallback scale / window, scoped failures with real CPU flex, a backward-only failure under no / reentrant / non-reentrant checkpointing, whole-model fp64 parity at CP=2 / CP=4 / DP2xCP2 with padding, a label-less rank, LoRA with nonzero B and one AdamW step, numerical negative controls, and the narrow refusal.
…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.
# Conflicts: # unsloth/context_parallel.py
…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.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b51a7f07e4
ℹ️ 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".
| for model_type in model_types or (): | ||
| if model_type in DEEPSEEK_ULYSSES_MODEL_TYPES: | ||
| return DEEPSEEK_ULYSSES_MODEL_TYPES[model_type] | ||
| return None |
There was a problem hiding this comment.
Include deferred hybrid models in the Ulysses packing blocker
When SFTTrainer receives a Kimi-Linear or MiniMax-M1 model ID with Ulysses CP and eval_packing=True, this branch returns None because the lookup contains only DeepSeek families. The separate hybrid gate clears training packing and padding_free, but _patch_sft_trainer_auto_packing relies on this blocker to clear eval_packing, leaving evaluation packed even though the new Ulysses mixer forwards do not support packed batches. Classify the deferred hybrid families here too, so model IDs receive the same safe evaluation settings as already-built instances.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 61b8e1d (parent branch, merged here): the string path now also maps kimi_linear / kimi_k3 / minimax to their Ulysses mixers, so a model ID turns eval_packing off like an instance does.
…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]>
Co-authored-by: Immanuel Sun <[email protected]>
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Co-authored-by: Immanuel Sun <[email protected]>
Co-authored-by: Immanuel Sun <[email protected]> # Conflicts: # unsloth/context_parallel.py
Co-authored-by: Immanuel Sun <[email protected]>
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Co-authored-by: Immanuel Sun <[email protected]> [skip ci]
Co-authored-by: Immanuel Sun <[email protected]>
Summary
Fourth of the per-family PRs split from #12052. Scope: Ulysses only.
Gemma4TextAttentionruns 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.[S, S]mask and compute every block. Under Ulysses, sliding layers therefore use a compiledflex_attentionwith 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).gemma4_textonly, 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_vand MoE need no change.per_layer_config), since the global per-layer reads raise on the heterogeneous 26B config. Trainer init also checksnum_global_key_value_headsagainstcontext_parallel_size.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
ContextParallelManageron 2 ranks. LoRA r=16 grads withlora_B ~ N(0, 1e-3), all-reduced and compared per parameter.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.
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). 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:
fully_shardgrouping.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_textwindow exemption described above were dropped from this branch. What is left is the part main still lacked:_model_headsreturns every distinct (heads, kv heads) pair in the model. It readsper_layer_configfirst (the global read raisesAmbiguousGlobalPerLayerAttributeErroron 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 addsnum_global_key_value_headswhenattention_k_eq_vis set and a full attention layer exists. Configs whose per-layer view cannot be built (for example remote-code configs withnum_layersinstead ofnum_hidden_layers) fall back to the global read._ulysses_head_planschecks 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_capabilitiesgains 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 bytests/test_ulysses_gemma4.pyagainst an fp64 reference. Multimodal Gemma 4 gets an explicit refused cell: its vision attention is bidirectional, so only the text-onlyGemma4ForCausalLMis 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:
num_key_value_headsis a per-layer attribute)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.