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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Context parallel: Ulysses for Gated DeltaNet hybrids (Qwen3.5, Qwen3-Next) (#13920)
Daniel Han3ef40111c17c
diff --git a/tests/test_context_parallel.py b/tests/test_context_parallel.pyindex d2826794232..9d07430819d 100644--- a/tests/test_context_parallel.py+++ b/tests/test_context_parallel.py@@ -129,6 +129,7 @@ def test_training_step_divides_the_pre_shard_token_count_by_cp_size(monkeypatch)num_items_in_batch = None,):seen.append(("train", num_items_in_batch))+ assert inputs["use_cache"] is Falsedef prediction_step(self, model, inputs, prediction_loss_only):return (None, None, None)@@ -406,7 +407,7 @@ def test_deepspeed_and_fsdp_are_refused(monkeypatch, distributed_type):monkeypatch.setattr(cp.dist, "is_initialized", lambda: True)monkeypatch.setattr(cp.dist, "get_world_size", lambda: 2)monkeypatch.setattr(torch.cuda, "is_available", lambda: False)- monkeypatch.setattr(cp, "_supports_context_parallel", lambda model: True)+ monkeypatch.setattr(cp, "_supports_context_parallel", lambda model, backend = "ring": True)args = types.SimpleNamespace(context_parallel_size = 2, label_smoothing_factor = 0.0)accelerator = types.SimpleNamespace(distributed_type = types.SimpleNamespace(name = distributed_type)@@ -421,7 +422,7 @@ def _cp_env(monkeypatch):monkeypatch.setattr(cp.dist, "is_initialized", lambda: True)monkeypatch.setattr(cp.dist, "get_world_size", lambda: 2)monkeypatch.setattr(torch.cuda, "is_available", lambda: False)- monkeypatch.setattr(cp, "_supports_context_parallel", lambda model: True)+ monkeypatch.setattr(cp, "_supports_context_parallel", lambda model, backend = "ring": True)@pytest.mark.parametrize("case", ["iterable", "dispatch", "eval_dict"])diff --git a/tests/test_ulysses_hybrid.py b/tests/test_ulysses_hybrid.pynew file mode 100644index 00000000000..b2f730acb4f--- /dev/null+++ b/tests/test_ulysses_hybrid.py@@ -0,0 +1,283 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Ulysses context parallelism for Gated DeltaNet hybrids (Qwen3.5, Qwen3-Next), on CPU gloo ranks."""++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")+if not hasattr(transformers, "Qwen3NextConfig"):+ pytest.skip("transformers without Qwen3-Next", allow_module_level = True)+KINDS = ["qwen3_5", "qwen3_next"] if hasattr(transformers, "Qwen3_5TextConfig") else ["qwen3_next"]+++def _config(kind, **overrides):+ common = dict(+ vocab_size = 64,+ hidden_size = 32,+ intermediate_size = 64,+ num_hidden_layers = 3,+ layer_types = ["linear_attention", "full_attention", "linear_attention"],+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 8,+ linear_num_key_heads = 2,+ linear_num_value_heads = 4,+ linear_key_head_dim = 8,+ linear_value_head_dim = 8,+ linear_conv_kernel_dim = 4,+ attention_dropout = 0.0,+ tie_word_embeddings = False,+ )+ common.update(overrides)+ if kind == "qwen3_next":+ common.update(+ num_experts = 2,+ num_experts_per_tok = 1,+ moe_intermediate_size = 16,+ shared_expert_intermediate_size = 16,+ # Dense MLPs: the MoE path may pick CUDA kernels in a forked CPU worker.+ mlp_only_layers = list(range(common["num_hidden_layers"])),+ )+ return transformers.Qwen3NextConfig(**common), transformers.Qwen3NextForCausalLM+ return transformers.Qwen3_5TextConfig(**common), transformers.Qwen3_5ForCausalLM+++def _model(kind, **overrides):+ torch.manual_seed(0)+ config, cls = _config(kind, **overrides)+ model = cls(config).train()+ model.config._attn_implementation = "sdpa"+ return model+++def _force_torch_kernels(model):+ # The parity check is about the exchange, not the kernels: fla / Triton would touch CUDA in a+ # forked CPU worker whenever a GPU is visible. Only called inside the worker process.+ import inspect++ from unsloth.utils.packing import _hub_closure+ for module in model.modules():+ if not type(module).__name__.endswith("GatedDeltaNet"):+ continue+ globs = inspect.getmodule(type(module)).__dict__+ for name in ("causal_conv1d_fn", "torch_chunk_gated_delta_rule"):+ torch_function = _hub_closure(globs.get(name)).get("torch_function")+ if torch_function is not None:+ globs[name] = torch_function+ if "chunk_gated_delta_rule" in vars(module):+ # transformers 4.57 binds the kernels on the instance.+ module.chunk_gated_delta_rule = globs["torch_chunk_gated_delta_rule"]+ module.causal_conv1d_fn = None+++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)+ _force_torch_kernels(model)+ ids = torch.randint(0, 64, (2, 13), 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()}+ 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+ 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()+ for name, param in model.named_parameters():+ 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-6, 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_hybrid_gradients_match_one_rank(kind):+ _spawn(_parity_worker, 2, kind, False)+++def test_shard_local_gated_delta_is_wrong():+ # Negative control: the stock forward on a sequence shard restarts the scan at the shard seam.+ with pytest.raises(Exception, match = "AssertionError"):+ _spawn(_parity_worker, 2, KINDS[0], True)+++def test_hybrid_gates():+ model = _model(KINDS[0])+ assert "ulysses" in cp._unsupported_attention(model.config, "ring")+ assert cp._unsupported_attention(model.config, "ulysses") is None+ assert cp._supports_context_parallel(model, "ulysses")+ assert not cp._supports_context_parallel(model, "ring")+ with pytest.raises(NotImplementedError, match = "context_parallel_backend = 'ulysses'"):+ cp._check_stateful_mixers(model, "ring", 2)+ cp._check_stateful_mixers(model, "ulysses", 2)+ with pytest.raises(ValueError, match = "num_k_heads"):+ cp._check_stateful_mixers(model, "ulysses", 4)++ class FakeMamba2(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.A_log = torch.nn.Parameter(torch.zeros(2))+ self.dt_bias = torch.nn.Parameter(torch.zeros(2))+ self.conv1d = torch.nn.Conv1d(2, 2, 4, groups = 2)++ model.model.layers[0].mixer = FakeMamba2()+ with pytest.raises(NotImplementedError, match = "Gated DeltaNet linear attention only"):+ cp._check_stateful_mixers(model, "ulysses", 2)+++def test_eager_attention_is_refused():+ model = _model(KINDS[0])+ attn = model.model.layers[1].self_attn+ with pytest.raises(NotImplementedError, match = "attn_implementation"):+ uh.install_hf_attention_wrapper(attn, "eager", cp.get_cp_manager)+++def test_hybrid_packing_metadata_is_off_under_context_parallelism():+ from unsloth.utils import packing++ kwargs = {+ "input_ids": torch.ones(1, 8, dtype = torch.long),+ "position_ids": torch.tensor([[0, 1, 2, 0, 1, 2, 3, 4]]),+ "packed_seq_lengths": torch.tensor([3, 5], dtype = torch.int32),+ }+ assert packing._hybrid_varlen_metadata(kwargs) is not None+ manager = _manager(2, 0)+ with manager.apply({"input_ids": torch.ones(1, 8, dtype = torch.long)}):+ # The shard sees 4 tokens: local boundaries would split documents at the wrong places.+ assert packing._hybrid_varlen_metadata(kwargs) is None+++def test_ulysses_refuses_position_only_packing():+ inputs = {+ "input_ids": torch.ones(1, 6, dtype = torch.long),+ "position_ids": torch.tensor([[0, 1, 2, 0, 1, 2]]),+ }+ with pytest.raises(ValueError, match = "packed_seq_lengths"):+ _manager(2, 0)._prepare_inputs(inputs)+ inputs["packed_seq_lengths"] = torch.tensor([3, 3], dtype = torch.int32)+ _manager(2, 0)._prepare_inputs(inputs)+++def test_ulysses_accepts_right_padding_with_mask_derived_positions():+ inputs = {+ "input_ids": torch.ones(2, 6, dtype = torch.long),+ "attention_mask": torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0]]),+ "position_ids": torch.tensor([[0, 1, 2, 3, 4, 5], [0, 1, 2, 0, 0, 0]]),+ }+ _manager(2, 0)._prepare_inputs(inputs)+ # A restart between real tokens is still packing.+ inputs["position_ids"] = torch.tensor([[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 0, 0]])+ with pytest.raises(ValueError, match = "packed_seq_lengths"):+ _manager(2, 0)._prepare_inputs(inputs)+++def test_hybrid_refuses_multimodal_and_router_aux_loss():+ model = _model(KINDS[0])+ assert cp._supports_context_parallel(model, "ulysses")+ model.config.output_router_logits = True+ assert "output_router_logits" in cp._hybrid_config_blocker(model)+ assert not cp._supports_context_parallel(model, "ulysses")+ model.config.output_router_logits = False+ model.config.vision_config = {"model_type": "qwen3_5_vision"}+ assert cp._hybrid_config_blocker(model) == "multimodal models"+ assert not cp._supports_context_parallel(model, "ulysses")+ model.config.vision_config = None+ # transformers 4.x Qwen3-Next: per-expert modules, each run only when routed on that rank.+ model.mlp_holder = torch.nn.Module()+ model.mlp_holder.experts = torch.nn.ModuleList([torch.nn.Linear(2, 2)])+ assert "sparse MoE" in cp._hybrid_config_blocker(model)+ assert not cp._supports_context_parallel(model, "ulysses")+++def test_ulysses_refuses_per_batch_router_logits_and_3d_positions():+ inputs = {"input_ids": torch.ones(1, 6, dtype = torch.long), "output_router_logits": True}+ with pytest.raises(ValueError, match = "output_router_logits"):+ _manager(2, 0)._prepare_inputs(inputs)+ inputs = {+ "input_ids": torch.ones(1, 6, dtype = torch.long),+ "position_ids": torch.arange(6).expand(4, 1, 6).contiguous(),+ }+ with pytest.raises(ValueError, match = "2D"):+ _manager(2, 0)._prepare_inputs(inputs)+++def test_linear_attn_gets_packed_lengths_the_decoder_did_not_forward(monkeypatch):+ seen = {}+ monkeypatch.setattr(+ uh, "ulysses_gated_delta_forward", lambda module, *a, group, **kw: seen.update(kw)+ )+ module = torch.nn.Identity()+ manager = types.SimpleNamespace(+ backend = "ulysses", group = None, packed_seq_lengths = torch.tensor([3, 5])+ )+ uh.wrap_gated_delta_forward(module, lambda: manager)+ module(torch.zeros(1, 4, 2))+ assert torch.equal(seen["packed_seq_lengths"], torch.tensor([3, 5]))+ # Lengths the decoder did forward win.+ module(torch.zeros(1, 4, 2), packed_seq_lengths = torch.tensor([8]))+ assert torch.equal(seen["packed_seq_lengths"], torch.tensor([8]))diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.pyindex 58c2dfc41a5..6527588de96 100644--- a/unsloth/context_parallel.py+++ b/unsloth/context_parallel.py@@ -87,8 +87,9 @@ def context_parallel_options(config) -> tuple:return size, backend, rotate_method-def _unsupported_attention(config) -> Optional[str]:+def _unsupported_attention(config, backend = "ring") -> Optional[str]:# Ring and Llama's forward ignore mask, window and softcap, so both backends refuse them.+ allowed = {"full_attention", "linear_attention"} if backend == "ulysses" else {"full_attention"}configs = [config]text_config = getattr(config, "text_config", None)if text_config is not None and text_config is not config:@@ -97,9 +98,14 @@ def _unsupported_attention(config) -> Optional[str]:if c is None:continuelayer_types = getattr(c, "layer_types", None)- if layer_types and any(t != "full_attention" for t in layer_types):- kinds = sorted({t for t in layer_types if t != "full_attention"})- return f"{', '.join(kinds)} layers"+ 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 = (+ " (use context_parallel_backend = 'ulysses')"+ if kinds == ["linear_attention"]+ else ""+ )+ 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 (isinstance(sliding_window, int) and sliding_window > 0) or getattr(@@ -125,6 +131,13 @@ def _unregister_cp_sharding_rules() -> None:from .device_type import DEVICE_TYPE_TORCHfrom .utils.ulysses import _document_positions, ulysses_head_plan+from .utils.ulysses_hybrid import (+ GATED_DELTA_ATTENTION_CLASSES,+ check_gated_delta_heads,+ install_hf_attention_wrapper,+ is_ulysses_gated_delta,+ wrap_gated_delta_forward,+)# A module global, not a ContextVar: CUDA runs backward (and checkpoint recompute) on another thread._ACTIVE_MANAGER: Optional["ContextParallelManager"] = None@@ -141,14 +154,71 @@ def get_cp_manager() -> Optional["ContextParallelManager"]:return _ACTIVE_MANAGER-def _supports_context_parallel(model) -> bool:+def _stateful_mixers(model) -> list:+ from .utils.packing import _iter_stateful_mixers+ return _iter_stateful_mixers(model) if isinstance(model, torch.nn.Module) else []+++def _positions_restart(position_ids, attention_mask) -> bool:+ restart = position_ids[:, 1:] <= position_ids[:, :-1]+ if isinstance(attention_mask, torch.Tensor) and attention_mask.shape == position_ids.shape:+ # Right padding may carry any positions; only steps between real tokens count.+ valid = attention_mask.bool()+ restart = restart & valid[:, 1:] & valid[:, :-1]+ return bool(restart.any())+++def _hybrid_config_blocker(model) -> Optional[str]:+ config = getattr(model, "config", None)+ if getattr(config, "vision_config", None) is not None:+ # Only text buffers are sharded; image / video features would stay whole on every rank.+ return "multimodal models"+ text_config = getattr(config, "text_config", None) or config+ if getattr(text_config, "output_router_logits", False):+ # The load balancing loss is a product of per-sequence means, not a sum over shards.+ return "the MoE router auxiliary loss (output_router_logits)"+ if any(isinstance(getattr(m, "experts", None), torch.nn.ModuleList) for m in model.modules()):+ # Per-expert modules run only for experts the local shard routes to, so with DDP's+ # find_unused_parameters off an expert unused on one rank stalls the gradient reduction.+ return "sparse MoE layers with per-expert modules (transformers 4.x Qwen3-Next)"+ return None+++def _supports_context_parallel(model, backend = "ring") -> bool:from .models.llama import LlamaAttention_fast_forward- forwards = [- getattr(type(module).forward, "__func__", type(module).forward)- for name, module in model.named_modules()- if name.endswith("self_attn")- ]- return bool(forwards) and all(f is LlamaAttention_fast_forward for f in forwards)++ modules = [module for name, module in model.named_modules() if name.endswith("self_attn")]+ forwards = [getattr(type(m).forward, "__func__", type(m).forward) for m in modules]+ if bool(forwards) and all(f is LlamaAttention_fast_forward for f in forwards):+ return not _stateful_mixers(model)+ mixers = _stateful_mixers(model)+ return (+ backend == "ulysses"+ and bool(mixers)+ and all(is_ulysses_gated_delta(m) for m, _ in mixers)+ and all(type(m).__name__ in GATED_DELTA_ATTENTION_CLASSES for m in modules)+ and _hybrid_config_blocker(model) is None+ )+++def _check_stateful_mixers(model, backend, size) -> None:+ mixers = _stateful_mixers(model)+ if not mixers:+ return+ if backend != "ulysses":+ kinds = sorted({type(m).__name__ for m, _ in mixers})+ raise NotImplementedError(+ f"Unsloth: ring context parallelism cannot split the sequential scans of {kinds}; "+ "use context_parallel_backend = 'ulysses'."+ )+ unsupported = sorted({type(m).__name__ for m, _ in mixers if not is_ulysses_gated_delta(m)})+ if unsupported:+ raise NotImplementedError(+ "Unsloth: Ulysses context parallelism supports Gated DeltaNet linear attention only, "+ f"not {unsupported}."+ )+ for module, _ in mixers:+ check_gated_delta_heads(module, size)def _self_attn_pre_forward_hook(_module, module_args, module_kwargs):@@ -183,6 +253,18 @@ class ContextParallelManager:return self.mesh.get_group()def attach_attention_hooks(self, model: torch.nn.Module) -> None:+ if self.backend == "ulysses":+ for module, _ in _stateful_mixers(model):+ if is_ulysses_gated_delta(module):+ wrap_gated_delta_forward(module, get_cp_manager)+ for name, module in model.named_modules():+ if (+ name.endswith("self_attn")+ and type(module).__name__ in GATED_DELTA_ATTENTION_CLASSES+ ):+ install_hf_attention_wrapper(+ module, module.config._attn_implementation, get_cp_manager+ )for name, module in model.named_modules():if name.endswith("self_attn") and not getattr(module, "_unsloth_cp_hooked", False):module.register_forward_pre_hook(@@ -209,6 +291,29 @@ class ContextParallelManager:raise ValueError(f"Unsloth: packed_seq_lengths sum to {used} but the packed row has {seq_len} tokens.")+ if inputs.get("output_router_logits"):+ raise ValueError(+ "Unsloth: context parallelism does not support the MoE router auxiliary loss "+ "(output_router_logits): it is a product of per-sequence means, not a sum over shards."+ )+ position_ids = inputs.get("position_ids")+ if isinstance(position_ids, torch.Tensor) and position_ids.ndim != 2:+ # Sharding slices dim 1, which is the batch axis of e.g. Qwen3.5's [4, batch, seq] ids.+ raise ValueError(+ f"Unsloth: context parallelism needs 2D [batch, seq] position_ids, got {position_ids.ndim}D."+ )+ if (+ ulysses+ and packed_seq_lengths is None+ and isinstance(position_ids, torch.Tensor)+ and position_ids.ndim == 2+ and _positions_restart(position_ids, inputs.get("attention_mask"))+ ):+ # Restarting positions mark packed documents that attention and scans could not see.+ raise ValueError(+ "Unsloth: Ulysses context parallelism needs packed_seq_lengths for packed batches; "+ "position_ids that restart are not enough."+ )# .get: a collator may carry the key with None, which would leave positions shard-local.if inputs.get("position_ids") is None and packed_seq_lengths is not None:inputs["position_ids"] = _document_positions(@@ -272,10 +377,13 @@ class ContextParallelManager:inputs[name] = tensor[:, rank * local : (rank + 1) * local].contiguous()global _ACTIVE_MANAGERprevious, _ACTIVE_MANAGER = _ACTIVE_MANAGER, self+ # Some decoders (transformers 5.3 / 5.5) do not forward packed_seq_lengths to linear_attn.+ self.packed_seq_lengths = inputs.get("packed_seq_lengths")try:yieldfinally:_ACTIVE_MANAGER = previous+ self.packed_seq_lengths = None@contextlib.contextmanagerdef apply(self, inputs: dict) -> Iterator[None]:@@ -470,7 +578,7 @@ def patch_sft_trainer() -> None:if Version(accelerate.__version__) < Version("1.10.0"):raise NotImplementedError("Unsloth: context parallelism needs accelerate >= 1.10.0.")model_config = getattr(self.model, "config", None)- unsupported = _unsupported_attention(model_config)+ unsupported = _unsupported_attention(model_config, backend)if unsupported is not None:raise NotImplementedError(f"Unsloth: {backend} context parallelism does not support {unsupported}."@@ -484,10 +592,16 @@ def patch_sft_trainer() -> None:or text_config.num_attention_heads,size,)- if not _supports_context_parallel(self.model):+ _check_stateful_mixers(self.model, backend, size)+ blocker = _hybrid_config_blocker(self.model) if _stateful_mixers(self.model) else None+ if blocker is not None:+ raise NotImplementedError(+ f"Unsloth: context parallelism on Gated DeltaNet hybrids does not support {blocker}."+ )+ if not _supports_context_parallel(self.model, backend):raise NotImplementedError(- "Unsloth: context parallelism currently supports Llama-style attention only "- "(Llama, Qwen2, Gemma)."+ "Unsloth: context parallelism currently supports Llama-style attention "+ "(Llama, Qwen2, Gemma), and Qwen3-Next / Qwen3.5 Gated DeltaNet hybrids with Ulysses.")accelerator = getattr(self, "accelerator", None)distributed_type = getattr(getattr(accelerator, "distributed_type", None), "name", "NO")@@ -594,6 +708,9 @@ def patch_sft_trainer() -> None:args = (args[0] // manager.size, *args[1:])elif kwargs.get("num_items_in_batch") is not None:kwargs["num_items_in_batch"] = kwargs["num_items_in_batch"] // manager.size+ # Without gradient checkpointing the model would build a cache for the sharded scans.+ if hasattr(inputs, "setdefault"):+ inputs.setdefault("use_cache", False)# Forward and backward both inside, so gradient checkpointing recomputes with ring attention.with manager.apply(inputs) if manager else contextlib.nullcontext():return original_training_step(self, model, inputs, *args, **kwargs)diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex bdeb0791c0e..a07b3784c47 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -1123,6 +1123,12 @@ def _hybrid_varlen_metadata(kwargs):return Noneif kwargs.get("past_key_values") is not None or kwargs.get("cache_params") is not None:return None+ from ..context_parallel import get_cp_manager++ # Under context parallelism the model sees one sequence shard, so shard-local boundaries are wrong;+ # the Ulysses mixer forward builds global ones from packed_seq_lengths itself.+ if get_cp_manager() is not None:+ return Nonetotal, device = None, Nonefor key in ("input_ids", "inputs_embeds", "position_ids"):tensor = kwargs.get(key)diff --git a/unsloth/utils/ulysses_hybrid.py b/unsloth/utils/ulysses_hybrid.pynew file mode 100644index 00000000000..d4d6f263ca7--- /dev/null+++ b/unsloth/utils/ulysses_hybrid.py@@ -0,0 +1,308 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Ulysses context parallelism for hybrid models: Gated DeltaNet layers and Hugging Face attention.++Linear attention scans run sequentially over the whole sequence, so a sequence shard cannot run its+scan alone. Ulysses exchanges the projected q / k / v / beta / gate inputs from sequence shards to+head shards, runs the short conv and the chunked scan over the full sequence for a subset of heads,+and exchanges the output back before the gated norm and the output projection.+"""++import functools+import inspect++import torch+import torch.distributed as dist+import torch.nn.functional as F++from .ulysses import _AllToAll, ulysses_attention++__all__ = [+ "GATED_DELTA_ATTENTION_CLASSES",+ "is_ulysses_gated_delta",+ "check_gated_delta_heads",+ "ulysses_gated_delta_forward",+ "wrap_gated_delta_forward",+ "install_hf_attention_wrapper",+]++# Hybrid full attention layers: Hugging Face forwards that call ALL_ATTENTION_FUNCTIONS after RoPE.+GATED_DELTA_ATTENTION_CLASSES = (+ "Qwen3NextAttention",+ "Qwen3_5Attention",+ "Qwen3_5MoeAttention",+)+++def is_ulysses_gated_delta(module) -> bool:+ if not type(module).__name__.endswith("GatedDeltaNet") or not hasattr(module, "conv1d"):+ return False+ if hasattr(module, "in_proj_qkvz"):+ return hasattr(module, "in_proj_ba") and hasattr(module, "fix_query_key_value_ordering")+ return all(hasattr(module, n) for n in ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a"))+++def check_gated_delta_heads(module, cp_size) -> None:+ for name in ("num_k_heads", "num_v_heads"):+ heads = getattr(module, name)+ if heads % cp_size != 0:+ raise ValueError(+ f"Unsloth: Ulysses context parallelism needs linear attention {name} ({heads}) "+ f"to be divisible by context_parallel_size ({cp_size})."+ )+++def _kernel_params(fn):+ # transformers' hub wrapper silently drops keyword arguments its bound implementation does not name.+ from .packing import _hub_closure++ params = _hub_closure(fn).get("applicable_params")+ if params is not None:+ return set(params)+ try:+ return set(inspect.signature(fn).parameters)+ except (TypeError, ValueError):+ return set()+++def _gated_delta_kernels(module):+ # transformers 4.57 binds the kernels on the instance; 5.x calls module globals.+ attrs = vars(module)+ globs = getattr(inspect.getmodule(type(module)), "__dict__", {})+ conv = attrs.get("_unsloth_varlen_orig_conv") or attrs.get(+ "causal_conv1d_fn", globs.get("causal_conv1d_fn")+ )+ scan = (+ attrs.get("_unsloth_varlen_orig_scan")+ or attrs.get("chunk_gated_delta_rule")+ or globs.get("torch_chunk_gated_delta_rule")+ or globs.get("chunk_gated_delta_rule")+ )+ if scan is None:+ raise RuntimeError(+ f"Unsloth: no chunked gated delta rule kernel found for {type(module).__name__}."+ )+ return conv, scan+++def _packed_boundaries(kwargs, total, device):+ if kwargs.get("packed_seq_lengths") is None:+ return None+ from .packing import _seq_idx_from_cu_seqlens, get_packed_info_from_kwargs++ info = get_packed_info_from_kwargs(kwargs, device)+ built = None if info is None else _seq_idx_from_cu_seqlens(info[1], total)+ if built is None:+ raise ValueError(+ "Unsloth: Ulysses context parallelism got packed_seq_lengths that do not cover the sequence."+ )+ return built+++def ulysses_gated_delta_forward(+ module,+ hidden_states,+ cache_params = None,+ attention_mask = None,+ *,+ group,+ **kwargs,+):+ """Training forward of a Qwen3-Next / Qwen3.5 GatedDeltaNet on a contiguous sequence shard."""+ if cache_params is not None:+ raise RuntimeError("Unsloth: Ulysses context parallelism does not support a cache.")+ if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2:+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(hidden_states.dtype)++ size = dist.get_world_size(group)+ rank = dist.get_rank(group)+ check_gated_delta_heads(module, size)+ bsz, local_len, _ = hidden_states.shape+ total = local_len * size+ k_heads, v_heads = module.num_k_heads // size, module.num_v_heads // size+ dk, dv = module.head_k_dim, module.head_v_dim++ if hasattr(module, "in_proj_qkvz"):+ q, k, v, z, b, a = module.fix_query_key_value_ordering(+ module.in_proj_qkvz(hidden_states), module.in_proj_ba(hidden_states)+ )+ else:+ q, k, v = torch.split(+ module.in_proj_qkv(hidden_states),+ [module.key_dim, module.key_dim, module.value_dim],+ dim = -1,+ )+ z = module.in_proj_z(hidden_states)+ b = module.in_proj_b(hidden_states)+ a = module.in_proj_a(hidden_states)++ # Heads are contiguous per rank, so v head h keeps k head h // (num_v_heads // num_k_heads).+ pieces = [x.reshape(bsz, local_len, size, -1) for x in (q, k, v, b, a)]+ widths = [p.shape[-1] for p in pieces]+ mixed = _AllToAll.apply(torch.cat(pieces, dim = -1), 2, 1, group).squeeze(2)+ q, k, v, b, a = torch.split(mixed, widths, dim = -1)++ weight = module.conv1d.weight.squeeze(1)+ bias = module.conv1d.bias+ key_dim = module.key_dim+ starts = (rank * widths[0], key_dim + rank * widths[1], 2 * key_dim + rank * widths[2])+ rows = torch.cat(+ [torch.arange(s, s + w, device = weight.device) for s, w in zip(starts, widths[:3])]+ )+ weight = weight.index_select(0, rows)+ bias = None if bias is None else bias.index_select(0, rows)++ conv, scan = _gated_delta_kernels(module)+ boundaries = _packed_boundaries(kwargs, total, hidden_states.device)+ if boundaries is not None:+ if conv is None or "seq_idx" not in _kernel_params(conv):+ raise RuntimeError(+ "Unsloth: Ulysses context parallelism with packing needs a causal conv1d kernel "+ "that takes seq_idx (install causal_conv1d or use unsloth_zoo's kernels)."+ )+ if "cu_seqlens" not in _kernel_params(scan):+ raise RuntimeError(+ "Unsloth: Ulysses context parallelism with packing needs a gated delta rule kernel "+ "that takes cu_seqlens (install flash-linear-attention or use unsloth_zoo's kernels)."+ )+ mixed_qkv = torch.cat([q, k, v], dim = -1).transpose(1, 2)+ if conv is None:+ mixed_qkv = F.conv1d(+ mixed_qkv.to(weight.dtype),+ weight.unsqueeze(1),+ bias,+ padding = weight.shape[-1] - 1,+ groups = weight.shape[0],+ )[..., :total]+ mixed_qkv = F.silu(mixed_qkv)+ else:+ conv_kwargs = {"activation": module.activation}+ if boundaries is not None:+ conv_kwargs["seq_idx"] = boundaries[1]+ mixed_qkv = conv(mixed_qkv, weight, bias, **conv_kwargs)+ q, k, v = torch.split(mixed_qkv.transpose(1, 2), widths[:3], dim = -1)+ q = q.reshape(bsz, total, k_heads, dk)+ k = k.reshape(bsz, total, k_heads, dk)+ v = v.reshape(bsz, total, v_heads, dv)++ heads = slice(rank * v_heads, (rank + 1) * v_heads)+ beta = b.sigmoid()+ g = -module.A_log[heads].float().exp() * F.softplus(a.float() + module.dt_bias[heads])+ if v_heads // k_heads > 1:+ q = q.repeat_interleave(v_heads // k_heads, dim = 2)+ k = k.repeat_interleave(v_heads // k_heads, dim = 2)+ scan_kwargs = {}+ if boundaries is not None:+ scan_kwargs["cu_seqlens"] = boundaries[0]+ out, _ = scan(+ q,+ k,+ v,+ g = g,+ beta = beta,+ initial_state = None,+ output_final_state = False,+ use_qk_l2norm_in_kernel = True,+ **scan_kwargs,+ )+ out = _AllToAll.apply(out.reshape(bsz, total, v_heads, dv), 1, 2, group)++ out = module.norm(out.reshape(-1, dv), z.reshape(-1, dv))+ return module.out_proj(out.reshape(bsz, local_len, -1))+++def wrap_gated_delta_forward(module, get_cp_manager) -> None:+ if getattr(module, "_unsloth_cp_orig_forward", None) is not None:+ return+ forward = module.forward++ @functools.wraps(forward)+ def wrapped(*args, **kwargs):+ manager = get_cp_manager()+ if manager is None or manager.backend != "ulysses":+ return forward(*args, **kwargs)+ if kwargs.get("packed_seq_lengths") is None:+ packed = getattr(manager, "packed_seq_lengths", None)+ if packed is not None:+ kwargs["packed_seq_lengths"] = packed+ return ulysses_gated_delta_forward(module, *args, group = manager.group, **kwargs)++ module._unsloth_cp_orig_forward = forward+ module.forward = wrapped+++def _ulysses_hf_attention(module, query, key, value, attention_mask, *, group, **kwargs):+ from .attention_dispatch import (+ AttentionConfig,+ AttentionContext,+ _run_attention,+ select_attention_backend,+ )+ from .packing import get_packed_info_from_kwargs++ bsz, n_heads, q_len, head_dim = query.shape+ scaling = kwargs.get("scaling")+ if scaling is not None and abs(scaling * head_dim**0.5 - 1) > 1e-6:+ raise NotImplementedError(+ "Unsloth: Ulysses context parallelism needs the default attention scale 1/sqrt(head_dim)."+ )+ if module.training and kwargs.get("dropout"):+ raise NotImplementedError(+ "Unsloth: Ulysses context parallelism does not support attention dropout."+ )+ seq_info = get_packed_info_from_kwargs(kwargs, query.device)+ n_kv_heads = key.shape[1]+ config = AttentionConfig(+ backend = select_attention_backend(use_varlen = seq_info is not None),+ n_kv_heads = n_kv_heads,+ n_groups = n_heads // n_kv_heads,+ flash_dense_kwargs = {"causal": True},+ flash_varlen_kwargs = {"dropout_p": 0.0, "causal": True},+ )+ context = AttentionContext(+ bsz = bsz,+ q_len = q_len,+ kv_seq_len = key.shape[2],+ n_heads = n_heads,+ head_dim = head_dim,+ requires_grad = query.requires_grad,+ seq_info = seq_info,+ attention_mask = None,+ causal_mask = None,+ )+ return ulysses_attention(_run_attention, config, context, query, key, value, group), None+++def install_hf_attention_wrapper(module, implementation, get_cp_manager) -> None:+ """Route this module's ALL_ATTENTION_FUNCTIONS[implementation] call through Ulysses while active."""+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS++ # "eager" is a per-model function some transformers releases call without the registry.+ current = None if implementation == "eager" else ALL_ATTENTION_FUNCTIONS.get(implementation)+ if current is None:+ raise NotImplementedError(+ "Unsloth: Ulysses context parallelism for hybrid models needs attn_implementation "+ f"'sdpa' or a flash attention backend, not {implementation!r}."+ )+ module._unsloth_cp_ulysses_attention = True+ if getattr(current, "_unsloth_cp_ulysses", False):+ return++ @functools.wraps(current)+ def attention(module, query, key, value, attention_mask, *args, **kwargs):+ manager = get_cp_manager()+ if (+ manager is None+ or manager.backend != "ulysses"+ or not getattr(module, "_unsloth_cp_ulysses_attention", False)+ ):+ return current(module, query, key, value, attention_mask, *args, **kwargs)+ if args:+ raise TypeError("Unsloth: Ulysses attention expects keyword arguments after the mask.")+ return _ulysses_hf_attention(+ module, query, key, value, attention_mask, group = manager.group, **kwargs+ )++ attention._unsloth_cp_ulysses = True+ ALL_ATTENTION_FUNCTIONS[implementation] = attention