Repository navigation
Context parallel: Ulysses for Gated DeltaNet hybrids (Qwen3.5, Qwen3-Next) - #13920
Conversation
Resolve conflicts against main (trainer patching moved to _gpu_init, CLI _build_sft_config, packing gate, attention dispatch, CausalLM loss block). Rework the context parallel path: - RoPE uses the sharded global position_ids with main's fast_rope_embedding (drops the slice helper that raised on per-row position_ids and the per-layer .item() host sync); only the rope cache length scales by CP size. - compute_loss divides the trainer's pre-shard num_items_in_batch by the CP size and delegates to the stock path, keeping GA-exact normalisation and HF's own cross-rank loss logging (replaces the custom loss all-reduce). - Drop the custom train sampler: accelerate already gives CP ranks the same batch from the dp_replicate x cp mesh, and the extra DistributedSampler double-sharded data once dp > 1. Drop shuffle_dataset / pad_to_multiple_of (CP pads to 2 x size internally). - Reset the active manager in finally; attention hook only drops the mask inside a CP step; reject world sizes not divisible by the CP size and models whose attention is not the Llama forward. - Resolve SDPA per call so context_parallel's monkey patch is seen. - Add tests/test_context_parallel.py.
HF find_labels treats every forward parameter containing 'label' as a required label, so a named shift_labels made eval batches look label-less and Unsloth's prediction_step fell into the prompt-only branch (KeyError: 'prompt').
Without a flash kernel (T4, fp32) SDPA with enable_gqa=True falls back to the math backend, which ring attention cannot shard (aten.add got mixed torch.Tensor and DTensor). Expand K/V while CP is active so flash or memory-efficient attention is used.
Training counts tokens before sharding, eval counts them after, so dividing in compute_loss inflated eval loss by the CP size.
torch's ring attention fails in backward on sm75 (2x T4, torch 2.10, pure torch probe without Unsloth), so fail at trainer init with a clear message.
…sses - DeviceMesh is SPMD: build the (dp_replicate, cp) mesh on every rank and take its cp submesh, instead of per-group meshes that hang once world_size > context_parallel_size. - Under CP, predictions come back as per-rank sequence shards; allow loss-only evaluation and refuse compute_metrics / predict(). - label_smoothing_factor and compute_loss_func drop labels before the model and recompute loss from sharded labels; refuse them under CP.
TRL chunked_nll calls the backbone directly, so it never sees the pre-shifted labels and re-shifts the sharded ones.
…lism accelerate before 1.10.0 ignores the cp mesh dim when sharding data, so CP peers would ring-attend over different examples. The attention hook drops the mask, which is only safe for right padding.
DoRA promotes Q/K/V to fp32, which keeps ring SDPA off the flash kernel; reuse the flash downcast (#1013) while CP is active. Higher-rank masks would be sharded on the wrong dim and then dropped.
accelerate's DeepSpeed data loader ignores the cp mesh dim and shards across every rank, and FSDP2 needs a parallelism_config alongside the mesh.
accelerate's DataLoaderDispatcher (default for iterable datasets) slices by world rank and ignores the cp dim. AcceleratorState is process-wide, so a later non-CP trainer must not inherit the CP mesh.
# Conflicts: # unsloth/models/llama.py
# Conflicts: # unsloth/models/llama.py
…ebinding trl.SFTConfig
…ft unset A PEFT model is not a PreTrainedModel, so the Trainer asks DDP for find_unused_parameters, which fails with Unsloth's reentrant gradient checkpointing (Expected to mark a variable ready only once). An explicit user value is kept.
…d_unused on transformers 4.x too On CUDA, autograd runs backward (and so Unsloth's reentrant checkpoint recompute) on its own device thread, where a ContextVar set on the training thread reads as unset: the recompute then picked flash attention / xformers over the local shard only. A module global is visible there. transformers 4.x rebuilds the DDP handler from ddp_find_unused_parameters when it wraps the model, so set the argument as well as the handler.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c00e723e95
ℹ️ 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".
| backend == "ulysses" | ||
| and bool(mixers) | ||
| and all(is_ulysses_gated_delta(m) for m, _ in mixers) | ||
| and all(type(m).__name__ in GATED_DELTA_ATTENTION_CLASSES for m in modules) | ||
| and _hybrid_config_blocker(model) is None |
There was a problem hiding this comment.
Handle unused sparse experts before enabling hybrid CP
When a supported Transformers 4.57 Qwen3-Next model retains its sparse MoE layers, this admission combines with _install_accelerator_state forcing ddp_find_unused_parameters=False. That Transformers implementation invokes only the experts selected by each local token shard, so any expert skipped on one CP rank has no autograd hook there and DDP can fail or hang during reduction on the next iteration; the new parity test avoids this by making every layer dense via mlp_only_layers. Reject this sparse implementation or retain unused-parameter detection for it before advertising Qwen3-Next CP support. Transformers 4.57.6 sparse routing implementation
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: hybrids whose MoE layers keep per-expert modules (the transformers 4.x Qwen3-Next layout) are now refused under CP, since an expert unused on one rank would stall DDP with find_unused_parameters off. Test added.
| text_config = getattr(config, "text_config", None) or config | ||
| if getattr(text_config, "output_router_logits", False): | ||
| # The load balancing loss is a product of per-sequence means, not a sum over shards. | ||
| return "the MoE router auxiliary loss (output_router_logits)" |
There was a problem hiding this comment.
Reject per-batch router auxiliary loss
When a batch explicitly contains output_router_logits=True while the model configuration keeps its default False, this initialization-only check admits the model and the forward still adds the shard-local nonlinear load-balancing loss. Fresh evidence after the config-level fix is that Qwen3-Next resolves the per-call argument before consulting the config, so CP silently optimizes the wrong objective in this valid input path; reject or force this input flag in the patched training step as well. Transformers 4.57.6 forward implementation
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: a batch carrying output_router_logits=True is refused in the CP input preparation, not just the config flag. Test added.
| and isinstance(position_ids, torch.Tensor) | ||
| and position_ids.ndim == 2 | ||
| and _positions_restart(position_ids, inputs.get("attention_mask")) |
There was a problem hiding this comment.
Shard Qwen3.5 position IDs along their sequence axis
When a Qwen3.5 caller supplies the model's native 3-D position IDs rather than the 2-D shorthand, this guard accepts them, after which _ulysses_scope slices dimension 1 even though their layout is [4, batch, sequence]. With the usual batch size 1 and CP size 2 this produces an empty position-ID batch while input_ids retains one row, and non-divisible sequence lengths can fail even earlier in the padding concatenation. Normalize these IDs to 2-D before CP or shard/pad their final dimension. Qwen3.5 native position-ID handling
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: position_ids that are not 2D [batch, seq] (e.g. Qwen3.5's [4, batch, seq]) are refused with a clear message instead of being sliced on the wrong axis. Test added.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
…lysses-linear-attn
…ysses-linear-attn
|
For reference: this overlaps with #12052, opened on 2026-09-26, about three weeks before this PR. #12052 adds Ulysses CP for Qwen3.5 Gated DeltaNet with the same split: projections on the local shard, an all-to-all to head shards, the full-sequence short conv and gated delta rule per head with the matching |
…inear MoE gate backward (#15880) ## 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 #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 ```python 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](#12052 (comment))). 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. --------- Co-authored-by: Backup Bot <[email protected]> Co-authored-by: Daniel Han <[email protected]>
**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]>
… 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]>
## 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](#12052 (comment))). 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 #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. --------- Co-authored-by: Backup Bot <[email protected]> Co-authored-by: Daniel Han <[email protected]>
Stacked on #13848 (Ulysses context parallel backend).
Hybrid models with Gated DeltaNet layers could not use context parallelism. Their linear attention runs a sequential scan (plus a short causal conv) over the whole sequence, so a sequence shard cannot run it alone, and the ring backend has no way to pass the recurrent state across shards.
This builds on the Ulysses backend. For each Gated DeltaNet layer the projections run on the local sequence shard. A single all-to-all then moves q, k, v, beta and the decay input from sequence shards to head shards. Each rank runs the short conv and the chunked gated delta rule over the full sequence for its heads, using the matching slice of the conv weight, A_log and dt_bias. A second all-to-all moves the output back before the gated norm and the output projection. Because the conv sees the full sequence, no halo exchange is needed. Packed batches pass global cu_seqlens / seq_idx from packed_seq_lengths to the conv and the scan, so documents crossing the shard seam stay isolated. If the bound kernels cannot take those arguments, packing under CP is refused instead of silently mixing documents.
The full attention layers of these models are Hugging Face modules. Under Ulysses they are routed through the existing Ulysses attention exchange and Unsloth's attention dispatcher (flash varlen for packed batches) via the ALL_ATTENTION_FUNCTIONS entry. Outside an active Ulysses step the entry passes straight through.
Constraints and refusals, checked on every rank at trainer init:
Testing:
Also, while context parallelism is active, the existing hybrid packing shim no longer derives boundaries from the local shard. Under CP it used to compute them from the shard and fail its kernel handshake on some ranks only. Packed batches that carry only restarting position_ids, without packed_seq_lengths, are refused under Ulysses.
End to end on 2 GPUs: FastModel + LoRA + SFTTrainer on a tiny Qwen3.5, with context_parallel_size = 2 and the ulysses backend vs a single GPU, for 6 steps, unpacked and with packing = True (documents crossing the shard seam).
Not covered here: Mamba-2 style hybrids, Qwen3-Next through FastModel, real weights, and more than 2 GPUs.