Skip to content

Context parallel: Ulysses for Gemma 4 text models - #15883

Merged
danielhanchen merged 98 commits into
unslothai:mainfrom
MegaGimen:cp-gemma4
Nov 9, 2026
Merged

danielhanchen merged 98 commits into
unslothai:mainfrom
MegaGimen:cp-gemma4

Conversation

@MegaGimen

@MegaGimen MegaGimen commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

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

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

Validation (this branch)

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

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

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

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

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

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

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

Further validation plan

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

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

Related: #12052, #13920.

Update after rebasing onto main

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

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

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

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

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

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

Backup Bot added 4 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.
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.

@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: 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".

Comment on lines +137 to +140
for model_type in model_types or ():
if model_type in DEEPSEEK_ULYSSES_MODEL_TYPES:
return DEEPSEEK_ULYSSES_MODEL_TYPES[model_type]
return None

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 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 👍 / 👎.

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

danielhanchen and others added 2 commits November 7, 2026 13:24
…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: 2cede1502d

ℹ️ 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 3 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. What shall we delve into next?

Reviewed commit: 57d5bbd239

ℹ️ 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 3329d6d into unslothai:main Nov 9, 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