Repository navigation
Context parallel: Ulysses backend with packing and varlen attention - #13848
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.
[skip ci]
# Conflicts: # tests/test_context_parallel.py # unsloth/context_parallel.py # unsloth/trainer.py # unsloth/utils/attention_dispatch.py [skip ci]
|
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". |
|
@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: 81f099a9fb
ℹ️ 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".
|
|
||
|
|
||
| from .device_type import DEVICE_TYPE_TORCH | ||
| from .utils.ulysses import _document_positions, ulysses_head_plan |
There was a problem hiding this comment.
Avoid importing Ulysses through the eager utils package
When context_parallel is imported before unsloth.utils—as happens during a clean model bootstrap—this import initializes utils/__init__.py, which eagerly imports attention_dispatch; that module immediately executes from ..context_parallel import get_cp_manager, but get_cp_manager is not defined until later in this file. The resulting partially-initialized-module ImportError can prevent import unsloth from completing. Move this import below the manager accessor definitions or otherwise break the eager package cycle.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
unsloth.context_parallel is only reachable as a submodule of the unsloth package, so unsloth/init.py always runs first, and it imports unsloth.utils (and with it attention_dispatch) before anything imports context_parallel. By the time line 128 runs, unsloth.utils is fully initialised and the import is a lookup. The import order is fixed by the package, and every GPU run on this branch (ring and Ulysses parity harness, real SFT jobs) imports it this way.
|
Codex Review: Didn't find any major issues. 🚀 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". |
# Conflicts: # tests/utils/test_packing.py [skip ci]
…Next) (unslothai#13920) Stacked on unslothai#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: - linear_num_key_heads and linear_num_value_heads must be divisible by context_parallel_size; - the ring backend refuses linear attention layers and points to context_parallel_backend = "ulysses"; - Mamba-2 and other stateful mixers are refused for now; - eager attention, a non-default attention scale and attention dropout are refused under Ulysses. Testing: - CPU (gloo, 2 ranks): - CP=2 vs CP=1 gradient parity on tiny Qwen3.5 and Qwen3-Next hybrids, plus a negative control that runs the stock shard-local layer and must fail; - gate tests; - run on transformers 5.17 and 4.57.6. - 2 GPUs, tiny random models, fp32 and bf16: - CP=2 vs CP=1 loss and per-parameter gradients, for unpacked batches and for a packed row whose document crosses the shard seam (reference: each document run alone). - With exact torch kernels in fp32 the largest gradient error is 4e-4 relative (most parameters below 1e-5). - With the fla kernels all non-decay parameters are within 2.5e-2 in fp32 and 1.5e-2 in bf16. - The shard-local control fails with 15% to 74% gradient errors. 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). - Loss matches within 4e-6 and grad norm within 7e-4. - Every LoRA gradient at the first step matches within 7e-3. - A control that leaves the Gated DeltaNet layers on their shard shows 6% to 14% gradient errors. - Unsloth's compiled Qwen3.5 module still dispatches full attention through the attention registry, and the Ulysses path is confirmed to run on every step. Not covered here: Mamba-2 style hybrids, Qwen3-Next through FastModel, real weights, and more than 2 GPUs. --------- Co-authored-by: Dan Saunders <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…hai#13910) Stacked on unslothai#13848 (Ulysses context parallel, which stacks on unslothai#4257). Depends on unslothai#13865 (FSDP2 core), which is merged into this branch; the change itself is commit 39d648e. Context parallelism was DDP only: an FSDP2 launch with context_parallel_size > 1 was refused. This lets the two compose the way torchtitan does. The world is laid out as a (dp_shard, cp) mesh, FSDP2 shards parameters over dp_shard x cp flattened (accelerate's dp_shard_cp), and the sequence split plus the ring or Ulysses collectives stay on the cp submesh. CP peers hold different tokens of the same rows, so their gradients are reduced together with the data parallel ones, and the existing token count normalisation (pre-shard count divided by the CP size, loss scaled by the world size) stays exact because FSDP2 averages over the same D x N ranks DDP did. Usage is unchanged: SFTConfig(context_parallel_size = N) under an FSDP2 launch (UNSLOTH_FSDP2=1 torchrun ..., or an accelerate FSDP2 config); dp_shard is world size / N. accelerate's own ParallelismConfig(cp_size = N) is still refused. With cp_size > 1 accelerate attaches torch's context_parallel SDPA hooks in prepare(), transformers wraps each step in maybe_context_parallel and divides num_items_in_batch by the CP size, all of which Unsloth already does itself. Instead Unsloth installs a ParallelismConfig with dp_shard_size = D x N and cp_size = 1 next to its own mesh, so fsdp2_prepare_model shards over mesh["dp_shard_cp"] and the data loader gives CP peers the same batch (both read the same way since accelerate 1.10, the CP minimum). FSDP1, DeepSpeed and a ParallelismConfig with dp_replicate, tp or sp above 1 are refused on every rank before any collective. Tests - tests/test_context_parallel.py: FSDP2 accepted, mesh and config installed and restored by a later trainer, FSDP1 and extra dimensions refused. - tests/test_context_parallel_fsdp2_gloo.py: four gloo ranks on CPU, (dp_shard 2, cp 2). Mesh layout, accelerate's real data loader and fsdp2_prepare_model, and one patched training step through FSDP2 matching an unsharded model's gradients. - GPU accuracy on a tiny Llama with LoRA (3 steps, first-step gradients): (dp_shard, cp) = (1, 2) ring and Ulysses, fp32 and bf16, gradient accumulation 2, (2, 1) and (2, 2) ring and Ulysses on four GPUs all match the single GPU run (loss rel err <= 2.5e-5, min grad cosine >= 0.99988). Removing the count division moves loss and gradients by exactly 0.5, so the check can fail. Not covered: HSDP or TP with CP, packing / FA3 / FA4 / 4-bit bases under FSDP2 + CP, multi-node, timing. --------- Co-authored-by: Dan Saunders <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…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 #4257 (base is its branch; retarget to
mainonce it merges).Adds a Ulysses backend for context parallelism:
SFTConfig(context_parallel_size = N, context_parallel_backend = "ulysses"). Ring attention (#4257) shards the sequence inside SDPA, so it cannot run varlen kernels and turns packing / padding-free off. Ulysses instead exchanges sequence shards for head shards around attention, so attention sees the whole sequence forH / Nheads and the normal dispatcher runs unchanged: packing, padding-free, flash varlen, torch varlen, SDPA packed segments and xformers all keep working, and FA4 / FA3 engage wherever they engage without CP (torch's flash path).How it works:
unsloth/utils/ulysses.py: an autograd all-to-all ([B, H, T/N, D] -> [B, H/N, T, D]and back for the output; backward is the inverse exchange, no scaling). WhenN > n_kv_heads, K/V heads are repeated so every rank gets whole groups; autograd sums the copies' gradients back. Needsn_heads % N == 0andn_kv_headsandNdividing one another, checked on every rank at trainer init.run_attentionroutes through the exchange when a Ulysses manager is active, rebuildingAttentionConfig/AttentionContextfor the local heads and global length, so the existing backends and guards (flash_impl_allows, varlen int32 guard, padded tail segment) apply as is.ContextParallelManager(Ulysses): buildsshift_labelson the full sequence after masking packed document starts, keeps (or builds per-document)position_ids, pads to a multiple ofN, and keeps this rank's contiguous slice.packed_seq_lengthsstays global, since attention sees the whole sequence; the CP pad tail becomes its own segment.select_attention_backend, the fp32 downcast,UNSLOTH_CP_GQA, the trainer's packing / padding-free /eval_packingblock,sync_each_batch, and the sm80 requirement.Nonce.Tests:
tests/test_ulysses.py(CPU, gloo, 2 and 4 ranks): exchange order and round trip; forward and Q/K/V gradients against full-sequence attention for MHA, GQA, MQA with 2x and 4x KV replication, fp32 and fp64, odd lengths padded; packed documents crossing every shard seam; the realrun_attentionSDPA path for dense and packed rows.tests/test_context_parallel.py: contiguous sharding after the global shift, packed lengths kept global with per-document positions and masked document starts, ring refusing packed batches, routing through the exchange, head-count and sm80 checks at init.GPU parity (tiny random Llama / Qwen2 with LoRA r16, 3 steps, uneven rows with masked regions, one row leaving the second contiguous shard with no targets). Reference is CP=1 on the same rows; gates are loss relative error <= 5e-3 and per-parameter gradient cosine >= 0.999; the CP=1 rerun (A/A) sets the noise floor.
2 x Tesla T4 (sm75, fp32, torch 2.14.1), where ring CP is refused:
no_syncon the first micro-stepN2 x B200 (bf16 and fp32, torch 2.13; fp32 Q/K/V are downcast for the flash kernels here, so the spread is larger):
packing = TrueNNot covered here: model families other than the Llama forward (Llama, Qwen2, Gemma), more than 2 GPUs, DP x CP on GPU (CPU gloo covers the 2 x 2 loss algebra), FA3 on Hopper, and FA4 (could not be validated on torch 2.13 here: flash-attn-4 b19+ changed the return arity torch expects and b18's backward hangs).