Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Context parallel: Ulysses for DeepSeek (V2 / V3 MLA, V3.2 indexer, V4 sink attention) (#15882)

Immanuel Sun66ee929c0956
diff --git a/tests/test_context_parallel.py b/tests/test_context_parallel.py
index 3e2d7968619..2c3c6117693 100644
--- a/tests/test_context_parallel.py
+++ b/tests/test_context_parallel.py
@@ -1557,3 +1557,20 @@ def test_a_forwarded_cp_size_of_one_installs_no_wrappers(monkeypatch, forwarded)
Trainer(None, args = args, context_parallel_size = forwarded)
assert built == []
assert not any(hasattr(Trainer.__dict__[name], "__wrapped__") for name in _CP_METHODS)
+
+
+ "model_type, blocker",
+ [
+ ("kimi_linear", "KimiDeltaAttention"),
+ ("kimi_k3", "KimiDeltaAttention"),
+ ("minimax", "MiniMaxLightningAttention"),
+ ("deepseek_v32", "DeepseekV32Attention"),
+ ("llama", None),
+ ("minimax_m2", None),
+ ],
+)
+def test_ulysses_packing_blocker_classifies_model_id_strings(model_type, blocker):
+ # A model ID string has no modules yet: its config's model type must give the instance outcome,
+ # so SFT also turns eval_packing off for hybrids whose Ulysses mixers refuse packed batches.
+ assert cp.ulysses_packing_blocker("some/model-id", model_types = (model_type,)) == blocker
diff --git a/tests/test_parallel_capabilities_evidence.py b/tests/test_parallel_capabilities_evidence.py
index 70a2812d4dd..feb185f2ab3 100644
--- a/tests/test_parallel_capabilities_evidence.py
+++ b/tests/test_parallel_capabilities_evidence.py
@@ -353,6 +353,63 @@ def test_minimax_evidence_ids_are_real_parity_cases():
assert set(ids) <= set(parity.MODEL_CASES), (cell.name, ids)
[email protected]("family", ["deepseek_v2", "deepseek_v3", "deepseek_v32", "deepseek_v4"])
+ "mode, expert_lora",
+ [("full", False), ("lora", False), ("lora", True)],
+ ids = ["full", "lora", "lora+experts"],
+)
+def test_deepseek_moe_under_cp_follows_its_gloo_evidence(family, mode, expert_lora):
+ # tests/test_ulysses_deepseek_reference.py::test_deepseek_cp_matches_fp64_reference: cp 2 / 4, dp 2 x cp 2,
+ # HF checkpointing, sdpa and eager (V4: eager). Unsloth's checkpoint, FSDP2 x cp and the router loss stay refused.
+ kw = dict(
+ trainer = "sft",
+ family = family,
+ moe = True,
+ mode = mode,
+ expert_lora = expert_lora,
+ cp = 2,
+ cp_backend = "ulysses",
+ torch = (2, 13),
+ attention = "eager",
+ )
+ for extra in ({}, {"memory": "gc"}, {"attention": "sdpa"}, {"dp": 2}, {"cp": 4}):
+ if family == "deepseek_v4" and extra.get("attention") == "sdpa":
+ continue
+ query = caps.Query(**{**kw, **extra})
+ status, cell = caps.cell_status(query)
+ assert status == "supported" and "test_deepseek_cp_matches_fp64_reference" in cell.parity, (
+ extra,
+ cell,
+ )
+ caps.check(query)
+ refused = [
+ ({"memory": "unsloth_offload"}, "Unsloth checkpoint"),
+ ({"fsdp2": True}, "fsdp2_cp"),
+ ({"router_aux_loss": True}, "router auxiliary loss"),
+ ({"compile": "block"}, "no numeric parity"),
+ ({"mode": "qlora"}, "4-bit experts"),
+ ]
+ if family == "deepseek_v4":
+ refused.append(({"attention": "sdpa"}, "no numeric parity"))
+ for extra, match in refused:
+ with pytest.raises(NotImplementedError, match = match):
+ caps.check(caps.Query(**{**kw, **extra}))
+
+
+def test_deepseek_evidence_ids_are_real_parity_cases():
+ import re
+
+ parity = pytest.importorskip("tests.test_ulysses_deepseek_reference")
+ named = 0
+ for cell in caps.CELLS:
+ if cell.parity and "test_deepseek_cp_matches_fp64_reference[" in cell.parity:
+ ids = re.search(r"\[(.*)\]", cell.parity).group(1).split("|")
+ assert set(ids) <= set(parity.CASES), (cell.name, ids)
+ named += 1
+ assert named >= 12
+
+
def test_unsloth_checkpoint_keeps_an_unverified_moe_row_refused_under_strict(
clean_env, monkeypatch
):
diff --git a/tests/test_ulysses_deepseek.py b/tests/test_ulysses_deepseek.py
new file mode 100644
index 00000000000..498fc1b0d44
--- /dev/null
+++ b/tests/test_ulysses_deepseek.py
@@ -0,0 +1,671 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Ulysses context parallelism for DeepSeek on CPU gloo ranks: V2 / V3 MLA on main's generic route, V3.2 (DSA
+indexer) and V4 (sink attention) on their own forwards. transformers' own forwards are the single-rank reference."""
+
+import os
+import tempfile
+import types
+
+import pytest
+import torch
+import torch.distributed as dist
+import torch.multiprocessing as mp
+import torch.nn.functional as F
+
+import unsloth # noqa: F401
+from unsloth import context_parallel as cp
+from unsloth.utils import attention_dispatch as ad
+from unsloth.utils import ulysses_hybrid as uh
+
+transformers = pytest.importorskip("transformers")
+KINDS = [
+ kind
+ for kind, name in (
+ ("v2", "DeepseekV2Config"),
+ ("v3", "DeepseekV3Config"),
+ ("v32", "DeepseekV32Config"),
+ ("v4", "DeepseekV4Config"),
+ )
+ if hasattr(transformers, name)
+]
+if not KINDS:
+ pytest.skip("transformers without DeepSeek", allow_module_level = True)
+VOCAB = 128
+YARN = {
+ "rope_type": "yarn",
+ "rope_theta": 10000.0,
+ "factor": 4.0,
+ "beta_fast": 32,
+ "beta_slow": 1,
+ "mscale": 0.707,
+ "mscale_all_dim": 0.707,
+ "original_max_position_embeddings": 64,
+}
+
+
+def _mla(**extra):
+ # YaRN mscale makes the softmax scale non-default; value heads (16) are narrower than q / k (24).
+ return dict(
+ vocab_size = VOCAB,
+ hidden_size = 64,
+ intermediate_size = 128,
+ moe_intermediate_size = 32,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 4,
+ kv_lora_rank = 16,
+ q_lora_rank = 24,
+ qk_rope_head_dim = 8,
+ v_head_dim = 16,
+ qk_nope_head_dim = 16,
+ n_routed_experts = 4,
+ n_shared_experts = 1,
+ num_experts_per_tok = 2,
+ first_k_dense_replace = 1,
+ rope_parameters = YARN,
+ **extra,
+ )
+
+
+def _build(kind):
+ t = transformers
+ if kind == "v2":
+ return t.DeepseekV2ForCausalLM(t.DeepseekV2Config(**_mla()))
+ if kind == "v3":
+ return t.DeepseekV3ForCausalLM(t.DeepseekV3Config(**_mla(n_group = 1, topk_group = 1)))
+ if kind == "v32":
+ config = t.DeepseekV32Config(
+ **_mla(n_group = 1, topk_group = 1, index_topk = 4, index_head_dim = 16, index_n_heads = 2)
+ )
+ return t.DeepseekV32ForCausalLM(config)
+ config = t.DeepseekV4Config(
+ vocab_size = VOCAB,
+ hidden_size = 64,
+ intermediate_size = 128,
+ moe_intermediate_size = 32,
+ num_hidden_layers = 3,
+ num_attention_heads = 4,
+ num_key_value_heads = 1,
+ head_dim = 32,
+ rope_head_dim = 16,
+ q_lora_rank = 32,
+ o_lora_rank = 32,
+ o_groups = 2,
+ num_local_experts = 4,
+ num_experts_per_tok = 2,
+ sliding_window = 8,
+ index_n_heads = 2,
+ index_head_dim = 16,
+ index_topk = 2,
+ layer_types = [
+ "sliding_attention",
+ "compressed_sparse_attention",
+ "heavily_compressed_attention",
+ ],
+ mlp_layer_types = ["hash_moe", "moe", "moe"],
+ compress_rates = {"compressed_sparse_attention": 4, "heavily_compressed_attention": 8},
+ )
+ model = t.DeepseekV4ForCausalLM(config)
+ with torch.no_grad():
+ g = torch.Generator().manual_seed(0)
+ for module in model.modules():
+ # Zero-initialised sinks / position biases would hide slicing mistakes.
+ if hasattr(module, "sinks"):
+ module.sinks.copy_(0.1 * torch.randn(module.sinks.shape, generator = g))
+ if hasattr(module, "position_bias"):
+ module.position_bias.copy_(
+ 0.05 * torch.randn(module.position_bias.shape, generator = g)
+ )
+ if hasattr(module, "tid2eid"):
+ ids = torch.arange(VOCAB)
+ module.tid2eid[:, 0] = ids % 4
+ module.tid2eid[:, 1] = (ids + 1) % 4
+ return model
+
+
+def _model(kind):
+ torch.manual_seed(0)
+ model = _build(kind).float().train()
+ # The V3.2 / V4 Ulysses forwards reproduce transformers' eager attention, and Unsloth runs
+ # DeepSeek-V4 eager only; V2 / V3 go through the attention registry, so sdpa is exercised.
+ model.config._attn_implementation = "eager" if kind in ("v32", "v4") else "sdpa"
+ model.config.use_cache = False
+ for module in model.modules():
+ # Grouped expert kernels may touch CUDA in a forked CPU worker.
+ if hasattr(module, "set_experts_implementation"):
+ module.set_experts_implementation("eager")
+ return model
+
+
+def _manager(size, rank):
+ manager = object.__new__(cp.ContextParallelManager)
+ manager.size = size
+ manager.backend = "ulysses"
+ manager.mesh = types.SimpleNamespace(get_group = lambda: None, get_local_rank = lambda: rank)
+ return manager
+
+
+def _loss(logits, shift_labels, count):
+ return (
+ F.cross_entropy(
+ logits.float().flatten(0, 1), shift_labels.flatten(), ignore_index = -100, reduction = "sum"
+ )
+ / count
+ )
+
+
+def _parity_worker(rank, world, kind, control):
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ model = _model(kind)
+ # transformers' V3.2 / V4 indexers are not invariant to appending tokens (top-k over zero-score
+ # ties, or over not-yet-causal compressed blocks), so the reference must see exactly the length
+ # CP runs: 16 needs no padding at cp = 2. V4's rate-8 compressed layers then see two blocks.
+ seq = 16 if kind in ("v32", "v4") else 15
+ ids = torch.randint(0, VOCAB, (2, seq), generator = torch.Generator().manual_seed(1))
+ shift = F.pad(ids, (0, 1), value = -100)[:, 1:]
+ count = shift.ne(-100).sum()
+ _loss(model(input_ids = ids, use_cache = False).logits, shift, count).backward()
+ reference = {n: p.grad.clone() for n, p in model.named_parameters() if p.grad is not None}
+ model.zero_grad(set_to_none = True)
+
+ manager = _manager(world, rank)
+ manager.attach_attention_hooks(model)
+ if control:
+ for module in model.modules():
+ if getattr(module, "_unsloth_cp_orig_forward", None) is not None:
+ module.forward = module._unsloth_cp_orig_forward
+ calls = []
+ if not control:
+ # The new path provably runs: once per layer, no silent fallback to the stock forward.
+ owner, fn_name = uh, "_ulysses_hf_attention"
+ if kind in ("v32", "v4"):
+ from unsloth.utils import ulysses_deepseek as ud
+ owner, fn_name = ud, f"ulysses_deepseek_{kind}_forward"
+ real = getattr(owner, fn_name)
+
+ def counted(*args, **kwargs):
+ calls.append(1)
+ return real(*args, **kwargs)
+
+ setattr(owner, fn_name, counted)
+ inputs = {"input_ids": ids.clone(), "labels": ids.clone()}
+ manager._prepare_inputs(inputs)
+ with manager.apply(inputs):
+ out = model(
+ input_ids = inputs["input_ids"], position_ids = inputs["position_ids"], use_cache = False
+ )
+ _loss(out.logits, inputs["shift_labels"], count).backward()
+ if not control:
+ assert len(calls) == model.config.num_hidden_layers, (kind, len(calls))
+ for name, param in model.named_parameters():
+ if name not in reference:
+ continue
+ grad = torch.zeros_like(param) if param.grad is None else param.grad
+ dist.all_reduce(grad)
+ torch.testing.assert_close(grad, reference[name], rtol = 1e-4, atol = 1e-5, msg = name)
+
+
+def _spawn(fn, world, *args):
+ # Fork: a spawned child would re-import unsloth without the conftest CUDA spoof.
+ if "fork" not in mp.get_all_start_methods():
+ pytest.skip("needs the fork start method")
+ with tempfile.TemporaryDirectory() as d:
+ mp.start_processes(
+ _entry,
+ args = (world, os.path.join(d, "init"), fn, args),
+ nprocs = world,
+ join = True,
+ start_method = "fork",
+ )
+
+
+def _entry(rank, world, init_file, fn, args):
+ torch.set_num_threads(1)
+ dist.init_process_group("gloo", init_method = f"file://{init_file}", rank = rank, world_size = world)
+ try:
+ fn(rank, world, *args)
+ finally:
+ dist.destroy_process_group()
+
+
[email protected]("kind", KINDS)
+def test_ulysses_deepseek_gradients_match_one_rank(kind):
+ _spawn(_parity_worker, 2, kind, False)
+
+
[email protected]("kind", [k for k in KINDS if k in ("v32", "v4")])
+def test_ulysses_deepseek_chunked_attention_matches(kind, monkeypatch):
+ # Chunks of 4 query rows: the checkpointed chunk loop instead of one dense block.
+ monkeypatch.setenv("UNSLOTH_CP_ATTN_CHUNK", "4")
+ _spawn(_parity_worker, 2, kind, False)
+
+
[email protected]("v4" not in KINDS, reason = "transformers without DeepSeek-V4")
+def test_shard_local_deepseek_v4_is_wrong():
+ # Negative control: the stock V4 forward on a shard sees neither earlier keys nor full blocks.
+ with pytest.raises(Exception, match = "AssertionError"):
+ _spawn(_parity_worker, 2, "v4", True)
+
+
[email protected]("v4" not in KINDS, reason = "transformers without DeepSeek-V4")
+def test_deepseek_v4_gates():
+ model = _model("v4")
+ # Its own Ulysses forward builds the sliding / compressed masks; the ring backend cannot.
+ assert cp._unsupported_attention(model.config, "ulysses") is None
+ assert cp._unsupported_attention(model.config, "ring") is not None
+ assert cp._supports_context_parallel(model, "ulysses")
+ assert not cp._supports_context_parallel(model, "ring")
+
+
[email protected]("kind", KINDS)
+def test_ulysses_deepseek_route(kind):
+ # V2 / V3 MLA (YaRN scale, value heads narrower than q / k) are plain registry attention: main's generic
+ # route runs their own attention function. V3.2 / V4 must take their own forward instead: on the generic
+ # route the indexer / compressor would see one shard and the rebuilt causal mask would drop the top-k.
+ model = _model(kind)
+ _manager(2, 0).attach_attention_hooks(model)
+ layers = [m for n, m in model.named_modules() if n.endswith("self_attn")]
+ assert len(layers) == model.config.num_hidden_layers
+ for module in layers:
+ own = getattr(module, "_unsloth_cp_orig_forward", None) is not None
+ generic = getattr(module, "_unsloth_cp_ulysses_attention", False)
+ assert (own, generic) == ((True, False) if kind in ("v32", "v4") else (False, True)), kind
+ # transformers 4.x builds per-expert modules, which the model check refuses under CP.
+ per_expert = any(
+ isinstance(getattr(m, "experts", None), torch.nn.ModuleList) for m in model.modules()
+ )
+ assert cp._supports_context_parallel(model, "ulysses") is not per_expert
+
+
[email protected]("kind", KINDS)
+def test_deepseek_model_checks_as_main_does(kind):
+ # SFT accepts every DeepSeek generation under Ulysses; DPO / GRPO refuse it like any generic Hugging Face
+ # attention model; ring and the router auxiliary loss stay refused.
+ model = _model(kind)
+ if any(isinstance(getattr(m, "experts", None), torch.nn.ModuleList) for m in model.modules()):
+ # transformers 4.x: per-expert modules stall DDP's reduction under CP (find_unused_parameters off).
+ with pytest.raises(NotImplementedError, match = "per-expert modules"):
+ cp._check_cp_model(model, 2, "ulysses", allow_hybrids = True)
+ return
+ cp._check_cp_model(model, 2, "ulysses", allow_hybrids = True)
+ with pytest.raises(NotImplementedError, match = "verified for SFTTrainer"):
+ cp._check_cp_model(model, 2, "ulysses", allow_hybrids = False)
+ with pytest.raises(NotImplementedError):
+ cp._check_cp_model(model, 2, "ring", allow_hybrids = True)
+ model.config.output_router_logits = True
+ with pytest.raises(NotImplementedError, match = "router auxiliary loss"):
+ cp._check_cp_model(model, 2, "ulysses", allow_hybrids = True)
+
+
[email protected]("wrap", ["none", "checkpoint"])
+def test_chunked_attention_gradients_match_and_nest_in_checkpointing(wrap, monkeypatch):
+ # The chunked V4 / V3.2 attention recomputes chunks inside one autograd op, so it must give the
+ # dense gradients and also run inside activation checkpointing of the whole layer.
+ from torch.utils.checkpoint import checkpoint
+
+ from unsloth.utils import ulysses_deepseek as ud
+
+ g = torch.Generator().manual_seed(0)
+ q = torch.randn(1, 2, 12, 8, generator = g)
+ kv = torch.randn(1, 1, 15, 8, generator = g)
+ sinks = torch.randn(2, generator = g)
+ bias = torch.zeros(1, 1, 12, 3)
+ bias[..., 2] = float("-inf")
+ k = torch.randn(1, 2, 12, 8, generator = g)
+ v = torch.randn(1, 2, 12, 6, generator = g)
+ topk = torch.randint(0, 12, (1, 12, 4), generator = g)
+ topk[..., 0] = torch.arange(12) # like the indexer, every query keeps at least one causal key
+
+ def sink(q, kv, sinks):
+ return ud._sink_attention(q, kv, bias, sinks, 5, 0.3, 0.0, True)
+
+ def mla(q, k, v):
+ return ud._sparse_mla_attention(q, k, v, topk, 0.3, 0.0, True)
+
+ for fn, inputs in ((sink, (q, kv, sinks)), (mla, (q, k, v))):
+ grads = []
+ for chunk in ("100", "4"):
+ monkeypatch.setenv("UNSLOTH_CP_ATTN_CHUNK", chunk)
+ leaves = [x.clone().requires_grad_() for x in inputs]
+ out = (
+ checkpoint(fn, *leaves, use_reentrant = False)
+ if wrap == "checkpoint"
+ else fn(*leaves)
+ )
+ (out.square().sum()).backward()
+ grads.append([x.grad for x in leaves])
+ for dense, chunked in zip(*grads):
+ torch.testing.assert_close(chunked, dense, rtol = 1e-5, atol = 1e-6)
+
+
+class _PackingStubTrainer:
+ def __init__(
+ self,
+ model = None,
+ args = None,
+ **kwargs,
+ ):
+ self.model = model
+ self.args = args
+
+
+class _KwargsModel(torch.nn.Module):
+ def __init__(self, attention):
+ super().__init__()
+ self.self_attn = attention
+
+ def forward(
+ self,
+ input_ids = None,
+ **kwargs,
+ ):
+ return None
+
+
[email protected]("kind", [k for k in KINDS if k in ("v32", "v4")])
+def test_ulysses_sft_turns_padding_free_off_for_attention_that_refuses_packing(kind, monkeypatch):
+ """V3.2 / V4 Ulysses forwards refuse packed batches, so SFT must not pick padding-free under
+ Ulysses CP: the automatic choice turned it on and the first CP step raised (Colab L4, i6)."""
+ from types import SimpleNamespace
+
+ import unsloth.trainer as trainer_module
+
+ for name in ("enable_padding_free_metadata", "enable_sample_packing"):
+ monkeypatch.setattr(trainer_module, name, lambda model, trainer: None)
+ monkeypatch.delenv("UNSLOTH_RETURN_LOGITS", raising = False)
+ module = SimpleNamespace(SFTTrainer = type("SFTTrainer", (_PackingStubTrainer,), {}))
+ trainer_module._patch_sft_trainer_auto_packing(module)
+
+ name = {"v32": "DeepseekV32Attention", "v4": "DeepseekV4Attention"}[kind]
+ refusing = _KwargsModel(type(name, (torch.nn.Module,), {})())
+ plain = _KwargsModel(type("DeepseekV3Attention", (torch.nn.Module,), {})())
+
+ def config(backend):
+ return SimpleNamespace(
+ packing = False,
+ padding_free = None,
+ max_length = 64,
+ context_parallel_size = 2,
+ context_parallel_backend = backend,
+ eval_packing = True,
+ )
+
+ args = config("ulysses")
+ module.SFTTrainer(model = refusing, args = args)
+ assert args.padding_free is False and args.packing is False
+ assert args.eval_packing is False
+ # Ulysses attention that takes packed batches keeps the automatic padding-free choice.
+ args = config("ulysses")
+ module.SFTTrainer(model = plain, args = args)
+ assert args.padding_free is not False
+ args = config("ulysses")
+ args.context_parallel_size = 1
+ module.SFTTrainer(model = refusing, args = args)
+ assert args.padding_free is not False
+
+
[email protected]("name", ["DeepseekV32Attention", "DeepseekV4Attention"])
+def test_ulysses_deepseek_forward_runs_eager_inside_compiled_layers(name, monkeypatch):
+ """Unsloth compiles each decoder layer as one region; traced, the V3.2 / V4 Ulysses forwards (list
+ all_gather, the sequence gather, the no_grad indexer top-k) segfaulted the first CP=2 SFT step on L4
+ (torch 2.14 and 2.8). They must run eagerly inside a compiled layer."""
+ from unsloth.utils import ulysses_deepseek as ud
+
+ seen = []
+
+ def fake_forward(module, hidden_states, *args, group, **kwargs):
+ seen.append(torch.compiler.is_compiling())
+ return hidden_states * 2, None
+
+ target = (
+ "ulysses_deepseek_v4_forward"
+ if name == "DeepseekV4Attention"
+ else "ulysses_deepseek_v32_forward"
+ )
+ monkeypatch.setattr(ud, target, fake_forward)
+ attention = type(
+ name,
+ (torch.nn.Module,),
+ {"forward": lambda self, hidden_states, **kw: (hidden_states, None)},
+ )()
+ manager = types.SimpleNamespace(backend = "ulysses", group = None, packed_seq_lengths = None)
+ ud.wrap_deepseek_attention_forward(attention, lambda: manager)
+
+ def layer(x):
+ return attention(x)[0] + 1
+
+ torch._dynamo.reset()
+ out = torch.compile(layer, backend = "eager")(torch.ones(2, 3))
+ torch.testing.assert_close(out, torch.full((2, 3), 3.0))
+ assert seen == [False], seen
+
+
+def _ddp_worker(rank, world, kind):
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ model = _model(kind)
+ seq = 16
+ ids = torch.randint(0, VOCAB, (2, seq), generator = torch.Generator().manual_seed(1))
+ count = F.pad(ids, (0, 1), value = -100)[:, 1:].ne(-100).sum()
+ manager = _manager(world, rank)
+ manager.attach_attention_hooks(model)
+ # The CP trainer turns DDP's find_unused_parameters off (reentrant checkpointing).
+ ddp = torch.nn.parallel.DistributedDataParallel(model, find_unused_parameters = False)
+ for _ in range(2):
+ inputs = {"input_ids": ids.clone(), "labels": ids.clone()}
+ manager._prepare_inputs(inputs)
+ with manager.apply(inputs):
+ out = ddp(
+ input_ids = inputs["input_ids"], position_ids = inputs["position_ids"], use_cache = False
+ )
+ _loss(out.logits, inputs["shift_labels"], count).backward()
+ indexer = [n for n, p in model.named_parameters() if ".indexer." in n]
+ assert indexer and all(model.get_parameter(n).grad is None for n in indexer), indexer
+
+
[email protected]("kind", [k for k in KINDS if k in ("v32", "v4")])
+def test_ulysses_deepseek_ddp_steps_with_trainable_indexer(kind):
+ """The DSA indexer only picks keys (a discrete top-k), so its weights never get a gradient. With
+ LoRA on them (V3.2 indexer.wq_b, V4 compressor.indexer.q_b_proj) and DDP's find_unused_parameters
+ off under CP, the second CP=2 SFT step on L4 failed with "Expected to have finished reduction"."""
+ _spawn(_ddp_worker, 2, kind)
+
+
[email protected]("kind", [k for k in KINDS if k in ("v32", "v4")])
+def test_ulysses_deepseek_layers_stay_out_of_block_compile(kind):
+ """The eager Ulysses forward is a graph break inside each decoder layer's compiled region."""
+ from unsloth.models import _block_compile as bc
+
+ model = _model(kind)
+ _manager(2, 0).attach_attention_hooks(model)
+ layers = model.model.layers
+ assert all(layer.__dict__.get("_unsloth_block_mode") == bc._OFF for layer in layers)
+
+
+_FAILING_FAKE_LIB = []
+
+
+def _failing_fake_op():
+ """An op whose fake (compile-time) kernel raises, called from an autograd Function: what fp32
+ experts hit on CUDA (torch._grouped_mm has no fp32 kernel for fake tensors)."""
+ if not _FAILING_FAKE_LIB:
+ lib = torch.library.Library("unsloth_test_cp_block", "FRAGMENT")
+ lib.define("ident(Tensor x) -> Tensor")
+ lib.impl("ident", lambda x: x.clone(), "CompositeExplicitAutograd")
+
+ def fake(x):
+ raise RuntimeError("no fake kernel")
+
+ torch.library.register_fake("unsloth_test_cp_block::ident", fake, lib = lib)
+ _FAILING_FAKE_LIB.append(lib)
+
+ class Ident(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x):
+ return torch.ops.unsloth_test_cp_block.ident(x)
+
+ @staticmethod
+ def backward(ctx, grad):
+ return grad
+
+ return Ident.apply
+
+
+def _block_compile_checkpoint_worker(rank, world):
+ from unsloth.models import _block_compile as bc
+
+ # Other test modules set these at import (e.g. UNSLOTH_COMPILE_DISABLE=1) and spawned ranks inherit them.
+ for key in ("UNSLOTH_BLOCK_COMPILE", "UNSLOTH_COMPILE_DISABLE", "UNSLOTH_FORCE_FLOAT32"):
+ os.environ.pop(key, None)
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ model = _model("v32")
+ # Layer 0 is dense, layer 1 MoE; only the MoE layer fails to compile after the attention break.
+ ident = _failing_fake_op()
+ moe = model.model.layers[1].mlp
+ moe_forward = moe.forward
+ moe.forward = lambda hidden_states: ident(moe_forward(hidden_states))
+ available = torch.cuda.is_available
+ torch.cuda.is_available = lambda: True # Unsloth compiles decoder layers on CUDA only
+ try:
+ assert bc.patch_block_compile(model) == ["DeepseekV32DecoderLayer"]
+ finally:
+ torch.cuda.is_available = available
+ manager = _manager(world, rank)
+ manager.attach_attention_hooks(model)
+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": False})
+ ids = torch.randint(0, VOCAB, (2, 16), generator = torch.Generator().manual_seed(1))
+ count = F.pad(ids, (0, 1), value = -100)[:, 1:].ne(-100).sum()
+ for _ in range(2):
+ inputs = {"input_ids": ids.clone(), "labels": ids.clone()}
+ manager._prepare_inputs(inputs)
+ with manager.apply(inputs):
+ out = model(
+ input_ids = inputs["input_ids"], position_ids = inputs["position_ids"], use_cache = False
+ )
+ _loss(out.logits, inputs["shift_labels"], count).backward()
+
+
[email protected]("v32" not in KINDS, reason = "transformers without DeepSeek-V3.2")
+def test_ulysses_deepseek_checkpointing_with_block_compile():
+ """V3.2 fp32 CP=2 SFT failed with CheckpointError (62 vs 61 saved tensors): the eager Ulysses
+ forward split each compiled decoder layer, the MoE layer's post-attention part failed to compile,
+ and the dense layer that ran it compiled recomputed it eagerly in backward."""
+ _spawn(_block_compile_checkpoint_worker, 2)
+
+
[email protected]("packing", [False, True])
[email protected]("kind", [k for k in KINDS if k in ("v3", "v32", "v4")])
+def test_ulysses_sft_string_model_gets_the_instance_outcome(kind, packing, monkeypatch, caplog):
+ """A model ID string defers the module walk, so the Ulysses packing check must classify the
+ resolved config instead: V3.2 kept packed / padding-free batches from a string and the
+ attention wrapper raised NotImplementedError on the first CP step, while an instance trained."""
+ import logging
+ from types import SimpleNamespace
+
+ import unsloth.trainer as trainer_module
+
+ for name in ("enable_padding_free_metadata", "enable_sample_packing"):
+ monkeypatch.setattr(trainer_module, name, lambda model, trainer: None)
+ monkeypatch.delenv("UNSLOTH_RETURN_LOGITS", raising = False)
+ built = _build(kind)
+
+ class _StringStub(_PackingStubTrainer):
+ def __init__(
+ self,
+ model = None,
+ args = None,
+ **kwargs,
+ ):
+ super().__init__(model = built if isinstance(model, str) else model, args = args)
+
+ module = SimpleNamespace(SFTTrainer = type("SFTTrainer", (_StringStub,), {}))
+ trainer_module._patch_sft_trainer_auto_packing(module)
+
+ def config(cp_size):
+ return SimpleNamespace(
+ packing = packing,
+ padding_free = None,
+ max_length = 64,
+ context_parallel_size = cp_size,
+ context_parallel_backend = "ulysses",
+ eval_packing = True,
+ )
+
+ with tempfile.TemporaryDirectory() as path:
+ built.config.save_pretrained(path)
+ outcomes = []
+ for model in (path, built):
+ args = config(2)
+ caplog.clear()
+ with caplog.at_level(logging.WARNING):
+ module.SFTTrainer(model = model, args = args)
+ outcomes.append((args.packing, args.padding_free is False, args.eval_packing))
+ if kind == "v32" and packing and model is path:
+ assert "DeepseekV32Attention refuses packed batches" in caplog.text
+ assert outcomes[0] == outcomes[1], outcomes
+ if kind in ("v32", "v4"):
+ assert outcomes[0] == (False, True, False)
+ else:
+ assert outcomes[0][1] is False
+ args = config(1)
+ module.SFTTrainer(model = path, args = args)
+ if kind != "v4":
+ assert args.padding_free is not False
+
+
+def _load_ulysses_deepseek_copy(path, name):
+ import importlib.util
+ import sys
+
+ spec = importlib.util.spec_from_file_location(f"unsloth.utils.{name}", path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ try:
+ spec.loader.exec_module(module)
+ finally:
+ sys.modules.pop(spec.name, None)
+ return module
+
+
[email protected]("device", ["cuda", "xpu"])
+def test_ulysses_deepseek_imports_on_torch_without_amp_custom_fwd(device, monkeypatch):
+ """torch.amp.custom_fwd / custom_bwd are 2.4+, and this module is imported by plain `import
+ unsloth` (models/llama.py -> context_parallel). A class-body decorator using them raised
+ AttributeError at import on torch 2.1 - 2.3; the module must fall back to torch.cuda.amp."""
+ import unsloth.device_type as device_type
+ from unsloth.utils import ulysses_deepseek as ud
+
+ seen = []
+
+ def fake_amp(kind):
+ def factory(
+ *args,
+ device_type = None,
+ **kwargs,
+ ):
+ seen.append((kind, device_type))
+ return lambda fn: fn
+
+ return factory
+
+ monkeypatch.setattr(device_type, "DEVICE_TYPE_TORCH", device)
+ monkeypatch.setattr(torch.amp, "custom_fwd", fake_amp("fwd"), raising = False)
+ monkeypatch.setattr(torch.amp, "custom_bwd", fake_amp("bwd"), raising = False)
+ modern = _load_ulysses_deepseek_copy(ud.__file__, "_ud_amp_modern")
+ assert seen == [("fwd", device), ("bwd", device)]
+
+ monkeypatch.delattr(torch.amp, "custom_fwd")
+ monkeypatch.delattr(torch.amp, "custom_bwd")
+ # torch 2.1 - 2.3: torch.cuda.amp holds the real decorators (newer ones forward to torch.amp).
+ legacy_fwd, legacy_bwd = (lambda fn: fn), (lambda fn: fn)
+ monkeypatch.setattr(torch.cuda.amp, "custom_fwd", legacy_fwd)
+ monkeypatch.setattr(torch.cuda.amp, "custom_bwd", legacy_bwd)
+ legacy = _load_ulysses_deepseek_copy(ud.__file__, "_ud_amp_legacy")
+ assert legacy._custom_fwd is legacy_fwd and legacy._custom_bwd is legacy_bwd
+ for module in (modern, legacy):
+ assert issubclass(module._ChunkedSinkAttention, torch.autograd.Function)
+ assert issubclass(module._ChunkedSparseMLA, torch.autograd.Function)
diff --git a/tests/test_ulysses_deepseek_reference.py b/tests/test_ulysses_deepseek_reference.py
new file mode 100644
index 00000000000..eb403e07390
--- /dev/null
+++ b/tests/test_ulysses_deepseek_reference.py
@@ -0,0 +1,654 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""DeepSeek Ulysses context parallelism against independent fp64 single-process references, on CPU gloo
+ranks: V2 / V3 MLA (YaRN softmax scale, narrower value heads) on main's generic route, V3.2's global top-k
+indexer, V4 sliding / CSA / HCA sink attention at release compression ratios, sdpa / eager, HF checkpointing, right-padded batches, a rank with no
+labels, a label across the shard seam, CP = 2 / 4 and DP 2 x CP 2, LoRA (also on the fused experts), one AdamW step, and negative
+controls that must fail."""
+
+import math
+import os
+import tempfile
+import types
+
+import pytest
+import torch
+import torch.distributed as dist
+import torch.multiprocessing as mp
+import torch.nn.functional as F
+
+import unsloth
+from unsloth import context_parallel as cp
+from unsloth.utils import attention_dispatch as ad
+from unsloth.utils import ulysses_deepseek as ud
+from unsloth.utils import ulysses_hybrid as uh
+
+transformers = pytest.importorskip("transformers")
+# Each arm must import the unsloth tree that holds this test file.
+_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+assert os.path.abspath(unsloth.__file__).startswith(_ROOT + os.sep), unsloth.__file__
+if not all(
+ hasattr(transformers, n) for n in ("DeepseekV3Config", "DeepseekV32Config", "DeepseekV4Config")
+):
+ pytest.skip("transformers without DeepSeek V3 / V3.2 / V4", allow_module_level = True)
+
+VOCAB = 96
+# DeepSeek-V3's released YaRN parameters (factor 40, mscale 1.0): softmax scale = mscale^2 / sqrt(d).
+YARN = {
+ "rope_type": "yarn",
+ "rope_theta": 10000.0,
+ "factor": 40.0,
+ "beta_fast": 32,
+ "beta_slow": 1,
+ "mscale": 1.0,
+ "mscale_all_dim": 1.0,
+ "original_max_position_embeddings": 64,
+}
+
+
+def _yarn_scale(head_dim):
+ mscale = 0.1 * 1.0 * math.log(40.0) + 1.0
+ return head_dim**-0.5 * mscale * mscale
+
+
+def _named(name):
+ return lambda detail: f"{name}: {detail}"
+
+
+def _spawn(fn, world, *args):
+ if "fork" not in mp.get_all_start_methods():
+ pytest.skip("needs the fork start method")
+ with tempfile.TemporaryDirectory() as d:
+ mp.start_processes(
+ _entry,
+ args = (world, os.path.join(d, "init"), fn, args),
+ nprocs = world,
+ join = True,
+ start_method = "fork",
+ )
+
+
+def _entry(rank, world, init_file, fn, args):
+ torch.set_num_threads(1)
+ dist.init_process_group("gloo", init_method = f"file://{init_file}", rank = rank, world_size = world)
+ try:
+ fn(rank, world, *args)
+ finally:
+ dist.destroy_process_group()
+
+
+def _cp_groups(world, cp_size):
+ """Contiguous CP groups (rank // cp_size = DP replica); every rank creates every group."""
+ mine = None
+ for start in range(0, world, cp_size):
+ ranks = list(range(start, start + cp_size))
+ group = dist.new_group(ranks)
+ if dist.get_rank() in ranks:
+ mine = group
+ return mine
+
+
+def _manager(cp_size, group):
+ manager = object.__new__(cp.ContextParallelManager)
+ manager.size = cp_size
+ manager.backend = "ulysses"
+ local = dist.get_rank(group)
+ manager.mesh = types.SimpleNamespace(get_group = lambda: group, get_local_rank = lambda: local)
+ return manager
+
+
+# 1. Model-level parity: V2 / V3 (main's generic route), V3.2 (indexer), V4 (sliding / CSA / HCA).
+
+
+def _mla(**extra):
+ return dict(
+ vocab_size = VOCAB,
+ hidden_size = 64,
+ intermediate_size = 96,
+ moe_intermediate_size = 32,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 4,
+ kv_lora_rank = 16,
+ q_lora_rank = 24,
+ qk_rope_head_dim = 8,
+ v_head_dim = 16,
+ qk_nope_head_dim = 16,
+ n_routed_experts = 4,
+ n_shared_experts = 1,
+ num_experts_per_tok = 2,
+ first_k_dense_replace = 1,
+ n_group = 1,
+ topk_group = 1,
+ rope_parameters = YARN,
+ **extra,
+ )
+
+
+def _build(kind, v4_topk):
+ t = transformers
+ if kind == "v2":
+ return t.DeepseekV2ForCausalLM(t.DeepseekV2Config(**_mla()))
+ if kind == "v3":
+ return t.DeepseekV3ForCausalLM(t.DeepseekV3Config(**_mla()))
+ if kind == "v32":
+ # 8 indexer heads keep exact zero-score ties (all ReLUs zero) improbable; top-6 of up to 24 keys.
+ config = t.DeepseekV32Config(**_mla(index_topk = 6, index_head_dim = 16, index_n_heads = 8))
+ return t.DeepseekV32ForCausalLM(config)
+ # Release ratios: CSA 4, HCA 128, sliding window 128 (DeepSeek-V4 config defaults).
+ config = t.DeepseekV4Config(
+ vocab_size = VOCAB,
+ hidden_size = 64,
+ intermediate_size = 64,
+ moe_intermediate_size = 32,
+ num_hidden_layers = 3,
+ num_attention_heads = 4,
+ num_key_value_heads = 1,
+ head_dim = 32,
+ rope_head_dim = 16,
+ q_lora_rank = 32,
+ o_lora_rank = 16,
+ o_groups = 2,
+ num_local_experts = 4,
+ num_experts_per_tok = 2,
+ sliding_window = 128,
+ # 32 indexer heads: an all-zero ReLU score (a tie whose top-k pick depends on the row
+ # length, also without CP) is improbable; the release uses 64.
+ index_n_heads = 32,
+ index_head_dim = 16,
+ index_topk = v4_topk,
+ layer_types = [
+ "sliding_attention",
+ "compressed_sparse_attention",
+ "heavily_compressed_attention",
+ ],
+ mlp_layer_types = ["hash_moe", "moe", "moe"],
+ compress_rates = {"compressed_sparse_attention": 4, "heavily_compressed_attention": 128},
+ )
+ model = t.DeepseekV4ForCausalLM(config)
+ with torch.no_grad():
+ g = torch.Generator().manual_seed(0)
+ for module in model.modules():
+ if hasattr(module, "sinks"):
+ module.sinks.copy_(0.5 * torch.randn(module.sinks.shape, generator = g))
+ if hasattr(module, "position_bias"):
+ module.position_bias.copy_(
+ 0.3 * torch.randn(module.position_bias.shape, generator = g)
+ )
+ if hasattr(module, "tid2eid"):
+ ids = torch.arange(VOCAB)
+ module.tid2eid[:, 0] = ids % 4
+ module.tid2eid[:, 1] = (ids + 1) % 4
+ return model
+
+
+def _model(
+ kind,
+ v4_topk = 16,
+ lora = False,
+ attn = None,
+ checkpoint = False,
+):
+ torch.manual_seed(0)
+ model = _build(kind, v4_topk).double().train()
+ if attn is None:
+ attn = "eager" if kind in ("v32", "v4") else "sdpa"
+ model.config._attn_implementation = attn
+ model.config.use_cache = False
+ for module in model.modules():
+ if hasattr(module, "set_experts_implementation"):
+ module.set_experts_implementation("eager")
+ if checkpoint:
+ # HF gradient checkpointing: every decoder layer (and its CP forward) is recomputed in backward.
+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": False})
+ if lora:
+ from peft import LoraConfig, get_peft_model
+
+ targets = (
+ ["q_b_proj", "kv_proj", "o_b_proj"]
+ if kind == "v4"
+ else ["q_b_proj", "kv_a_proj_with_mqa", "kv_b_proj", "o_proj"]
+ )
+ extra = {}
+ if lora == "experts":
+ # LoRA on the routed experts too: the fused 3D expert weights.
+ extra["target_parameters"] = ["experts.gate_up_proj", "experts.down_proj"]
+ model = get_peft_model(
+ model, LoraConfig(r = 4, lora_alpha = 8, target_modules = targets, **extra)
+ )
+ g = torch.Generator().manual_seed(5)
+ with torch.no_grad():
+ for name, p in model.named_parameters():
+ if "lora_B" in name: # nonzero B: the adapter changes the forward
+ p.copy_(0.05 * torch.randn(p.shape, generator = g, dtype = p.dtype))
+ return model
+
+
+def _batch(seq, lengths, labels_scheme, cp_size):
+ g = torch.Generator().manual_seed(1)
+ ids = torch.randint(1, VOCAB, (len(lengths), seq), generator = g)
+ mask = torch.zeros_like(ids)
+ for row, n in enumerate(lengths):
+ mask[row, :n] = 1
+ ids = ids * mask # right padding with pad id 0
+ labels = ids.masked_fill(mask == 0, -100)
+ if labels_scheme == "late_rank_empty":
+ # The last CP rank of the padded row gets no labels; the label predicting the token right
+ # after the first seam is kept so a label crosses the seam.
+ padded = seq + (-seq) % cp_size
+ start = padded - padded // cp_size
+ labels[:, start:] = -100
+ labels[:, padded // cp_size] = ids[:, padded // cp_size].masked_fill(
+ mask[:, padded // cp_size] == 0, -100
+ )
+ return ids, mask, labels
+
+
+def _sum_ce(logits, shift_labels):
+ return F.cross_entropy(
+ logits.flatten(0, 1), shift_labels.flatten(), ignore_index = -100, reduction = "sum"
+ )
+
+
+def _controls(model, kind, control, monkey):
+ if control is None:
+ return
+ if control == "shard_local":
+ for module in model.modules():
+ if getattr(module, "_unsloth_cp_orig_forward", None) is not None:
+ module.forward = module._unsloth_cp_orig_forward
+ elif control == "default_scale":
+ for module in model.modules():
+ if hasattr(module, "qk_head_dim") and hasattr(module, "scaling"):
+ module.scaling = module.qk_head_dim**-0.5
+ elif control == "dropped_window":
+ real = ud._sink_attention
+ monkey(ud, "_sink_attention", lambda q, kv, bb, s, w, *a: real(q, kv, bb, s, None, *a))
+ elif control == "wrong_offset":
+ real = ud.ulysses_deepseek_v4_forward
+
+ def shard_positions(
+ module,
+ *args,
+ position_ids = None,
+ group = None,
+ **kw,
+ ):
+ return real(
+ module, *args, position_ids = position_ids - position_ids[:, :1], group = group, **kw
+ )
+
+ monkey(ud, "ulysses_deepseek_v4_forward", shard_positions)
+ elif control == "local_topk":
+ real = ud._v32_global_topk
+
+ def local_topk(indexer, hidden, q_resid, pe, group, module):
+ # Shard-local selection: each rank scores only its own keys, then indices are offset.
+ local = real(indexer, hidden, q_resid, pe, _SOLO[0], module)
+ local = local + dist.get_rank(group) * hidden.shape[1]
+ parts = [torch.empty_like(local) for _ in range(dist.get_world_size(group))]
+ dist.all_gather(parts, local.contiguous(), group = group)
+ return torch.cat(parts, dim = 1)
+
+ monkey(ud, "_v32_global_topk", local_topk)
+ else:
+ raise ValueError(control)
+
+
+_SOLO = [None]
+
+
+def _parity_worker(rank, world, case):
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ if case.get("chunk"):
+ os.environ["UNSLOTH_CP_ATTN_CHUNK"] = str(case["chunk"])
+ kind, cp_size = case["kind"], case["cp"]
+ dp = world // cp_size
+ group = _cp_groups(world, cp_size)
+ solos = [dist.new_group([r]) for r in range(world)]
+ _SOLO[0] = solos[rank]
+ patched = []
+
+ def monkey(obj, name, value):
+ patched.append((obj, name, getattr(obj, name)))
+ setattr(obj, name, value)
+
+ try:
+ _parity_body(rank, world, case, kind, cp_size, dp, group, monkey)
+ finally:
+ for obj, name, value in reversed(patched):
+ setattr(obj, name, value)
+
+
+def _parity_body(rank, world, case, kind, cp_size, dp, group, monkey):
+ import copy
+
+ model = _model(
+ kind,
+ case.get("v4_topk", 16),
+ case.get("lora", False),
+ case.get("attn"),
+ case.get("checkpoint", False),
+ )
+ if kind in ("v2", "v3"):
+ # The MLA cases exercise what the generic route must carry: a non-default softmax scale and value
+ # heads narrower than query / key heads.
+ attn = next(m for n, m in model.named_modules() if n.endswith("self_attn"))
+ assert abs(attn.scaling * attn.qk_head_dim**0.5 - 1) > 0.1, attn.scaling
+ assert attn.v_head_dim < attn.qk_head_dim
+ if kind == "v3":
+ assert abs(attn.scaling - _yarn_scale(attn.qk_head_dim)) < 1e-12, attn.scaling
+ reference = copy.deepcopy(model)
+ seq, lengths = case["seq"], case["lengths"]
+ ids, mask, labels = _batch(seq, lengths, case.get("labels", "all"), cp_size)
+ shift = F.pad(labels, (0, 1), value = -100)[:, 1:]
+ count = shift.ne(-100).sum()
+ assert count > 0
+
+ # transformers runs the MoE router, the V3.2 / V4 indexer scores and V4's compressor gate softmax
+ # in fp32, so even the reference moves at ~1e-8 with the batch shape.
+ tol = dict(rtol = 1e-6, atol = 1e-6)
+ ref_logits = reference(input_ids = ids, attention_mask = mask, use_cache = False).logits
+ (_sum_ce(ref_logits, shift) / count).backward()
+ # Valid tokens must not depend on the padding: each row alone, unpadded.
+ with torch.no_grad():
+ for row, n in enumerate(lengths):
+ alone = reference(input_ids = ids[row : row + 1, :n], use_cache = False).logits
+ torch.testing.assert_close(
+ ref_logits[row, :n].detach(), alone[0], msg = _named("ref pad"), **tol
+ )
+
+ rows = list(range(rank // cp_size, len(lengths), dp))
+ manager = _manager(cp_size, group)
+ manager.attach_attention_hooks(model)
+ _controls(model, kind, case.get("control"), monkey)
+ calls = []
+ # Engagement: the CP path runs once per layer (twice under checkpointing), no silent fallback.
+ owner, fn_name = (
+ (ud, f"ulysses_deepseek_{kind}_forward")
+ if kind in ("v32", "v4")
+ else (uh, "_ulysses_hf_attention")
+ )
+ real_fn = getattr(owner, fn_name)
+
+ def counted(*args, **kwargs):
+ calls.append(1)
+ return real_fn(*args, **kwargs)
+
+ monkey(owner, fn_name, counted)
+ inputs = {
+ "input_ids": ids[rows].clone(),
+ "attention_mask": mask[rows].clone(),
+ "labels": labels[rows].clone(),
+ }
+ with manager.apply(inputs):
+ out = model(
+ input_ids = inputs["input_ids"],
+ attention_mask = inputs["attention_mask"],
+ position_ids = inputs["position_ids"],
+ use_cache = False,
+ )
+ local_ce = _sum_ce(out.logits, inputs["shift_labels"])
+ (local_ce / count).backward()
+ if case.get("control") is None:
+ runs = 2 if case.get("checkpoint") else 1
+ layers = model.config.num_hidden_layers
+ assert len(calls) == runs * layers, (len(calls), runs, layers)
+ if case.get("labels") == "late_rank_empty" and dist.get_rank(group) == cp_size - 1:
+ assert inputs["shift_labels"].ne(-100).sum() == 0
+ logits = torch.cat(dist_all_gather(out.logits.detach(), group), dim = 1)
+ for i, row in enumerate(rows):
+ n = lengths[row]
+ torch.testing.assert_close(
+ logits[i, :n], ref_logits[row, :n].detach(), msg = _named("logits"), **tol
+ )
+ with torch.no_grad():
+ alone = reference(input_ids = ids[row : row + 1, :n], use_cache = False).logits
+ torch.testing.assert_close(logits[i, :n], alone[0], msg = _named("unpadded"), **tol)
+ total = local_ce.detach().clone()
+ dist.all_reduce(total)
+ torch.testing.assert_close(total / count, _sum_ce(ref_logits.detach(), shift) / count, **tol)
+ # Same fp32 ops; chunked attention also accumulates full-sequence gradients in fp32.
+ gtol = dict(rtol = 1e-5, atol = 1e-8)
+
+ # Gradients: None stays None, zero stays zero, values match; then one AdamW step.
+ ref_params = dict(reference.named_parameters())
+ for name, param in model.named_parameters():
+ has = torch.tensor([0.0 if param.grad is None else 1.0])
+ dist.all_reduce(has)
+ grad = torch.zeros_like(param) if param.grad is None else param.grad
+ dist.all_reduce(grad)
+ ref_grad = ref_params[name].grad
+ if ref_grad is None:
+ assert has.item() == 0, f"{name}: reference grad is None, CP produced one"
+ param.grad = None
+ continue
+ assert has.item() > 0, f"{name}: CP grad is None, reference has one"
+ torch.testing.assert_close(grad, ref_grad, msg = _named(name), **gtol)
+ param.grad = grad
+ # Adam's first step is lr * g / (|g| + eps): with eps = 1e-8 the fp32 noise of tiny gradients
+ # (V4's Sinkhorn hyper-connections run in fp32) is amplified to ~lr. eps = 1e-3 bounds that at
+ # ~1e-8 while weight decay on a zero-instead-of-None gradient (lr * wd * |p| ~ 1e-4) still fails.
+ lr = dict(lr = 1e-2, weight_decay = 0.1, eps = 1e-3)
+ atol = dict(rtol = 1e-6, atol = 1e-7)
+ torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], **lr).step()
+ torch.optim.AdamW([p for p in reference.parameters() if p.requires_grad], **lr).step()
+ for name, param in model.named_parameters():
+ torch.testing.assert_close(param, ref_params[name], msg = _named(f"adamw {name}"), **atol)
+
+
+def dist_all_gather(t, group):
+ parts = [torch.empty_like(t) for _ in range(dist.get_world_size(group))]
+ dist.all_gather(parts, t.contiguous(), group = group)
+ return parts
+
+
+# V3.2: 23 tokens pads to 24 under CP; row 1 holds 17 valid tokens, so CP ranks see unequal counts.
+V32 = dict(kind = "v32", seq = 23, lengths = [23, 17])
+# V4 at release ratios: 397 tokens -> 3 full HCA blocks (128) + partial, ~99 CSA blocks, window 128;
+# the CP = 2 seam (199) sits inside HCA block 1, the CP = 4 seams (100, 200, 300) inside blocks 0-2.
+V4 = dict(kind = "v4", seq = 397, lengths = [397, 290])
+V3 = dict(kind = "v3", seq = 23, lengths = [23, 17])
+V2 = dict(V3, kind = "v2")
+
+CASES = {
+ "v2_cp2": dict(V2, cp = 2, world = 2),
+ "v2_cp4": dict(V2, cp = 4, world = 4),
+ "v2_dp2cp2": dict(V2, cp = 2, world = 4),
+ "v2_cp2_eager_checkpoint": dict(V2, cp = 2, world = 2, attn = "eager", checkpoint = True),
+ "v2_cp2_lora": dict(V2, cp = 2, world = 2, lora = True),
+ "v2_cp2_lora_experts": dict(V2, cp = 2, world = 2, lora = "experts"),
+ "v3_cp2": dict(V3, cp = 2, world = 2),
+ "v3_cp4": dict(V3, cp = 4, world = 4),
+ "v3_dp2cp2": dict(V3, cp = 2, world = 4),
+ "v3_cp2_eager_checkpoint": dict(V3, cp = 2, world = 2, attn = "eager", checkpoint = True),
+ "v3_cp2_lora": dict(V3, cp = 2, world = 2, lora = True),
+ "v3_cp2_lora_experts": dict(V3, cp = 2, world = 2, lora = "experts"),
+ "v32_cp2": dict(V32, cp = 2, world = 2),
+ "v32_cp2_chunk1": dict(V32, cp = 2, world = 2, chunk = 1),
+ "v32_cp2_chunk5": dict(V32, cp = 2, world = 2, chunk = 5),
+ "v32_cp4_late_rank_empty": dict(V32, cp = 4, world = 4, labels = "late_rank_empty"),
+ "v32_dp2cp2": dict(V32, cp = 2, world = 4),
+ "v32_cp2_lora": dict(V32, cp = 2, world = 2, lora = True),
+ "v32_cp2_lora_experts": dict(V32, cp = 2, world = 2, lora = "experts"),
+ "v32_cp2_sdpa_checkpoint": dict(V32, cp = 2, world = 2, attn = "sdpa", checkpoint = True),
+ "v4_cp2": dict(V4, cp = 2, world = 2),
+ "v4_cp2_topk512": dict(V4, cp = 2, world = 2, v4_topk = 512),
+ "v4_cp2_chunk1": dict(V4, cp = 2, world = 2, chunk = 1),
+ "v4_cp2_chunk37": dict(V4, cp = 2, world = 2, chunk = 37),
+ "v4_cp4_late_rank_empty": dict(V4, cp = 4, world = 4, labels = "late_rank_empty", chunk = 37),
+ "v4_dp2cp2": dict(V4, cp = 2, world = 4, chunk = 64),
+ "v4_cp2_lora": dict(V4, cp = 2, world = 2, lora = True, chunk = 50),
+ "v4_cp2_lora_experts": dict(V4, cp = 2, world = 2, lora = "experts", chunk = 50),
+ "v4_cp2_checkpoint": dict(V4, cp = 2, world = 2, checkpoint = True, chunk = 64),
+}
+
+CONTROLS = {
+ "v32_local_topk": dict(V32, cp = 2, world = 2, control = "local_topk"),
+ "v32_default_scale": dict(V32, cp = 2, world = 2, control = "default_scale"),
+ "v2_default_scale": dict(V2, cp = 2, world = 2, control = "default_scale"),
+ "v3_default_scale": dict(V3, cp = 2, world = 2, control = "default_scale"),
+ "v4_shard_local": dict(V4, cp = 2, world = 2, control = "shard_local"),
+ "v4_dropped_window": dict(V4, cp = 2, world = 2, control = "dropped_window"),
+ "v4_wrong_offset": dict(V4, cp = 2, world = 2, control = "wrong_offset"),
+}
+
+
[email protected]("name", list(CASES))
+def test_deepseek_cp_matches_fp64_reference(name):
+ case = CASES[name]
+ _spawn(_parity_worker, case["world"], case)
+
+
[email protected]("name", list(CONTROLS))
+def test_deepseek_cp_negative_control_fails(name):
+ case = CONTROLS[name]
+ with pytest.raises(Exception, match = "AssertionError"):
+ _spawn(_parity_worker, case["world"], case)
+
+
+# 2. V3.2 indexer: global causal top-k vs transformers' full-sequence indexer.
+
+
+def _topk_worker(rank, world, seq):
+ model = _model("v32")
+ attn = model.model.layers[0].self_attn
+ modeling = __import__(type(attn).__module__, fromlist = ["x"])
+ g = torch.Generator().manual_seed(7)
+ hidden = torch.randn(2, seq, 64, generator = g, dtype = torch.float64)
+ pos = torch.arange(seq)[None].expand(2, -1)
+ pe = model.model.rotary_emb(hidden, pos)
+ q_resid = attn.q_a_layernorm(attn.q_a_proj(hidden)).detach()
+ causal = torch.full((2, seq, seq), torch.finfo(torch.float64).min, dtype = torch.float64).triu(1)
+ ref = attn.indexer(hidden, q_resid, pe, causal, pos)
+
+ # Reference scores, to prove the compared rows are not tied at the top-k boundary.
+ idx = attn.indexer
+ q = idx.wq_b(q_resid).view(2, seq, idx.n_heads, idx.head_dim)
+ k = idx.k_norm(idx.wk(hidden)).unsqueeze(2)
+ r = idx.qk_rope_head_dim
+ qr, kr = modeling.apply_rotary_pos_emb(q[..., :r], k[..., :r], *pe, unsqueeze_dim = 2)
+ q = torch.cat([qr, q[..., r:]], -1).float()
+ k = torch.cat([kr, k[..., r:]], -1).squeeze(2).float()
+ scores = F.relu(torch.matmul(q, k.transpose(-1, -2).unsqueeze(1)) * idx.softmax_scale)
+ w = idx.weights_proj(hidden).float() * idx.n_heads**-0.5
+ s = torch.matmul(w.unsqueeze(-2), scores).squeeze(-2)
+
+ local = seq // world
+ sl = slice(rank * local, (rank + 1) * local)
+ pe_local = tuple(t[:, sl] for t in pe)
+ got = ud._v32_global_topk(
+ idx, hidden[:, sl], q_resid[:, sl], pe_local, dist.group.WORLD, modeling
+ )
+ assert got.shape == ref.shape
+ topk = idx.index_topk
+ short = 0
+ for b in range(2):
+ for t in range(seq):
+ want = {int(i) for i in ref[b, t] if int(i) <= t}
+ have = {int(i) for i in got[b, t] if int(i) <= t}
+ if t + 1 <= topk:
+ short += 1
+ assert want == have == set(range(t + 1)), (b, t)
+ continue
+ row = s[b, t, : t + 1].sort(descending = True).values
+ assert row[topk - 1] - row[topk] > 1e-6, f"tie at ({b}, {t}): pick another seed"
+ assert want == have, (b, t, want, have)
+ assert short == 2 * topk # early queries with fewer causal keys than top-k were exercised
+
+
[email protected]("world", [2, 4])
+def test_v32_global_topk_matches_full_sequence_indexer(world):
+ _spawn(_topk_worker, world, 24)
+
+
+# 3. Chunked sink attention custom backward vs an independent fp64 reference.
+
+
+def _reference_sink(q, kv, block_bias, sinks, window, scaling):
+ rows, seq = q.shape[2], q.shape[2]
+ pos = torch.arange(seq)
+ diff = pos[:, None] - pos[None, :]
+ keep = (diff >= 0) & (diff < window)
+ logits = torch.matmul(q, kv.transpose(-1, -2)) * scaling
+ dense = logits[..., :seq].masked_fill(~keep, float("-inf"))
+ full = torch.cat([dense, logits[..., seq:] + block_bias], -1)
+ full = torch.cat([full, sinks.view(1, -1, 1, 1).expand(q.shape[0], -1, rows, 1)], -1)
+ probs = torch.softmax(full, -1)[..., :-1]
+ return torch.matmul(probs, kv).transpose(1, 2)
+
+
+def _sink_case(chunk, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_CP_ATTN_CHUNK", chunk)
+ g = torch.Generator().manual_seed(0)
+ seq, blocks, window, scaling = 40, 5, 9, 0.21
+ q = torch.randn(2, 3, seq, 8, generator = g, dtype = torch.float64)
+ kv = torch.randn(2, 1, seq + blocks, 8, generator = g, dtype = torch.float64)
+ sinks = torch.randn(3, generator = g, dtype = torch.float64)
+ # Block w is visible to query t once (t + 1) // 8 > w (HCA rule), plus one indexer-dropped block.
+ t = torch.arange(seq)[:, None]
+ bias = torch.where(torch.arange(blocks)[None] < (t + 1) // 8, 0.0, float("-inf"))
+ bias = bias.to(torch.float64).expand(2, 1, seq, blocks).clone()
+ bias[1, :, 30:, 1] = float("-inf")
+ grad_out = torch.randn(2, seq, 3, 8, generator = g, dtype = torch.float64)
+ a = [x.clone().requires_grad_() for x in (q, kv, sinks)]
+ b = [x.clone().requires_grad_() for x in (q, kv, sinks)]
+ out = ud._sink_attention(a[0], a[1], bias, a[2], window, scaling, 0.0, True)
+ ref = _reference_sink(b[0], b[1], bias, b[2], window, scaling)
+ torch.testing.assert_close(out, ref, rtol = 1e-12, atol = 1e-12)
+ (out * grad_out).sum().backward()
+ (ref * grad_out).sum().backward()
+ # q's rows are written once; kv and sinks accumulate over chunks in fp32 by design.
+ exact = dict(rtol = 1e-12, atol = 1e-12)
+ tol = exact if int(chunk) >= seq else dict(rtol = 1e-6, atol = 1e-7)
+ for name, x, y in zip(("q", "kv", "sinks"), a, b):
+ torch.testing.assert_close(
+ x.grad, y.grad, msg = _named(name), **(exact if name == "q" else tol)
+ )
+
+
+# 1 and 7 run the chunked autograd op (7 leaves a partial last chunk); 40 = the sequence and 4096
+# take the plain autograd path.
[email protected]("chunk", ["1", "7", "40", "4096"])
+def test_chunked_sink_attention_backward_matches_reference(chunk, monkeypatch):
+ _sink_case(chunk, monkeypatch)
+
+
[email protected]("chunk", ["1", "7"])
+def test_chunked_sink_attention_dropping_a_chunk_is_wrong(chunk, monkeypatch):
+ real = ud._recompute_rows
+
+ def drop_first(chunk_size, full_seq, run, grad_out, *args):
+ grad_out = grad_out.clone()
+ grad_out[:, :chunk_size] = 0
+ return real(chunk_size, full_seq, run, grad_out, *args)
+
+ monkeypatch.setattr(ud, "_recompute_rows", drop_first)
+ with pytest.raises(AssertionError):
+ _sink_case(chunk, monkeypatch)
+
+
+# 4. The own-mask exemption covers only layer types and the window.
+
+
[email protected]("kind", ["v32", "v4"])
+def test_own_mask_exemption_is_narrow(kind):
+ config = _model(kind).config
+ # generic = True is what _check_cp_model passes for them (their attention calls the registry).
+ for generic in (False, True):
+ config = _model(kind).config
+ assert cp._unsupported_attention(config, "ulysses", generic = generic) is None
+ assert cp._unsupported_attention(config, "ring", generic = generic) is not None
+ config.attn_logit_softcapping = 30.0
+ assert (
+ cp._unsupported_attention(config, "ulysses", generic = generic)
+ == "attention logit softcapping"
+ )
+ config.attn_logit_softcapping = None
+ config.attention_chunk_size = 64
+ assert cp._unsupported_attention(config, "ulysses", generic = generic) == "chunked attention"
+ config.attention_chunk_size = None
+ config.layer_types = ["chunked_attention"] * config.num_hidden_layers
+ assert cp._unsupported_attention(config, "ulysses", generic = generic) is not None
diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.py
index ef762071465..64ba402ad87 100644
--- a/unsloth/context_parallel.py
+++ b/unsloth/context_parallel.py
@@ -111,6 +111,80 @@ def context_parallel_options(config) -> tuple:
return size, backend, rotate_method
+# Their Ulysses forwards (utils/ulysses_deepseek.py) build their own sliding / compressed masks, so
+# only these layer types and the window are exempt; chunked attention and softcap still refuse.
+_ULYSSES_OWN_MASK_LAYER_TYPES = {
+ "deepseek_v32": ("deepseek_sparse_attention",),
+ "deepseek_v4": (
+ "sliding_attention",
+ "compressed_sparse_attention",
+ "heavily_compressed_attention",
+ ),
+}
+
+
+# Model types whose Ulysses mixers refuse packed batches, for a model ID string (no modules to walk yet).
+_ULYSSES_HYBRID_PACKING_MODEL_TYPES = {
+ "kimi_linear": "KimiDeltaAttention",
+ "kimi_k3": "KimiDeltaAttention",
+ "minimax": "MiniMaxLightningAttention",
+}
+
+
+def ulysses_packing_blocker(model, model_types = ()) -> Optional[str]:
+ """Class name of the first module whose Ulysses forward refuses packed batches (Kimi delta,
+ MiniMax Lightning, DeepSeek V3.2 / V4 attention), else None. SFT keeps padding-free off for them.
+ A model ID string (TRL builds it later) is classified by its config's model types instead."""
+ from .utils.ulysses_deepseek import (
+ DEEPSEEK_ULYSSES_ATTENTION_CLASSES,
+ DEEPSEEK_ULYSSES_MODEL_TYPES,
+ )
+ from .utils.ulysses_hybrid import is_ulysses_kimi_delta, is_ulysses_lightning
+
+ if not isinstance(model, torch.nn.Module):
+ for model_type in model_types or ():
+ if model_type in DEEPSEEK_ULYSSES_MODEL_TYPES:
+ return DEEPSEEK_ULYSSES_MODEL_TYPES[model_type]
+ if model_type in _ULYSSES_HYBRID_PACKING_MODEL_TYPES:
+ return _ULYSSES_HYBRID_PACKING_MODEL_TYPES[model_type]
+ return None
+ for module in model.modules():
+ if (
+ type(module).__name__ in DEEPSEEK_ULYSSES_ATTENTION_CLASSES
+ or is_ulysses_kimi_delta(module)
+ or is_ulysses_lightning(module)
+ ):
+ return type(module).__name__
+ return None
+
+
+def _ddp_ignore_indexer(model, attn_name: str, attention) -> None:
+ # The DSA indexer only picks keys (a discrete top-k), so its weights never get a gradient. CP
+ # turns DDP's find_unused_parameters off, so trainable indexer weights (LoRA on V3.2 wq_b, V4
+ # q_b_proj) would stall the gradient reduction: DDP leaves them out instead.
+ names = [
+ f"{attn_name}.{sub}.{p}"
+ for sub, module in attention.named_modules()
+ if sub.rsplit(".", 1)[-1] == "indexer"
+ for p, _ in module.named_parameters()
+ ]
+ if names:
+ ignored = set(getattr(model, "_ddp_params_and_buffers_to_ignore", ()))
+ model._ddp_params_and_buffers_to_ignore = sorted(ignored.union(names))
+
+
+def _keep_layer_out_of_block_compile(model, attn_name: str) -> None:
+ # The eager Ulysses forward is a graph break; the resume function is shared by all layers, so one
+ # layer failing to compile it (fp32 MoE grouped_mm) makes earlier checkpointed layers recompute it
+ # eagerly: CheckpointError (62 vs 61 saved tensors, V3.2 fp32 CP = 2).
+ parent = attn_name.rpartition(".")[0]
+ if not parent:
+ return
+ from .models._block_compile import _OFF
+
+ model.get_submodule(parent).__dict__["_unsloth_block_mode"] = _OFF
+
+
def _model_heads(model):
config = getattr(model, "config", None)
text = getattr(config, "text_config", None) or config
@@ -164,7 +238,14 @@ def _unsupported_attention(
for c in configs:
if c is None:
continue
+ own_mask = (
+ _ULYSSES_OWN_MASK_LAYER_TYPES.get(getattr(c, "model_type", None))
+ if backend == "ulysses"
+ else None
+ )
layer_types = getattr(c, "layer_types", None)
+ if own_mask and layer_types:
+ layer_types = [t for t in layer_types if t not in own_mask]
if layer_types and any(t not in allowed for t in layer_types):
kinds = sorted({t for t in layer_types if t not in allowed})
hint = (
@@ -175,14 +256,15 @@ def _unsupported_attention(
return f"{', '.join(kinds)} layers{hint}"
# Any positive window, even with use_sliding_window off: Unsloth's masks read it directly.
sliding_window = getattr(c, "sliding_window", None)
- if not windows_ok and (
+ if not (own_mask or windows_ok) and (
(isinstance(sliding_window, int) and sliding_window > 0)
or getattr(c, "use_sliding_window", None) is True
):
return "sliding window attention"
if getattr(c, "attention_chunk_size", None):
return "chunked attention"
- if not windows_ok and getattr(c, "attn_logit_softcapping", None):
+ # DeepSeek's own forwards apply no softcap, so it refuses there even on the generic route.
+ if (own_mask or not windows_ok) and getattr(c, "attn_logit_softcapping", None):
return "attention logit softcapping"
return None
@@ -208,6 +290,10 @@ def get_cp_manager() -> Optional["ContextParallelManager"]:
from .device_type import DEVICE_TYPE_TORCH
from .utils.ulysses import _document_positions, ulysses_head_plan
+from .utils.ulysses_deepseek import (
+ DEEPSEEK_ULYSSES_ATTENTION_CLASSES,
+ wrap_deepseek_attention_forward,
+)
from .utils.ulysses_hybrid import (
GATED_DELTA_ATTENTION_CLASSES,
check_ulysses_mixer_heads,
@@ -432,11 +518,15 @@ def _uses_unsloth_attention(model, rl = False) -> bool:
def _generic_hf_attention(model) -> bool:
"""Every attention layer is a Hugging Face forward through ALL_ATTENTION_FUNCTIONS, so Ulysses can run the
- model's own attention function (scaling, softcap, sliding window, sinks) after the exchange."""
+ model's own attention function (scaling, softcap, sliding window, sinks) after the exchange. DeepSeek V3.2 /
+ V4 attention gets its own Ulysses forward instead (utils/ulysses_deepseek.py) under the same model checks."""
if not isinstance(model, torch.nn.Module) or _stateful_mixers(model):
return False
modules = _attention_modules(model)
- return bool(modules) and all(is_hf_registry_attention(m) for m in modules)
+ return bool(modules) and all(
+ is_hf_registry_attention(m) or type(m).__name__ in DEEPSEEK_ULYSSES_ATTENTION_CLASSES
+ for m in modules
+ )
def _supports_context_parallel(
@@ -554,7 +644,14 @@ class ContextParallelManager:
# Fast forwards exchange inside run_attention; other HF layers run their attention after the exchange.
generic = not _uses_unsloth_attention(model)
for name, module in model.named_modules():
- if name.endswith("self_attn") and (
+ if (
+ name.endswith("self_attn")
+ and type(module).__name__ in DEEPSEEK_ULYSSES_ATTENTION_CLASSES
+ ):
+ wrap_deepseek_attention_forward(module, get_cp_manager)
+ _ddp_ignore_indexer(model, name, module)
+ _keep_layer_out_of_block_compile(model, name)
+ elif name.endswith("self_attn") and (
type(module).__name__ in GATED_DELTA_ATTENTION_CLASSES
or (generic and is_hf_registry_attention(module))
):
@@ -1522,7 +1619,7 @@ def _check_cp_model(
"Unsloth: context parallelism supports Unsloth's fast attention (Llama-style, Qwen3, Mistral, Granite, "
"Cohere) with either backend, and with Ulysses any Hugging Face attention model (attention through "
"ALL_ATTENTION_FUNCTIONS, e.g. MiniMax-M2) and the Qwen3-Next / Qwen3.5 Gated DeltaNet, Kimi-Linear and "
- "MiniMax-M1 Lightning hybrids."
+ "MiniMax-M1 Lightning hybrids, and DeepSeek V3.2 (DSA indexer) / V4 (compressed sink attention)."
)
diff --git a/unsloth/parallel_capabilities.py b/unsloth/parallel_capabilities.py
index 60995583aab..246309d7f03 100644
--- a/unsloth/parallel_capabilities.py
+++ b/unsloth/parallel_capabilities.py
@@ -812,7 +812,10 @@ MOE_FAMILIES = (
"qwen3_moe",
"qwen3_5_moe",
"gpt_oss",
+ "deepseek_v2",
"deepseek_v3",
+ "deepseek_v32",
+ "deepseek_v4",
"kimi_linear",
"minimax",
"minimax_m2",
@@ -882,6 +885,36 @@ _KIMI_EAGER = "eager: remote code, no compiled region"
# rows, fp64 against one process, every gradient and one AdamW step. HF checkpointing only.
_MINIMAX = "tests/test_ulysses_minimax_parity.py::test_minimax_model_matches_upstream"
_MINIMAX_EAGER = "eager: block compile not measured for this family"
+# DeepSeek (transformers' DeepseekV2 / V3 / V32 / V4ForCausalLM, fused experts): V2 / V3 MLA (YaRN softmax scale,
+# narrower value heads) on the generic route, V3.2's global DSA indexer top-k and V4's sliding / CSA / HCA sink
+# attention on their own Ulysses forwards; right padded rows, fp64 against one process, every gradient (None vs
+# zero) and one AdamW step. HF checkpointing only. V4 runs eager attention only.
+_DEEPSEEK = "tests/test_ulysses_deepseek_reference.py::test_deepseek_cp_matches_fp64_reference"
+_DEEPSEEK_EAGER = "eager: block compile not measured for this family"
+_DEEPSEEK_CASES = {
+ "deepseek_v2": {
+ "full": "v2_cp2|v2_cp4|v2_dp2cp2|v2_cp2_eager_checkpoint",
+ "lora": "v2_cp2_lora",
+ "lora+experts": "v2_cp2_lora_experts",
+ },
+ "deepseek_v3": {
+ "full": "v3_cp2|v3_cp4|v3_dp2cp2|v3_cp2_eager_checkpoint",
+ "lora": "v3_cp2_lora",
+ "lora+experts": "v3_cp2_lora_experts",
+ },
+ "deepseek_v32": {
+ "full": "v32_cp2|v32_cp4_late_rank_empty|v32_dp2cp2|v32_cp2_sdpa_checkpoint",
+ "lora": "v32_cp2_lora",
+ "lora+experts": "v32_cp2_lora_experts",
+ },
+ "deepseek_v4": {
+ "full": "v4_cp2|v4_cp4_late_rank_empty|v4_dp2cp2|v4_cp2_checkpoint",
+ "lora": "v4_cp2_lora",
+ "lora+experts": "v4_cp2_lora_experts",
+ },
+}
+# Attention implementations a family's evidence ran (default: _MOE_COMMON's sdpa and eager).
+_MOE_ATTENTION = {"deepseek_v4": ("eager",)}
# Families whose cp rows also ran Unsloth's checkpoint (path A and B); the others match HF checkpointing only.
_MOE_UNSLOTH_GC_FAMILIES = ("qwen3_moe",)
# (family, precision, aux, mode) -> (parity, engagement, compile) for the rows a test proves.
@@ -952,13 +985,20 @@ _MOE_EVIDENCE = {
)
* 2
+ (_MINIMAX_EAGER,),
+ **{
+ (family, precision, False, "cp"): (f"{_DEEPSEEK}[{ids}]",) * 2 + (_DEEPSEEK_EAGER,)
+ for family, cases in _DEEPSEEK_CASES.items()
+ for precision, ids in cases.items()
+ },
}
# Cells table only; a real model is read by structure (_direct_params, _tp_blocker).
_DIRECT_PARAM_FAMILIES = ("gpt_oss",)
_TP_BLOCKED_FAMILIES = {
+ "deepseek_v2": "multi-head latent attention (MLA, kv_lora_rank)",
"deepseek_v3": "multi-head latent attention (MLA, kv_lora_rank)",
+ "deepseek_v32": "multi-head latent attention (MLA, kv_lora_rank)",
"olmoe": "q_norm / k_norm normalize all heads' features, not one head",
}
@@ -1010,6 +1050,8 @@ def _moe_cells():
}
name = f"MoE {family} x {precision} x aux {'on' if aux else 'off'} x {mode}"
if evidence:
+ if family in _MOE_ATTENTION:
+ match = {**match, "attention": _MOE_ATTENTION[family]}
note = compiled_note = ""
if mode in ("cp", "fsdp2_cp") and family in _MOE_UNSLOTH_GC_FAMILIES:
match = {**match, "memory": _WITH_UNSLOTH_GC}
diff --git a/unsloth/trainer.py b/unsloth/trainer.py
index dd5af1f4f1e..aa19b61b9d9 100644
--- a/unsloth/trainer.py
+++ b/unsloth/trainer.py
@@ -1926,6 +1926,7 @@ def _patch_sft_trainer_auto_packing(trl_module):
# condition the post-init check skips on, so leaving it armed is free.
cp_size = getattr(config_arg, "context_parallel_size", 1) or 1
is_ring_context_parallel = False
+ ulysses_packing_blocker = None
if isinstance(cp_size, int) and cp_size > 1:
from .context_parallel import resolve_cp_backend
@@ -1937,6 +1938,15 @@ def _patch_sft_trainer_auto_packing(trl_module):
)
# Ring cannot keep packed rows apart: packing goes off below, as before 'auto' existed.
is_ring_context_parallel = cp_backend == "ring"
+ # Kimi delta, Lightning and DeepSeek V3.2 / V4 Ulysses forwards refuse packed batches: an
+ # automatic padding-free choice would fail the first CP step.
+ # A deferred (string) model is classified by its resolved config's model types.
+ if cp_backend == "ulysses":
+ from .context_parallel import ulysses_packing_blocker as _ulysses_packing_blocker
+ ulysses_packing_blocker = _ulysses_packing_blocker(
+ None if _packing_gate_deferred else model,
+ model_types if _packing_gate_deferred else (),
+ )
boundary_blocker = packing_boundary_blocker(model, model_types)
# Read before __init__: the compiled trainer ends it with model.for_inference(), which sets the flag.
eval_logits_wanted = os.environ.get(
@@ -1954,6 +1964,7 @@ def _patch_sft_trainer_auto_packing(trl_module):
blocked = (
(data_collator is not None)
or is_ring_context_parallel
+ or ulysses_packing_blocker is not None
or is_pipeline_parallel_env
or auto_off_cp_tp
or (is_processor and not processor_text_only)
@@ -1987,7 +1998,10 @@ def _patch_sft_trainer_auto_packing(trl_module):
setattr(config_arg, "padding_free", False)
# TRL resolves eval_packing on its own; packed eval batches would hit ring attention's varlen refusal.
if (
- is_ring_context_parallel or is_pipeline_parallel_env or boundary_blocker is not None
+ is_ring_context_parallel
+ or ulysses_packing_blocker is not None
+ or is_pipeline_parallel_env
+ or boundary_blocker is not None
) and getattr(config_arg, "eval_packing", None):
setattr(config_arg, "eval_packing", False)
@@ -2012,6 +2026,10 @@ def _patch_sft_trainer_auto_packing(trl_module):
if getattr(config_arg, "_unsloth_cp_backend_auto", False)
else "ring context parallelism; context_parallel_backend = 'ulysses' keeps it"
)
+ elif ulysses_packing_blocker is not None:
+ reason = (
+ f"Ulysses context parallelism: {ulysses_packing_blocker} refuses packed batches"
+ )
elif is_pipeline_parallel_env:
reason = "pipeline parallel (UNSLOTH_PP_SIZE)"
elif boundary_blocker is not None:
diff --git a/unsloth/utils/ulysses_deepseek.py b/unsloth/utils/ulysses_deepseek.py
new file mode 100644
index 00000000000..e4ef493af21
--- /dev/null
+++ b/unsloth/utils/ulysses_deepseek.py
@@ -0,0 +1,527 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Ulysses context parallelism for DeepSeek attention that bypasses ALL_ATTENTION_FUNCTIONS.
+
+DeepSeek-V3.2 folds a DSA indexer's top-k selection into its mask, and DeepSeek-V4 mixes sliding,
+compressed sparse (CSA) and heavily compressed (HCA) sink attention with K == V. Both forwards are
+replaced while Ulysses is active: projections run on the local sequence shard, queries move to head
+shards, and the indexer / compressor see the full sequence. Attention runs in query chunks so the
+score matrix is [H / N, chunk, T] instead of [H / N, T, T] (UNSLOTH_CP_ATTN_CHUNK, default 1024);
+with grad each chunk is recomputed in backward by a single autograd op, so this composes with
+activation checkpointing of the decoder layer.
+"""
+
+import functools
+import os
+import sys
+
+import torch
+import torch.distributed as dist
+import torch.nn.functional as F
+
+from ..device_type import DEVICE_TYPE_TORCH
+from .ulysses import _AllToAll
+
+__all__ = [
+ "DEEPSEEK_ULYSSES_ATTENTION_CLASSES",
+ "ulysses_deepseek_v4_forward",
+ "ulysses_deepseek_v32_forward",
+ "wrap_deepseek_attention_forward",
+]
+
+DEEPSEEK_ULYSSES_ATTENTION_CLASSES = ("DeepseekV32Attention", "DeepseekV4Attention")
+# model_type -> attention class, for configs whose model is not built yet (SFT given a model ID).
+DEEPSEEK_ULYSSES_MODEL_TYPES = {
+ "deepseek_v32": "DeepseekV32Attention",
+ "deepseek_v4": "DeepseekV4Attention",
+}
+
+# torch.amp.custom_fwd(device_type =) is 2.4+; older torch only has torch.cuda.amp (kernels/utils.py).
+_AMP_DEVICE = DEVICE_TYPE_TORCH if DEVICE_TYPE_TORCH in ("xpu", "npu") else "cuda"
+if hasattr(torch.amp, "custom_fwd") and hasattr(torch.amp, "custom_bwd"):
+ _custom_fwd = torch.amp.custom_fwd(device_type = _AMP_DEVICE)
+ _custom_bwd = torch.amp.custom_bwd(device_type = _AMP_DEVICE)
+else:
+ _custom_fwd = torch.cuda.amp.custom_fwd
+ _custom_bwd = torch.cuda.amp.custom_bwd
+
+
+def _apply_rotary_fn(mod):
+ module = sys.modules[type(mod).__module__]
+ return module.apply_rotary_pos_emb
+
+
+def _gather_seq(
+ x,
+ group,
+ dim = 1,
+):
+ """All-gather sequence shards along ``dim``; backward reduce-scatters the summed gradient.
+
+ torch.distributed.nn.all_gather's gloo backward scatters from group ranks as if they were global
+ ranks, so it fails on every CP group but the first under DP x CP.
+ """
+ from ..context_parallel import _GatherSequence
+
+ out = _GatherSequence.apply(
+ x.movedim(dim, 1), group, dist.get_rank(group), dist.get_world_size(group)
+ )
+ return out.movedim(1, dim)
+
+
+def _attn_chunk() -> int:
+ return max(1, int(os.environ.get("UNSLOTH_CP_ATTN_CHUNK", "1024")))
+
+
+def _sink_attention_chunk(
+ q, kv, block_bias, sinks, q_start, full_seq, window, scaling, dropout_p, training
+):
+ """Sink-softmax attention for the query rows ``[q_start, q_start + q.shape[2])``.
+
+ q: [B, H, rows, D]; kv: [B, 1, full_seq + n_blocks, D] (K == V); block_bias: [B, 1, rows, n_blocks].
+ Returns [B, rows, H, D].
+ """
+ batch, _, rows, _ = q.shape
+ dtype = q.dtype
+ q_idx = torch.arange(q_start, q_start + rows, device = q.device)
+ k_idx = torch.arange(full_seq, device = q.device)
+ diff = q_idx[:, None] - k_idx[None, :]
+ keep = diff >= 0
+ if window is not None:
+ keep = keep & (diff < window)
+ mask = torch.zeros((1, 1, rows, full_seq), dtype = dtype, device = q.device)
+ mask.masked_fill_(~keep.view(1, 1, rows, full_seq), torch.finfo(dtype).min)
+ extra = kv.shape[2] - full_seq
+ if extra > 0:
+ if block_bias is not None:
+ mask = torch.cat([mask.expand(batch, -1, -1, -1), block_bias.to(dtype)], dim = -1)
+ else:
+ mask = F.pad(mask, (0, extra), value = 0.0)
+
+ logits = torch.matmul(q, kv.transpose(2, 3)) * scaling + mask
+ sink = sinks.reshape(1, -1, 1, 1).expand(batch, -1, rows, -1)
+ combined = torch.cat([logits, sink], dim = -1)
+ combined = combined - combined.max(dim = -1, keepdim = True).values
+ probs = F.softmax(combined, dim = -1, dtype = combined.dtype)[..., :-1]
+ probs = F.dropout(probs, p = dropout_p, training = training).to(kv.dtype)
+ return torch.matmul(probs, kv).transpose(1, 2).contiguous()
+
+
+def _refuse_dropout(dropout_p, training):
+ if training and dropout_p:
+ raise NotImplementedError(
+ "Unsloth: Ulysses context parallelism does not support attention dropout."
+ )
+
+
+def _recompute_rows(chunk, full_seq, run, grad_out, row_inputs, full_inputs, needs):
+ """Backward of a query-chunked op: recompute each chunk and accumulate its input gradients.
+
+ run(start, end, *rows, *full) -> [B, rows, H, D]; row_inputs are sliced on dim 2, full_inputs are
+ not; needs is ctx.needs_input_grad for row_inputs + full_inputs, in that order.
+ """
+ row_need, full_need = needs[: len(row_inputs)], needs[len(row_inputs) :]
+ row_grads = [torch.zeros_like(t) if n else None for t, n in zip(row_inputs, row_need)]
+ full_grads = [
+ torch.zeros(t.shape, dtype = torch.float32, device = t.device) if n else None
+ for t, n in zip(full_inputs, full_need)
+ ]
+ for start in range(0, full_seq, chunk):
+ end = min(full_seq, start + chunk)
+ with torch.enable_grad():
+ rows = [
+ t[:, :, start:end].detach().requires_grad_(n) for t, n in zip(row_inputs, row_need)
+ ]
+ full = [t.detach().requires_grad_(n) for t, n in zip(full_inputs, full_need)]
+ out = run(start, end, *rows, *full)
+ wanted = [t for t in rows + full if t.requires_grad]
+ grads = iter(torch.autograd.grad(out, wanted, grad_out[:, start:end]))
+ for i, t in enumerate(rows):
+ if t.requires_grad:
+ row_grads[i][:, :, start:end] = next(grads)
+ for i, t in enumerate(full):
+ if t.requires_grad:
+ full_grads[i] += next(grads).float()
+ full_grads = [g if g is None else g.to(t.dtype) for g, t in zip(full_grads, full_inputs)]
+ return row_grads, full_grads
+
+
+class _ChunkedSinkAttention(torch.autograd.Function):
+ """Sink attention over query chunks; only the inputs are saved and each chunk is recomputed in
+ backward. Being one autograd op (no nested torch.utils.checkpoint) it composes with activation
+ checkpointing of the whole layer; custom_fwd / custom_bwd replay the forward's autocast state."""
+
+ @staticmethod
+ @_custom_fwd
+ def forward(ctx, q, kv, sinks, block_bias, window, scaling, chunk):
+ ctx.save_for_backward(q, kv, sinks, block_bias)
+ ctx.window, ctx.scaling, ctx.chunk = window, scaling, chunk
+ full_seq = q.shape[2]
+ with torch.no_grad():
+ outs = [
+ _sink_attention_chunk(
+ q[:, :, s : s + chunk],
+ kv,
+ None if block_bias is None else block_bias[:, :, s : s + chunk],
+ sinks,
+ s,
+ full_seq,
+ window,
+ scaling,
+ 0.0,
+ False,
+ )
+ for s in range(0, full_seq, chunk)
+ ]
+ return torch.cat(outs, dim = 1)
+
+ @staticmethod
+ @_custom_bwd
+ def backward(ctx, grad_out):
+ q, kv, sinks, block_bias = ctx.saved_tensors
+ full_seq = q.shape[2]
+
+ def run(start, end, q_rows, kv_full, sinks_full):
+ bias = None if block_bias is None else block_bias[:, :, start:end]
+ return _sink_attention_chunk(
+ q_rows,
+ kv_full,
+ bias,
+ sinks_full,
+ start,
+ full_seq,
+ ctx.window,
+ ctx.scaling,
+ 0.0,
+ False,
+ )
+
+ (gq,), (gkv, gsinks) = _recompute_rows(
+ ctx.chunk, full_seq, run, grad_out, [q], [kv, sinks], ctx.needs_input_grad[:3]
+ )
+ return gq, gkv, gsinks, None, None, None, None
+
+
+def _sink_attention(q, kv, block_bias, sinks, window, scaling, dropout_p, training):
+ """Query-chunked sink attention so the score matrix is [H/cp, chunk, S] rather than [H/cp, S, S].
+
+ With grad, chunks are recomputed in backward (_ChunkedSinkAttention), so peak memory is
+ O(chunk * S) per layer.
+ """
+ _refuse_dropout(dropout_p, training)
+ full_seq = q.shape[2]
+ chunk = _attn_chunk()
+ if block_bias is not None and block_bias.requires_grad:
+ raise RuntimeError("Unsloth: DeepSeek-V4 block bias is a mask and must not require grad.")
+ if torch.is_grad_enabled() and full_seq > chunk:
+ return _ChunkedSinkAttention.apply(q, kv, sinks, block_bias, window, scaling, chunk)
+ outs = [
+ _sink_attention_chunk(
+ q[:, :, s : s + chunk],
+ kv,
+ None if block_bias is None else block_bias[:, :, s : s + chunk],
+ sinks,
+ s,
+ full_seq,
+ window,
+ scaling,
+ 0.0,
+ False,
+ )
+ for s in range(0, full_seq, chunk)
+ ]
+ return outs[0] if len(outs) == 1 else torch.cat(outs, dim = 1)
+
+
+def ulysses_deepseek_v4_forward(
+ module,
+ hidden_states,
+ position_embeddings = None,
+ position_ids = None,
+ attention_mask = None,
+ past_key_values = None,
+ *,
+ group,
+ **kwargs,
+):
+ """Training forward of a DeepSeek-V4 attention layer on a contiguous sequence shard."""
+ cp = dist.get_world_size(group)
+ if past_key_values is not None:
+ raise RuntimeError("DeepSeek-V4 context parallel is the training path; cache is off.")
+ if module.num_heads % cp != 0:
+ raise RuntimeError(
+ f"DeepSeek-V4 CP needs cp={cp} to divide attention heads {module.num_heads}."
+ )
+
+ apply_rotary_pos_emb = _apply_rotary_fn(module)
+ rank = dist.get_rank(group)
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, module.head_dim)
+ cos, sin = position_embeddings[module.rope_layer_type]
+
+ q_residual = module.q_a_norm(module.q_a_proj(hidden_states))
+ q = module.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2)
+ q = module.q_b_norm(q)
+ q = apply_rotary_pos_emb(q, cos, sin)
+
+ kv = module.kv_norm(module.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2)
+ kv = apply_rotary_pos_emb(kv, cos, sin)
+
+ # Scatter query heads across cp ranks and gather full sequence [B, H/cp, S_full, D].
+ q = _AllToAll.apply(q, 1, 2, group)
+ # Gather single-head KV across sequence [B, 1, S_full, D]; backward sums the gradients
+ # of all head-partitioned ranks back to each rank's token shard.
+ kv = _gather_seq(kv, group, dim = 2)
+
+ local_heads = q.shape[1]
+ block_bias = None
+ if module.compressor is not None:
+ full_hidden = _gather_seq(hidden_states, group)
+ full_q_res = _gather_seq(q_residual, group)
+ pos_local = position_ids.contiguous()
+ pos_list = [torch.empty_like(pos_local) for _ in range(cp)]
+ dist.all_gather(pos_list, pos_local, group = group)
+ full_pos_ids = torch.cat(pos_list, dim = -1)
+ compressed_kv, block_bias = module.compressor(
+ full_hidden, full_q_res, full_pos_ids, None, module.layer_idx
+ )
+ kv = torch.cat([kv, compressed_kv], dim = 2)
+
+ attn_output = _sink_attention(
+ q,
+ kv,
+ block_bias,
+ module.sinks[rank * local_heads : (rank + 1) * local_heads],
+ module.sliding_window,
+ module.scaling,
+ 0.0 if not module.training else module.attention_dropout,
+ module.training,
+ )
+
+ # [B, S_full, H/cp, D] -> [B, S_local, H, D]
+ attn_output = _AllToAll.apply(attn_output, 1, 2, group)
+ attn_output = apply_rotary_pos_emb(attn_output.transpose(1, 2), cos, -sin).transpose(1, 2)
+
+ grouped = attn_output.reshape(*input_shape, module.config.o_groups, -1)
+ grouped = module.o_a_proj(grouped).flatten(2)
+ output = module.o_b_proj(grouped)
+ return output, None
+
+
+def _v32_global_topk(indexer, hidden_states, q_resid, position_embeddings, group, module):
+ """DSA indexer top-k for this rank's queries against the *full* key sequence, then gathered.
+
+ Indexer keys are a single 128-d vector per token, so gathering them is cheap. Scores are
+ ``[B, chunk, H_idx, S]`` in fp32, so queries are processed in chunks.
+ Returns int32 indices ``[B, S_full, topk]`` identical on every rank.
+ """
+ cp = dist.get_world_size(group)
+ rank = dist.get_rank(group)
+ batch, local_seq, _ = hidden_states.shape
+ cos, sin = position_embeddings
+ rope = indexer.qk_rope_head_dim
+
+ q = indexer.wq_b(q_resid).view(batch, local_seq, indexer.n_heads, indexer.head_dim)
+ q_rot, q_pass = torch.split(q, [rope, indexer.head_dim - rope], dim = -1)
+ k = indexer.k_norm(indexer.wk(hidden_states)).unsqueeze(2)
+ k_rot, k_pass = torch.split(k, [rope, indexer.head_dim - rope], dim = -1)
+ q_rot, k_rot = module.apply_rotary_pos_emb(q_rot, k_rot, cos, sin, unsqueeze_dim = 2)
+ q = torch.cat([q_rot, q_pass], dim = -1)
+ k = torch.cat([k_rot, k_pass], dim = -1).squeeze(2).contiguous()
+
+ k_parts = [torch.empty_like(k) for _ in range(cp)]
+ dist.all_gather(k_parts, k, group = group)
+ k_full = torch.cat(k_parts, dim = 1) # [B, S, D]
+ full_seq = k_full.shape[1]
+
+ weights = indexer.weights_proj(hidden_states.to(indexer.weights_proj.weight.dtype)).float()
+ weights = weights * (indexer.n_heads**-0.5)
+ k_t = k_full.transpose(-1, -2).float().unsqueeze(1) # [B, 1, D, S]
+ k_idx = torch.arange(full_seq, device = hidden_states.device)
+ topk = min(indexer.index_topk, full_seq)
+ chunk = max(1, _attn_chunk() // 4)
+ q_start = rank * local_seq
+
+ parts = []
+ for s in range(0, local_seq, chunk):
+ e = min(local_seq, s + chunk)
+ scores = torch.matmul(q[:, s:e].float(), k_t) * indexer.softmax_scale # [B, c, H, S]
+ scores = F.relu(scores)
+ index_scores = torch.matmul(weights[:, s:e].unsqueeze(-2), scores).squeeze(-2) # [B, c, S]
+ q_pos = torch.arange(q_start + s, q_start + e, device = hidden_states.device)
+ causal = q_pos[:, None] >= k_idx[None, :]
+ index_scores = index_scores.masked_fill(~causal.unsqueeze(0), float("-inf"))
+ parts.append(index_scores.topk(topk, dim = -1).indices.to(torch.int32))
+ local_topk = torch.cat(parts, dim = 1).contiguous()
+
+ gathered = [torch.empty_like(local_topk) for _ in range(cp)]
+ dist.all_gather(gathered, local_topk, group = group)
+ return torch.cat(gathered, dim = 1)
+
+
+def _sparse_mla_chunk(q, k, v, topk, q_start, scaling, dropout_p, training):
+ """Causal attention restricted to each query's indexer-selected keys. Returns [B, rows, H, Dv]."""
+ batch, _, rows, _ = q.shape
+ full_seq = k.shape[2]
+ q_idx = torch.arange(q_start, q_start + rows, device = q.device)
+ k_idx = torch.arange(full_seq, device = q.device)
+ causal = q_idx[:, None] >= k_idx[None, :]
+ selected = torch.zeros((batch, rows, full_seq), dtype = torch.bool, device = q.device)
+ selected.scatter_(-1, topk.long(), True)
+ keep = (selected & causal.unsqueeze(0)).unsqueeze(1) # [B, 1, rows, S]
+
+ logits = torch.matmul(q, k.transpose(2, 3)) * scaling
+ logits = logits.masked_fill(~keep, torch.finfo(logits.dtype).min)
+ probs = F.softmax(logits, dim = -1, dtype = torch.float32).to(q.dtype)
+ probs = F.dropout(probs, p = dropout_p, training = training)
+ return torch.matmul(probs, v).transpose(1, 2).contiguous()
+
+
+class _ChunkedSparseMLA(torch.autograd.Function):
+ """Indexer-masked MLA attention over query chunks, recomputed per chunk in backward."""
+
+ @staticmethod
+ @_custom_fwd
+ def forward(ctx, q, k, v, topk, scaling, chunk):
+ ctx.save_for_backward(q, k, v, topk)
+ ctx.scaling, ctx.chunk = scaling, chunk
+ full_seq = q.shape[2]
+ with torch.no_grad():
+ outs = [
+ _sparse_mla_chunk(
+ q[:, :, s : s + chunk], k, v, topk[:, s : s + chunk], s, scaling, 0.0, False
+ )
+ for s in range(0, full_seq, chunk)
+ ]
+ return torch.cat(outs, dim = 1)
+
+ @staticmethod
+ @_custom_bwd
+ def backward(ctx, grad_out):
+ q, k, v, topk = ctx.saved_tensors
+
+ def run(start, end, q_rows, k_full, v_full):
+ return _sparse_mla_chunk(
+ q_rows, k_full, v_full, topk[:, start:end], start, ctx.scaling, 0.0, False
+ )
+
+ (gq,), (gk, gv) = _recompute_rows(
+ ctx.chunk, q.shape[2], run, grad_out, [q], [k, v], ctx.needs_input_grad[:3]
+ )
+ return gq, gk, gv, None, None, None
+
+
+def _sparse_mla_attention(q, k, v, topk, scaling, dropout_p, training):
+ _refuse_dropout(dropout_p, training)
+ full_seq = q.shape[2]
+ chunk = _attn_chunk()
+ if torch.is_grad_enabled() and full_seq > chunk:
+ return _ChunkedSparseMLA.apply(q, k, v, topk, scaling, chunk)
+ outs = [
+ _sparse_mla_chunk(
+ q[:, :, s : s + chunk], k, v, topk[:, s : s + chunk], s, scaling, 0.0, False
+ )
+ for s in range(0, full_seq, chunk)
+ ]
+ return outs[0] if len(outs) == 1 else torch.cat(outs, dim = 1)
+
+
+def ulysses_deepseek_v32_forward(
+ module,
+ hidden_states,
+ position_embeddings = None,
+ attention_mask = None,
+ past_key_values = None,
+ position_ids = None,
+ *,
+ group,
+ **kwargs,
+):
+ """Training forward of DeepSeek-V3.2 MLA + DSA indexer on a contiguous sequence shard."""
+ cp = dist.get_world_size(group)
+ if past_key_values is not None:
+ raise RuntimeError("DeepSeek-V3.2 context parallel is the training path; cache is off.")
+ if module.num_heads % cp != 0:
+ raise RuntimeError(
+ f"DeepSeek-V3.2 CP needs cp={cp} to divide attention heads {module.num_heads}."
+ )
+
+ modeling = sys.modules[type(module).__module__]
+ batch, local_seq = hidden_states.shape[:-1]
+ cos, sin = position_embeddings
+
+ q_resid = module.q_a_layernorm(module.q_a_proj(hidden_states))
+ q_states = (
+ module.q_b_proj(q_resid).view(batch, local_seq, -1, module.qk_head_dim).transpose(1, 2)
+ )
+ q_pass, q_rot = torch.split(
+ q_states, [module.qk_nope_head_dim, module.qk_rope_head_dim], dim = -1
+ )
+
+ kv_pass, k_rot = torch.split(
+ module.kv_a_proj_with_mqa(hidden_states),
+ [module.kv_lora_rank, module.qk_rope_head_dim],
+ dim = -1,
+ )
+ k_pass = module.kv_a_layernorm(kv_pass).view(batch, 1, local_seq, module.kv_lora_rank)
+ k_rot = k_rot.view(batch, 1, local_seq, module.qk_rope_head_dim)
+ q_rot, k_rot = modeling.apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
+ query_states = torch.cat((q_pass, q_rot), dim = -1)
+ key_states, value_states = module.expand_kv(k_pass, k_rot)
+
+ topk = _v32_global_topk(
+ module.indexer, hidden_states, q_resid, position_embeddings, group, modeling
+ )
+
+ # [B, H, S_local, D] -> [B, H/cp, S_full, D]
+ q = _AllToAll.apply(query_states, 1, 2, group)
+ k = _AllToAll.apply(key_states, 1, 2, group)
+ v = _AllToAll.apply(value_states, 1, 2, group)
+
+ attn_output = _sparse_mla_attention(
+ q,
+ k,
+ v,
+ topk,
+ module.scaling,
+ 0.0 if not module.training else module.attention_dropout,
+ module.training,
+ )
+ # [B, S_full, H/cp, Dv] -> [B, S_local, H, Dv]
+ attn_output = _AllToAll.apply(attn_output, 1, 2, group)
+ attn_output = attn_output.reshape(batch, local_seq, -1).contiguous()
+ return module.o_proj(attn_output), None
+
+
+def _run_eager(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+
+def wrap_deepseek_attention_forward(module, get_cp_manager) -> None:
+ if getattr(module, "_unsloth_cp_orig_forward", None) is not None:
+ return
+ forward = module.forward
+ name = type(module).__name__
+ v4 = name == "DeepseekV4Attention"
+
+ @functools.wraps(forward)
+ def wrapped(*args, **kwargs):
+ manager = get_cp_manager()
+ if manager is None or manager.backend != "ulysses":
+ return forward(*args, **kwargs)
+ packed = kwargs.get("packed_seq_lengths")
+ if packed is not None or getattr(manager, "packed_seq_lengths", None) is not None:
+ raise NotImplementedError(
+ f"Unsloth: Ulysses context parallelism does not support packing for {name}."
+ )
+ # Looked up per call (tests substitute it). Eager even inside Unsloth's per-layer compiled
+ # region: traced, the list all_gather / sequence gather / no_grad indexer top-k crashed the
+ # first CP step (SIGSEGV on L4, torch 2.8 and 2.14).
+ ulysses_forward = ulysses_deepseek_v4_forward if v4 else ulysses_deepseek_v32_forward
+ return _run_eager(ulysses_forward, module, *args, group = manager.group, **kwargs)
+
+ module._unsloth_cp_orig_forward = forward
+ module.forward = wrapped