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.

Correct sample packing for hybrid models (gated-delta, Mamba2, short conv) (#9812)

kfastino7320e0921773
diff --git a/tests/utils/test_packing.py b/tests/utils/test_packing.py
index a67731107b8..807c00ff0e9 100644
--- a/tests/utils/test_packing.py
+++ b/tests/utils/test_packing.py
@@ -504,7 +504,7 @@ def test_patch_hybrid_varlen_no_dispatch_aborts(monkeypatch):
monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
model = _hybrid_model_with_gdn(lambda self, hidden_states, **kw: hidden_states)
assert patch_hybrid_linear_attention_varlen(model) is True
- with pytest.raises(RuntimeError, match = "both invoked"):
+ with pytest.raises(RuntimeError, match = "were not invoked"):
model(
input_ids = torch.zeros(1, 6),
packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
@@ -519,7 +519,7 @@ def test_patch_hybrid_varlen_partial_dispatch_aborts(monkeypatch):
lambda self, hidden_states, **kw: self.causal_conv1d_fn(hidden_states)
)
assert patch_hybrid_linear_attention_varlen(conv_only) is True
- with pytest.raises(RuntimeError, match = "both invoked"):
+ with pytest.raises(RuntimeError, match = "were not invoked"):
conv_only(
input_ids = torch.zeros(1, 6),
packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
@@ -530,7 +530,7 @@ def test_patch_hybrid_varlen_partial_dispatch_aborts(monkeypatch):
lambda self, hidden_states, **kw: self.chunk_gated_delta_rule(hidden_states)
)
assert patch_hybrid_linear_attention_varlen(scan_only) is True
- with pytest.raises(RuntimeError, match = "both invoked"):
+ with pytest.raises(RuntimeError, match = "were not invoked"):
scan_only(
input_ids = torch.zeros(1, 6),
packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
@@ -538,6 +538,667 @@ def test_patch_hybrid_varlen_partial_dispatch_aborts(monkeypatch):
)
+def _make_fake_mamba2_fused():
+ def mamba2_split_conv1d_scan_combined(
+ *args,
+ seq_idx = None,
+ **kwargs,
+ ):
+ mamba2_split_conv1d_scan_combined.calls.append(seq_idx)
+ return args[0] if args else None
+
+ mamba2_split_conv1d_scan_combined.calls = []
+ return mamba2_split_conv1d_scan_combined
+
+
+class _FakeNemotronHMamba2Mixer(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.conv1d = torch.nn.Conv1d(4, 4, 3, groups = 4)
+ self.A_log = torch.nn.Parameter(torch.zeros(4))
+ self.dt_bias = torch.nn.Parameter(torch.zeros(4))
+ self.mamba2_split_conv1d_scan_combined = _make_fake_mamba2_fused()
+
+ def forward(self, hidden_states, **kwargs):
+ fused_kwargs = dict(kwargs)
+ return self.mamba2_split_conv1d_scan_combined(hidden_states, **fused_kwargs)
+
+
+class _FakeMamba2Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.config = SimpleNamespace() # no markers -> module-level detection
+ self.mixer = _FakeNemotronHMamba2Mixer()
+
+ def forward(
+ self,
+ input_ids = None,
+ packed_seq_lengths = None,
+ use_cache = None,
+ **kwargs,
+ ):
+ return self.mixer(input_ids.float(), **kwargs)
+
+
+def test_is_hybrid_linear_attention_detects_mamba2_mixer():
+ is_hybrid = trainer_module._is_hybrid_linear_attention_model
+ assert is_hybrid(_FakeMamba2Model()) is True
+
+
+def test_patch_mamba2_varlen_injects_seq_idx(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ model = _FakeMamba2Model()
+ fused_orig = model.mixer.mamba2_split_conv1d_scan_combined
+
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ assert patch_hybrid_linear_attention_varlen(model) is True # idempotent
+
+ fused_orig.calls.clear()
+ packing_module._HYBRID_WARNED.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ seq_idx = fused_orig.calls[-1]
+ assert seq_idx is not None
+ assert seq_idx.tolist() == [[0, 0, 1, 2, 2, 2]]
+ assert not packing_module._HYBRID_WARNED
+
+ fused_orig.calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = True,
+ )
+ assert fused_orig.calls[-1] is None
+
+
+def test_patch_mamba2_varlen_kwargs_only_stub_fail_closed(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ model = _FakeMamba2Model()
+
+ def stub(*args, **kwargs):
+ return None
+
+ model.mixer.mamba2_split_conv1d_scan_combined = stub
+ assert patch_hybrid_linear_attention_varlen(model) is False
+
+
+def _fake_mamba2_model_with_modeling(name, **kernel_globals):
+ # The mixer's __init__ globals stand in for the modeling module the kernels load into.
+ import sys
+ import types
+
+ modeling = types.ModuleType(name)
+ modeling.__dict__.update(kernel_globals)
+ modeling._Base = _FakeNemotronHMamba2Mixer
+ exec(
+ "class NemotronHMamba2Mixer(_Base):\n"
+ " def __init__(self):\n"
+ " super().__init__()\n",
+ modeling.__dict__,
+ )
+ modeling.NemotronHMamba2Mixer.__module__ = name
+ sys.modules[name] = modeling
+ model = _FakeMamba2Model()
+ model.mixer = modeling.NemotronHMamba2Mixer()
+ return model, modeling
+
+
+def test_patch_mamba2_varlen_rejects_unavailable_fast_path(monkeypatch):
+ # Kernels missing at mixer __init__: transformers routes to torch_forward, so decline up front.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+
+ name = "fake_modeling_nemotron_h_nofast"
+ try:
+ model, modeling = _fake_mamba2_model_with_modeling(
+ name, is_fast_path_available = False, causal_conv1d_update = None
+ )
+ assert patch_hybrid_linear_attention_varlen(model) is False
+ assert modeling.is_fast_path_available is False
+ finally:
+ sys.modules.pop(name, None)
+
+
+def test_patch_mamba2_varlen_syncs_stale_compiled_kernel_globals(monkeypatch):
+ # The compiled copy gets the real kernel globals, never a forced fast path.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+ import types
+
+ def conv_update(*args, **kwargs):
+ return None
+
+ name = "fake_modeling_nemotron_h_fast"
+ compiled = types.ModuleType("unsloth_compiled_cache.fake_nemotron_h_sync")
+ compiled.is_fast_path_available = False
+ compiled.causal_conv1d_update = None
+ other = types.ModuleType("fake_nemotron_h_other")
+ other.is_fast_path_available = False
+ sys.modules[compiled.__name__] = compiled
+ sys.modules[other.__name__] = other
+ try:
+ model, modeling = _fake_mamba2_model_with_modeling(
+ name, is_fast_path_available = True, causal_conv1d_update = conv_update
+ )
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ assert compiled.is_fast_path_available is True
+ assert compiled.causal_conv1d_update is conv_update
+ assert other.is_fast_path_available is False
+ finally:
+ for key in (name, compiled.__name__, other.__name__):
+ sys.modules.pop(key, None)
+
+
+def test_patch_mamba2_varlen_rebinds_compiled_module_alias(monkeypatch):
+ # unsloth_compiled_cache holds its own fused-kernel alias; it must be rebound too.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+ import types
+
+ fused = _make_fake_mamba2_fused()
+ compiled = types.ModuleType("unsloth_compiled_cache.NemotronHMamba2Mixer")
+ compiled.mamba_split_conv1d_scan_combined = fused
+ sys.modules[compiled.__name__] = compiled
+
+ class _CompiledNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def __init__(self):
+ super().__init__()
+ del self.mamba2_split_conv1d_scan_combined
+ self.mamba2_split_conv1d_scan_combined = fused
+
+ def forward(self, hidden_states, **fused_kwargs):
+ return compiled.mamba_split_conv1d_scan_combined(
+ hidden_states, seq_idx = None, **fused_kwargs
+ )
+
+ class _CompiledModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _CompiledNemotronHMamba2Mixer()
+
+ try:
+ model = _CompiledModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ fused.calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert fused.calls[-1] is not None
+ assert fused.calls[-1].tolist() == [[0, 0, 1, 2, 2, 2]]
+ assert compiled.mamba_split_conv1d_scan_combined is not fused
+ finally:
+ sys.modules.pop(compiled.__name__, None)
+
+
+def _make_hub_mamba2_namespace(module_name):
+ # Functions exec'd into a registered module dict, so their LOAD_GLOBALs resolve through it.
+ import sys
+ import types
+
+ module = types.ModuleType(module_name)
+ sys.modules[module_name] = module
+ exec(
+ """
+def mamba_split_conv1d_scan_combined(*args, seq_idx=None, **kwargs):
+ mamba_split_conv1d_scan_combined.calls.append(seq_idx)
+ return args[0]
+mamba_split_conv1d_scan_combined.calls = []
+def cuda_kernels_forward(self, hidden_states, cache_params=None, attention_mask=None):
+ return mamba_split_conv1d_scan_combined(hidden_states, seq_idx=None)
+""",
+ module.__dict__,
+ )
+ return module
+
+
+def test_patch_mamba2_varlen_rewrites_cuda_kernels_forward_global(monkeypatch):
+ # transformers <= 5.15 cuda_kernels_forward LOAD_GLOBALs the kernel with seq_idx=None.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+ import types
+
+ module = _make_hub_mamba2_namespace("transformers_modules.fake_nemotron_h")
+ ns = module.__dict__
+
+ class _HubNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def __init__(self):
+ super().__init__()
+ del self.mamba2_split_conv1d_scan_combined
+ self.cuda_kernels_forward = types.MethodType(ns["cuda_kernels_forward"], self)
+
+ def forward(self, hidden_states, **kwargs):
+ return self.cuda_kernels_forward(hidden_states)
+
+ _HubNemotronHMamba2Mixer.__module__ = module.__name__
+
+ class _HubModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _HubNemotronHMamba2Mixer()
+
+ try:
+ model = _HubModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ ns["mamba_split_conv1d_scan_combined"].calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ seq_idx = ns["mamba_split_conv1d_scan_combined"].calls[-1]
+ assert seq_idx is not None
+ assert seq_idx.tolist() == [[0, 0, 1, 2, 2, 2]]
+ finally:
+ sys.modules.pop(module.__name__, None)
+
+
+def test_patch_mamba2_varlen_unreachable_kernel_namespace_aborts(monkeypatch):
+ # A kernel reachable only from an unregistered namespace must fail closed.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import types
+
+ ns: dict = {"__name__": "nowhere.fake_nemotron_h"}
+ exec(
+ """
+def mamba_split_conv1d_scan_combined(*args, seq_idx=None, **kwargs):
+ return args[0]
+def cuda_kernels_forward(self, hidden_states, cache_params=None, attention_mask=None):
+ return mamba_split_conv1d_scan_combined(hidden_states, seq_idx=None)
+""",
+ ns,
+ )
+
+ class _HiddenNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def __init__(self):
+ super().__init__()
+ self.cuda_kernels_forward = types.MethodType(ns["cuda_kernels_forward"], self)
+
+ def forward(self, hidden_states, **kwargs):
+ return self.cuda_kernels_forward(hidden_states)
+
+ class _HiddenModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _HiddenNemotronHMamba2Mixer()
+
+ model = _HiddenModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ with pytest.raises(RuntimeError, match = "were not invoked"):
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+
+
+def test_patch_mamba2_varlen_reaches_compiled_module_global(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+ import types
+
+ compiled = types.ModuleType("unsloth_compiled_cache.NemotronHMamba2Mixer")
+ ns = compiled.__dict__
+ ns["__name__"] = compiled.__name__
+ exec(
+ """
+def mamba_split_conv1d_scan_combined(*args, seq_idx=None, **kwargs):
+ mamba_split_conv1d_scan_combined.calls.append(seq_idx)
+ return args[0]
+mamba_split_conv1d_scan_combined.calls = []
+def NemotronHMamba2Mixer_cuda_kernels_forward(self, hidden_states, cache_params=None, attention_mask=None):
+ return mamba_split_conv1d_scan_combined(hidden_states, seq_idx=None)
+""",
+ ns,
+ )
+ sys.modules[compiled.__name__] = compiled
+
+ class _CompiledNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def __init__(self):
+ super().__init__()
+ del self.mamba2_split_conv1d_scan_combined
+ self.cuda_kernels_forward = types.MethodType(
+ ns["NemotronHMamba2Mixer_cuda_kernels_forward"], self
+ )
+
+ def forward(self, hidden_states, **kwargs):
+ return self.cuda_kernels_forward(hidden_states)
+
+ _CompiledNemotronHMamba2Mixer.__module__ = compiled.__name__
+
+ class _CompiledModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _CompiledNemotronHMamba2Mixer()
+
+ try:
+ model = _CompiledModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ ns["mamba_split_conv1d_scan_combined"].calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ seq_idx = ns["mamba_split_conv1d_scan_combined"].calls[-1]
+ assert seq_idx is not None
+ assert seq_idx.tolist() == [[0, 0, 1, 2, 2, 2]]
+ finally:
+ sys.modules.pop(compiled.__name__, None)
+
+
+def test_patch_mamba2_varlen_overwrites_stale_compiled_import(monkeypatch):
+ # The compiled cache imported the kernel before mixer __init__ loaded the real one.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+ import types
+
+ def stale(
+ *args,
+ seq_idx = None,
+ **kwargs,
+ ):
+ stale.calls.append(seq_idx)
+ return args[0] if args else None
+
+ stale.calls = []
+ real = _make_fake_mamba2_fused()
+ compiled = types.ModuleType("unsloth_compiled_cache.NemotronHMamba2Mixer")
+ compiled.mamba_split_conv1d_scan_combined = stale
+ sys.modules[compiled.__name__] = compiled
+
+ class _StaleNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def __init__(self):
+ super().__init__()
+ self.mamba2_split_conv1d_scan_combined = real
+
+ def cuda_kernels_forward(
+ self,
+ hidden_states,
+ cache_params = None,
+ attention_mask = None,
+ ):
+ return compiled.mamba_split_conv1d_scan_combined(hidden_states, seq_idx = None)
+
+ def forward(self, hidden_states, **kwargs):
+ return self.cuda_kernels_forward(hidden_states)
+
+ _StaleNemotronHMamba2Mixer.__module__ = compiled.__name__
+
+ class _StaleModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _StaleNemotronHMamba2Mixer()
+
+ try:
+ model = _StaleModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ real.calls.clear()
+ stale.calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert stale.calls == []
+ assert real.calls[-1] is not None
+ assert real.calls[-1].tolist() == [[0, 0, 1, 2, 2, 2]]
+ assert compiled.mamba_split_conv1d_scan_combined is not stale
+ finally:
+ sys.modules.pop(compiled.__name__, None)
+
+
+def test_patch_mamba2_varlen_clears_padded_mask_for_fused_path(monkeypatch):
+ # The fused kernel needs an all-ones mask; packed batches carry pad zeros.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+
+ def mamba_chunk_scan_combined(
+ *args,
+ seq_idx = None,
+ **kwargs,
+ ):
+ mamba_chunk_scan_combined.calls.append(seq_idx)
+ return args[0] if args else None
+
+ mamba_chunk_scan_combined.calls = []
+
+ class _MaskedNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def cuda_kernels_forward(
+ self,
+ hidden_states,
+ cache_params = None,
+ attention_mask = None,
+ ):
+ input_not_masked = attention_mask is None or bool(torch.all(attention_mask == 1))
+ if self.training and cache_params is None and input_not_masked:
+ return self.mamba2_split_conv1d_scan_combined(hidden_states, seq_idx = None)
+ return mamba_chunk_scan_combined(hidden_states, seq_idx = None)
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params = None,
+ attention_mask = None,
+ **kwargs,
+ ):
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+
+ class _MaskedModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _MaskedNemotronHMamba2Mixer()
+
+ model = _MaskedModel()
+ fused_orig = model.mixer.mamba2_split_conv1d_scan_combined
+ model.train()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ fused_orig.calls.clear()
+ mamba_chunk_scan_combined.calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ attention_mask = torch.tensor([[1, 1, 1, 1, 1, 0]]),
+ use_cache = False,
+ )
+ assert mamba_chunk_scan_combined.calls == []
+ assert fused_orig.calls[-1] is not None
+ assert fused_orig.calls[-1].tolist() == [[0, 0, 1, 2, 2, 2]]
+
+
+def test_patch_mamba2_varlen_clears_mask_on_compiled_mixer_forward(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+ import types
+
+ compiled = types.ModuleType("unsloth_compiled_module_nemotron_h")
+ ns = compiled.__dict__
+ ns["__name__"] = compiled.__name__
+ ns["torch"] = torch
+ exec(
+ """
+def mamba_split_conv1d_scan_combined(*args, seq_idx=None, **kwargs):
+ mamba_split_conv1d_scan_combined.calls.append(seq_idx)
+ return args[0]
+mamba_split_conv1d_scan_combined.calls = []
+def mamba_chunk_scan_combined(*args, seq_idx=None, **kwargs):
+ mamba_chunk_scan_combined.calls.append(seq_idx)
+ return args[0]
+mamba_chunk_scan_combined.calls = []
+def cuda_kernels_forward(self, hidden_states, cache_params=None, attention_mask=None):
+ input_not_masked = attention_mask is None or bool(torch.all(attention_mask == 1))
+ if self.training and cache_params is None and input_not_masked:
+ return mamba_split_conv1d_scan_combined(hidden_states, seq_idx=None)
+ return mamba_chunk_scan_combined(hidden_states, seq_idx=None)
+def NemotronHMamba2Mixer_forward(self, hidden_states, cache_params=None, attention_mask=None, **kwargs):
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+""",
+ ns,
+ )
+ sys.modules[compiled.__name__] = compiled
+
+ class _CompiledNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def __init__(self):
+ super().__init__()
+ del self.mamba2_split_conv1d_scan_combined
+ self.cuda_kernels_forward = types.MethodType(ns["cuda_kernels_forward"], self)
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params = None,
+ attention_mask = None,
+ **kwargs,
+ ):
+ return ns["NemotronHMamba2Mixer_forward"](
+ self,
+ hidden_states = hidden_states,
+ cache_params = cache_params,
+ attention_mask = attention_mask,
+ **kwargs,
+ )
+
+ _CompiledNemotronHMamba2Mixer.__module__ = compiled.__name__
+
+ class _EmptyCache:
+ def has_previous_state(self, layer_idx):
+ return False
+
+ class _CompiledModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _CompiledNemotronHMamba2Mixer()
+
+ def forward(
+ self,
+ input_ids = None,
+ packed_seq_lengths = None,
+ use_cache = None,
+ **kwargs,
+ ):
+ # Nemotron-H hands mixers an empty Cache, which also blocks the fused kernel.
+ return self.mixer(
+ input_ids.float(),
+ cache_params = _EmptyCache(),
+ **kwargs,
+ )
+
+ try:
+ model = _CompiledModel()
+ model.train()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ ns["mamba_split_conv1d_scan_combined"].calls.clear()
+ ns["mamba_chunk_scan_combined"].calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ attention_mask = torch.tensor([[1, 1, 1, 1, 1, 0]]),
+ use_cache = False,
+ )
+ assert ns["mamba_chunk_scan_combined"].calls == []
+ seq_idx = ns["mamba_split_conv1d_scan_combined"].calls[-1]
+ assert seq_idx is not None
+ assert seq_idx.tolist() == [[0, 0, 1, 2, 2, 2]]
+ finally:
+ sys.modules.pop(compiled.__name__, None)
+
+
+def test_patch_mamba2_varlen_wraps_shared_kernel_once_per_model(monkeypatch):
+ # Shared kernel name across layers: re-wrapping per mixer hit RecursionError.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+
+ fused = _make_fake_mamba2_fused()
+
+ class _SharedNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def __init__(self):
+ super().__init__()
+ self.mamba2_split_conv1d_scan_combined = fused
+
+ class _ManyLayerModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _SharedNemotronHMamba2Mixer()
+ self.layers = torch.nn.ModuleList([_SharedNemotronHMamba2Mixer() for _ in range(24)])
+
+ def forward(
+ self,
+ input_ids = None,
+ packed_seq_lengths = None,
+ use_cache = None,
+ **kwargs,
+ ):
+ hidden = self.mixer(input_ids.float(), **kwargs)
+ for layer in self.layers:
+ hidden = layer(hidden, **kwargs)
+ return hidden
+
+ model = _ManyLayerModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+
+ installed = model.mixer.mamba2_split_conv1d_scan_combined
+ assert installed is not fused
+ assert installed.__wrapped__ is fused # exactly one wrapper deep
+ for layer in model.layers:
+ assert layer.mamba2_split_conv1d_scan_combined is installed
+
+ fused.calls.clear()
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert fused.calls[-1].tolist() == [[0, 0, 1, 2, 2, 2]]
+
+
+def test_patch_mamba2_varlen_skips_stale_seq_idx_after_training(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+
+ class _GeneratingModel(_FakeMamba2Model):
+ def generate(self, hidden_states):
+ return self.mixer(hidden_states)
+
+ model = _GeneratingModel()
+ fused_orig = model.mixer.mamba2_split_conv1d_scan_combined
+ assert patch_hybrid_linear_attention_varlen(model) is True
+
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert fused_orig.calls[-1].tolist() == [[0, 0, 1, 2, 2, 2]]
+
+ # A shorter prompt must not inherit the 6-token packed boundaries.
+ fused_orig.calls.clear()
+ model.generate(torch.zeros(1, 3, 4))
+ assert fused_orig.calls == [None]
+
+
+def test_patch_mamba2_varlen_no_fused_dispatch_aborts(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+
+ class _SilentNemotronHMamba2Mixer(_FakeNemotronHMamba2Mixer):
+ def forward(self, hidden_states, **kwargs):
+ return hidden_states
+
+ class _SilentModel(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = _SilentNemotronHMamba2Mixer()
+
+ model = _SilentModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ with pytest.raises(RuntimeError, match = "were not invoked"):
+ model(
+ input_ids = torch.zeros(1, 6),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+
+
def test_varlen_from_position_ids_mrope_3d():
pos = (
torch.tensor([[0, 1, 0, 0, 1, 2]]).unsqueeze(0).expand(3, 1, 6).clone()
@@ -1696,3 +2357,432 @@ def test_guard_is_idempotent_and_actually_masks():
assert torch.equal(twice, once)
# idempotence alone is trivial for an identity helper, so pin the values
assert once.reshape(-1).tolist() == [-100, 1, -100, -100, 4, 5]
+
+
+def test_call_as_packed_mamba2_prefill_propagates_inner_type_error():
+ calls = []
+
+ def cuda_kernels_forward(
+ hidden_states,
+ cache_params = None,
+ attention_mask = None,
+ ):
+ calls.append((cache_params, attention_mask))
+ raise TypeError("'NoneType' object is not callable")
+
+ with pytest.raises(TypeError, match = "NoneType"):
+ packing_module._call_as_packed_mamba2_prefill(
+ cuda_kernels_forward, (torch.zeros(1), object(), torch.ones(1, 2)), {}
+ )
+ assert calls == [(None, None)]
+
+
+class _FakeMamba1Mixer(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.conv1d = torch.nn.Conv1d(4, 4, 3, groups = 4)
+ self.A_log = torch.nn.Parameter(torch.zeros(4, 2))
+ self.dt_proj = torch.nn.Linear(2, 4)
+
+
+class _FakeLfm2ShortConv(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.conv = torch.nn.Conv1d(4, 4, 3, groups = 4)
+ self.calls = []
+
+ def forward(
+ self,
+ hidden_states,
+ past_key_values = None,
+ attention_mask = None,
+ seq_idx = None,
+ ):
+ self.calls.append(seq_idx)
+ return hidden_states
+
+
+class _FakeFalconH1Mixer(_FakeNemotronHMamba2Mixer):
+ pass
+
+
+class _FakeMiniMaxLightningAttention(torch.nn.Module):
+ pass
+
+
+def _stateful_model(mixer):
+ model = _FakeMamba2Model()
+ model.mixer = mixer
+ return model
+
+
+def test_stateful_mixer_kind_by_structure():
+ kind = packing_module._stateful_mixer_kind
+ assert kind(_FakeNemotronHMamba2Mixer()) == "ssd"
+ assert kind(_FakeFalconH1Mixer()) == "ssd" # name-independent
+ assert kind(_FakeMamba1Mixer()) == "unsupported"
+ assert kind(_FakeLfm2ShortConv()) == "short_conv"
+ assert kind(_FakeMiniMaxLightningAttention()) == "unsupported"
+ assert kind(torch.nn.Linear(2, 2)) is None
+
+
[email protected]("mixer_cls", [_FakeFalconH1Mixer, _FakeMamba1Mixer, _FakeLfm2ShortConv])
+def test_trainer_flags_every_stateful_mixer_as_hybrid(mixer_cls):
+ from unsloth.trainer import _is_hybrid_linear_attention_model
+ assert _is_hybrid_linear_attention_model(_stateful_model(mixer_cls())) is True
+
+
[email protected]("mixer_cls", [_FakeMamba1Mixer, _FakeMiniMaxLightningAttention])
+def test_patch_varlen_rejects_mixers_without_boundary_kernels(monkeypatch, mixer_cls):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ assert patch_hybrid_linear_attention_varlen(_stateful_model(mixer_cls())) is False
+
+
+def test_patch_varlen_injects_seq_idx_into_short_conv(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ conv = _FakeLfm2ShortConv()
+
+ class _Lfm2Like(_FakeMamba2Model):
+ def __init__(self):
+ super().__init__()
+ self.mixer = conv
+
+ def forward(
+ self,
+ input_ids = None,
+ packed_seq_lengths = None,
+ use_cache = None,
+ **kwargs,
+ ):
+ return self.mixer(input_ids.float()[..., None].expand(-1, -1, 4))
+
+ model = _Lfm2Like()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert conv.calls[-1].tolist() == [[0, 0, 1, 2, 2, 2]]
+ model(input_ids = torch.zeros(1, 4, dtype = torch.long), use_cache = True)
+ assert conv.calls[-1] is None
+
+
+def _hub_wrapped(torch_function, implementation):
+ # Same closure shape as transformers' use_kernel_func_from_hub_with_fallback.
+ import functools
+ import inspect as _inspect
+
+ applicable_params = tuple(_inspect.signature(implementation).parameters)
+
+ @functools.wraps(torch_function)
+ def wrapped(*args, **kwargs):
+ kwargs = {k: v for k, v in kwargs.items() if k in applicable_params}
+ return implementation(*args, **kwargs)
+
+ return wrapped
+
+
+def _kwargs_gdn_model(name, accelerated):
+ # transformers >= 5.16 shape: forward(**kwargs) splats into module-level hub kernels.
+ import sys
+ import types
+
+ calls = {"conv": [], "scan": []}
+
+ def conv_ref(
+ x,
+ weight,
+ bias = None,
+ activation = None,
+ **kwargs,
+ ):
+ return x
+
+ def conv_fast(
+ x,
+ weight,
+ bias = None,
+ seq_idx = None,
+ activation = None,
+ ):
+ calls["conv"].append(seq_idx)
+ return x
+
+ def scan_ref(q, **kwargs):
+ return q
+
+ def scan_fast(
+ q,
+ cu_seqlens = None,
+ **kwargs,
+ ):
+ calls["scan"].append(cu_seqlens)
+ return q
+
+ modeling = types.ModuleType(name)
+ modeling.causal_conv1d_fn = _hub_wrapped(conv_ref, conv_fast if accelerated else conv_ref)
+ modeling.torch_chunk_gated_delta_rule = _hub_wrapped(
+ scan_ref, scan_fast if accelerated else scan_ref
+ )
+ exec(
+ "import torch\n"
+ "class FakeGatedDeltaNet(torch.nn.Module):\n"
+ " def __init__(self):\n"
+ " super().__init__()\n"
+ " self.conv1d = torch.nn.Conv1d(4, 4, 3, groups = 4)\n"
+ " def forward(self, hidden_states, **kwargs):\n"
+ " x = causal_conv1d_fn(hidden_states, self.conv1d.weight, **kwargs)\n"
+ " return torch_chunk_gated_delta_rule(x, cu_seqlens = kwargs.pop('cu_seq_lens_q', None), **kwargs)\n",
+ modeling.__dict__,
+ )
+ modeling.FakeGatedDeltaNet.__module__ = name
+ sys.modules[name] = modeling
+ model = _FakeMamba2Model()
+ model.mixer = modeling.FakeGatedDeltaNet()
+ return model, calls
+
+
+def test_patch_varlen_kwargs_mixer_injects_boundaries(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+
+ name = "fake_modeling_kwargs_gdn"
+ try:
+ model, calls = _kwargs_gdn_model(name, accelerated = True)
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert calls["conv"][-1].tolist() == [[0, 0, 1, 2, 2, 2]]
+ assert calls["scan"][-1].tolist() == [0, 2, 3, 6]
+ finally:
+ sys.modules.pop(name, None)
+
+
+def test_patch_varlen_kwargs_mixer_rejects_torch_fallback(monkeypatch):
+ # The hub wrapper would silently drop seq_idx / cu_seqlens on the reference kernels.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+
+ name = "fake_modeling_kwargs_gdn_ref"
+ try:
+ model, _ = _kwargs_gdn_model(name, accelerated = False)
+ assert patch_hybrid_linear_attention_varlen(model) is False
+ finally:
+ sys.modules.pop(name, None)
+
+
+def test_patch_varlen_kwargs_mixer_rejects_missing_recurrent_kernel(monkeypatch):
+ # A conv-only kernel table would let the first-forward handshake pass on the conv probe alone.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+
+ name = "fake_modeling_kwargs_gdn_noscan"
+ try:
+ model, _ = _kwargs_gdn_model(name, accelerated = True)
+ del sys.modules[name].torch_chunk_gated_delta_rule
+ assert patch_hybrid_linear_attention_varlen(model) is False
+ finally:
+ sys.modules.pop(name, None)
+
+
+def test_packed_mask_builder_gets_per_sequence_positions():
+ seen = []
+
+ def create_causal_mask(**kwargs):
+ seen.append(kwargs.get("position_ids"))
+
+ ns = {"create_causal_mask": create_causal_mask}
+ varlen = (torch.tensor([0, 2, 3, 6], dtype = torch.int32), torch.tensor([[0, 0, 1, 2, 2, 2]]))
+ packing_module._install_packed_mask_positions(ns, lambda: varlen)
+ ns["create_causal_mask"](inputs_embeds = None)
+ assert seen[-1].tolist() == [[0, 1, 0, 0, 1, 2]]
+ explicit = torch.arange(6)[None]
+ ns["create_causal_mask"](position_ids = explicit)
+ assert seen[-1] is explicit
+
+
+def test_short_conv_only_model_packs_without_flag(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", raising = False)
+ assert patch_hybrid_linear_attention_varlen(_stateful_model(_FakeLfm2ShortConv())) is True
+ assert patch_hybrid_linear_attention_varlen(_FakeMamba2Model()) is False
+
+
+def test_short_conv_rejects_hub_conv_bound_to_torch_fallback(monkeypatch):
+ # transformers >= 5.16 LFM2 routes through the hub conv; its torch fallback drops seq_idx.
+ monkeypatch.delenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", raising = False)
+ import sys
+ import types
+
+ def conv_ref(
+ x,
+ weight,
+ bias = None,
+ activation = None,
+ **kwargs,
+ ):
+ return x
+
+ name = "fake_modeling_lfm2_ref"
+ modeling = types.ModuleType(name)
+ modeling.causal_conv1d_fn = _hub_wrapped(conv_ref, conv_ref)
+ modeling._Base = _FakeLfm2ShortConv
+ exec("class Lfm2ShortConv(_Base):\n pass\n", modeling.__dict__)
+ modeling.Lfm2ShortConv.__module__ = name
+ sys.modules[name] = modeling
+ try:
+ assert (
+ patch_hybrid_linear_attention_varlen(_stateful_model(modeling.Lfm2ShortConv())) is False
+ )
+ finally:
+ sys.modules.pop(name, None)
+
+
+def test_patch_mamba2_varlen_second_model_gets_its_own_boundaries(monkeypatch):
+ # The kernel is a module global, so its wrapper outlives the first model; a later patched model
+ # must get its own boundaries rather than the first model's context.
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ import sys
+ import types
+
+ name = "fake_modeling_nemotron_h_global"
+ modeling = types.ModuleType(name)
+ exec(
+ "def mamba_split_conv1d_scan_combined(*args, seq_idx = None, **kwargs):\n"
+ " mamba_split_conv1d_scan_combined.calls.append(seq_idx)\n"
+ " return args[0]\n"
+ "mamba_split_conv1d_scan_combined.calls = []\n",
+ modeling.__dict__,
+ )
+ modeling._Base = _FakeNemotronHMamba2Mixer
+ exec(
+ "class NemotronHMamba2Mixer(_Base):\n"
+ " def __init__(self):\n"
+ " super().__init__()\n"
+ " del self.mamba2_split_conv1d_scan_combined\n"
+ " def forward(self, hidden_states, **kwargs):\n"
+ " return mamba_split_conv1d_scan_combined(hidden_states, seq_idx = None)\n",
+ modeling.__dict__,
+ )
+ modeling.NemotronHMamba2Mixer.__module__ = name
+ sys.modules[name] = modeling
+ calls = modeling.mamba_split_conv1d_scan_combined.calls
+
+ def build():
+ model = _FakeMamba2Model()
+ model.mixer = modeling.NemotronHMamba2Mixer()
+ return model
+
+ try:
+ first, second = build(), build()
+ assert patch_hybrid_linear_attention_varlen(first) is True
+ first(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert patch_hybrid_linear_attention_varlen(second) is True
+ second(
+ input_ids = torch.zeros(1, 5, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([4, 1], dtype = torch.int32),
+ use_cache = False,
+ )
+ assert calls[-1].tolist() == [[0, 0, 0, 0, 1]]
+ finally:
+ sys.modules.pop(name, None)
+
+
+def test_generate_restores_packed_stash_for_pending_backward(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ model = _FakeMamba2Model()
+ seen = []
+ model.generate = lambda *a, **k: seen.append(model.mixer._unsloth_varlen)
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ model(
+ input_ids = torch.zeros(1, 6, dtype = torch.long),
+ packed_seq_lengths = torch.tensor([2, 1, 3], dtype = torch.int32),
+ use_cache = False,
+ )
+ stash = model.mixer._unsloth_varlen
+ model.generate()
+ assert seen == [None] # generate never sees training boundaries
+ assert model.mixer._unsloth_varlen is stash # recompute in backward still does
+
+
+ "model_type, stateful, extra",
+ [
+ ("lfm2", True, {"num_hidden_layers": 2, "layer_types": ["conv", "full_attention"]}),
+ ("mamba2", True, {}),
+ ("falcon_h1", True, {}),
+ ("llama", False, {}),
+ ],
+)
+def test_string_model_config_detects_stateful_mixers(model_type, stateful, extra):
+ # A string model= reaches the detector as its config only.
+ from transformers import AutoConfig
+ from unsloth.trainer import _is_hybrid_linear_attention_model
+
+ # Keep the default layer count: shrinking it truncates hybrid layer schedules.
+ small = dict(
+ hidden_size = 64,
+ intermediate_size = 128,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ vocab_size = 128,
+ )
+ config = AutoConfig.for_model(model_type, **extra)
+ for key, value in small.items():
+ if hasattr(config, key):
+ setattr(config, key, value)
+ assert _is_hybrid_linear_attention_model(SimpleNamespace(config = config)) is stateful
+
+
+_REMOTE_MODELING = """
+import torch
+from transformers import PretrainedConfig, PreTrainedModel
+
+
+class RemoteSSMConfig(PretrainedConfig):
+ model_type = "remote_ssm_pr9812"
+
+
+class RemoteMixer(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.A_log = torch.nn.Parameter(torch.zeros(4))
+ self.dt_bias = torch.nn.Parameter(torch.zeros(4))
+ self.conv1d = torch.nn.Conv1d(4, 4, 3, groups = 4)
+
+
+class RemoteSSMForCausalLM(PreTrainedModel):
+ config_class = RemoteSSMConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.mixer = RemoteMixer()
+"""
+
+
[email protected]("grant", [True, False])
+def test_string_remote_code_model_forwards_trust_grant(tmp_path, grant):
+ # An auto_map-only checkpoint is built under the user's own trust_remote_code grant.
+ import json
+ from unsloth.trainer import _is_hybrid_linear_attention_model
+
+ (tmp_path / "modeling_remote_ssm.py").write_text(_REMOTE_MODELING, encoding = "utf-8")
+ auto_map = {
+ "AutoConfig": "modeling_remote_ssm.RemoteSSMConfig",
+ "AutoModelForCausalLM": "modeling_remote_ssm.RemoteSSMForCausalLM",
+ }
+ (tmp_path / "config.json").write_text(
+ json.dumps({"model_type": "remote_ssm_pr9812", "auto_map": auto_map}), encoding = "utf-8"
+ )
+ from transformers import AutoConfig
+
+ config = AutoConfig.from_pretrained(str(tmp_path), trust_remote_code = True)
+ target = SimpleNamespace(config = config, trust_remote_code = grant)
+ assert _is_hybrid_linear_attention_model(target) is grant
diff --git a/unsloth/trainer.py b/unsloth/trainer.py
index 592244e44b9..7253dbf9f4c 100644
--- a/unsloth/trainer.py
+++ b/unsloth/trainer.py
@@ -33,7 +33,7 @@ from unsloth.utils import (
enable_padding_free_metadata,
enable_sample_packing,
)
-from unsloth.utils.packing import patch_hybrid_linear_attention_varlen
+from unsloth.utils.packing import _stateful_mixer_kind, patch_hybrid_linear_attention_varlen
from unsloth_zoo.training_utils import (
unsloth_train as _unsloth_train,
)
@@ -465,11 +465,8 @@ def _resolve_string_model_class(model_name, model_config, config_arg):
# explicit `model_init_kwargs["trust_remote_code"] = None` keeps its falsy meaning.
# Disagreeing with that function would execute a module under a grant the config
# load itself did not accept.
+ trust_remote_code = _string_model_trust_remote_code(config_arg)
init_kwargs = getattr(config_arg, "model_init_kwargs", None) or {}
- if "trust_remote_code" in init_kwargs:
- trust_remote_code = init_kwargs["trust_remote_code"]
- else:
- trust_remote_code = getattr(config_arg, "trust_remote_code", None)
auto_map = getattr(model_config, "auto_map", None) or {}
if not trust_remote_code or not isinstance(auto_map, dict):
@@ -508,6 +505,13 @@ def _resolve_string_model_class(model_name, model_config, config_arg):
return None
+def _string_model_trust_remote_code(config_arg):
+ init_kwargs = getattr(config_arg, "model_init_kwargs", None) or {}
+ if "trust_remote_code" in init_kwargs:
+ return init_kwargs["trust_remote_code"]
+ return getattr(config_arg, "trust_remote_code", None)
+
+
def _is_hybrid_linear_attention_model(model) -> bool:
"""Detect models mixing linear-attention / state-space mixers (gated-delta,
Mamba-style) with a causal conv1d, e.g. Qwen3.5 / Qwen3-Next. Packing and
@@ -532,27 +536,34 @@ def _is_hybrid_linear_attention_model(model) -> bool:
if any(hasattr(config, marker) for marker in _HYBRID_CONFIG_MARKERS):
return True
- # Module-level: a mixer carrying a recurrent gated-delta op plus a conv1d.
- named_modules = getattr(model, "named_modules", None)
- if named_modules is None:
- return False
- seen = set()
- for _, module in named_modules():
- if id(module) in seen:
- continue
- seen.add(id(module))
- cls = type(module).__name__
- if not (
- cls.endswith("GatedDeltaNet") or "LinearAttention" in cls or cls.endswith("Mamba2Mixer")
- ):
- continue
- has_recurrent = any(
- hasattr(module, attr)
- for attr in ("chunk_gated_delta_rule", "recurrent_gated_delta_rule", "A_log")
+ # Module-level: any recurrent / causal-conv mixer, whether or not the varlen shim can serve it.
+ modules = getattr(model, "modules", None)
+ if modules is None:
+ return _config_has_stateful_mixer(
+ getattr(model, "config", None),
+ trust_remote_code = bool(getattr(model, "trust_remote_code", False)),
)
- if has_recurrent and hasattr(module, "conv1d"):
- return True
- return False
+ return any(_stateful_mixer_kind(module) is not None for module in modules())
+
+
+def _config_has_stateful_mixer(config, trust_remote_code = False) -> bool:
+ # A string model= only has its config here: build it on the meta device and classify its modules.
+ if config is None or not hasattr(config, "model_type"):
+ return False
+ try:
+ import torch
+ from transformers import AutoModel, AutoModelForCausalLM
+ with torch.device("meta"):
+ try:
+ model = AutoModelForCausalLM.from_config(
+ config, trust_remote_code = trust_remote_code
+ )
+ except Exception:
+ model = AutoModel.from_config(config, trust_remote_code = trust_remote_code)
+ except Exception:
+ # Unclassifiable remote code may hide a recurrent mixer: fail closed.
+ return bool(trust_remote_code and getattr(config, "auto_map", None))
+ return any(_stateful_mixer_kind(module) is not None for module in model.modules())
def _resolve_string_model_config(model_name, config_arg):
@@ -1361,13 +1372,16 @@ def _patch_sft_trainer_auto_packing(trl_module):
is_vlm = _is_vlm_config(model_config, model_types)
is_encoder_decoder = bool(getattr(model_config, "is_encoder_decoder", False))
hybrid_target = (
- SimpleNamespace(config = model_config)
+ SimpleNamespace(
+ config = model_config,
+ trust_remote_code = _string_model_trust_remote_code(config_arg),
+ )
if isinstance(model, str) and model_config is not None
else model
)
is_hybrid = _is_hybrid_linear_attention_model(hybrid_target)
- # Hybrid models corrupt packed batches unless the gated-delta conv and scan reset at sequence
- # boundaries, so enable the experimental varlen shim (flag plus kernels) or keep them blocked.
+ # Hybrid models corrupt packed batches unless the gated-delta / Mamba2 conv and scan reset at
+ # sequence boundaries, so enable the experimental varlen shim (flag plus kernels) or keep them blocked.
if (
is_hybrid
and not isinstance(model, str)
diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.py
index f1ae71ef84f..08525ad9345 100644
--- a/unsloth/utils/packing.py
+++ b/unsloth/utils/packing.py
@@ -18,6 +18,7 @@ import copy
import inspect
import logging
import os
+import sys
from collections import OrderedDict
from functools import wraps
from typing import Any, Iterable, Optional, Sequence, Tuple
@@ -300,12 +301,13 @@ def enable_padding_free_metadata(model, trainer):
collator._unsloth_padding_free_lengths_wrapped = True
-# Experimental correct packing / padding-free for hybrid linear-attention: Qwen3.5 / Qwen3-Next
-# mix a gated-delta recurrence with a causal conv1d, and packing flattens the batch so both leak
-# state across sequence boundaries unless seq_idx (conv) and cu_seqlens (scan) are passed. Only
-# the accelerated kernels accept these, so it fails closed on the pure-torch fallbacks, behind an
-# env flag, and overrides only the per-module prefill kernels (causal_conv1d_fn /
-# chunk_gated_delta_rule), leaving decode untouched.
+# Experimental packing for hybrid linear-attention (Qwen3.5 / Qwen3-Next gated-delta, Nemotron-H Mamba2):
+# a flattened batch leaks recurrent + conv state across sequences unless seq_idx / cu_seqlens reach the
+# accelerated kernels, so this is env-gated and fails closed on the pure-torch fallbacks.
+_MAMBA2_FUSED_NAMES = (
+ "mamba2_split_conv1d_scan_combined",
+ "mamba_split_conv1d_scan_combined",
+)
_HYBRID_PACKING_ENV_VAR = "UNSLOTH_EXPERIMENTAL_HYBRID_PACKING"
_HYBRID_LOGGER = logging.getLogger("unsloth.hybrid_packing")
_HYBRID_WARNED: set = set()
@@ -332,15 +334,274 @@ def _hybrid_reject(reason: str) -> bool:
return False
-def _iter_gated_delta_modules(model):
- modules, seen = [], set()
+def _names_param(
+ module,
+ param,
+ methods = ("forward",),
+) -> bool:
+ # Decorated forwards can hide their signature; their kernel methods still name the parameter.
+ for method in methods:
+ fn = getattr(type(module), method, None)
+ try:
+ if fn is not None and param in inspect.signature(fn).parameters:
+ return True
+ except (TypeError, ValueError):
+ continue
+ return False
+
+
+_QKV_CONVS = ("q_conv1d", "k_conv1d", "v_conv1d")
+
+
+def _stateful_mixer_kind(module) -> Optional[str]:
+ """How a token mixer carries state across positions: "gated_delta" / "ssd" (Mamba2-style
+ chunked scan) / "short_conv" take boundary metadata, "unsupported" leaks with no kernel
+ fix (Mamba1 selective scan, lightning attention, RWKV), None is stateless."""
+ name = type(module).__name__
+ if name.endswith("GatedDeltaNet"):
+ if hasattr(module, "conv1d"):
+ return "gated_delta"
+ convs = [getattr(module, c, None) for c in _QKV_CONVS]
+ if all(c is not None and _names_param(c, "cu_seqlens") for c in convs):
+ return "gated_delta_qkv"
+ return "unsupported"
+ if hasattr(module, "A_log"):
+ # Mamba2 / SSD mixers learn dt_bias; Mamba1 projects dt through dt_proj.
+ if hasattr(module, "conv1d") and hasattr(module, "dt_bias"):
+ return "ssd"
+ return "unsupported"
+ if "ShortConv" in name:
+ methods = ("forward", "cuda_kernels_forward", "slow_forward")
+ return "short_conv" if _names_param(module, "seq_idx", methods) else "unsupported"
+ if "LightningAttention" in name or (name.startswith("Rwkv") and hasattr(module, "time_decay")):
+ return "unsupported"
+ return None
+
+
+def _iter_stateful_mixers(model):
+ """(module, kind) for every stateful mixer, outermost first; submodules of a gated-delta
+ mixer (its own short convs) are owned by that mixer's shim."""
+ found, owned = [], set()
for module in model.modules():
- if id(module) in seen:
+ if id(module) in owned:
+ continue
+ kind = _stateful_mixer_kind(module)
+ if kind is None:
continue
- seen.add(id(module))
- if type(module).__name__.endswith("GatedDeltaNet") and hasattr(module, "conv1d"):
- modules.append(module)
- return modules
+ found.append((module, kind))
+ owned.update(id(m) for m in module.modules())
+ return found
+
+
+def _iter_gated_delta_modules(model):
+ return [
+ m for m, kind in _iter_stateful_mixers(model) if kind in ("gated_delta", "gated_delta_qkv")
+ ]
+
+
+def _iter_mamba2_modules(model):
+ return [m for m, kind in _iter_stateful_mixers(model) if kind == "ssd"]
+
+
+def _iter_short_conv_modules(model):
+ return [m for m, kind in _iter_stateful_mixers(model) if kind == "short_conv"]
+
+
+def _callable_accepts_named_seq_idx(fn) -> Optional[str]:
+ # A **kwargs-only hub stub does not count: it may drop seq_idx.
+ try:
+ params = inspect.signature(fn).parameters
+ except (TypeError, ValueError):
+ return "kernel signature not introspectable"
+ if "seq_idx" in params:
+ return None
+ return "mamba2 fused kernel does not accept seq_idx"
+
+
+_MAMBA2_NAMESPACE_SUBSTR = ("unsloth_compiled", "mamba_ssm")
+
+
+_MAMBA2_KERNEL_GLOBALS = (
+ "is_fast_path_available",
+ "causal_conv1d_fn",
+ "causal_conv1d_update",
+ "selective_state_update",
+ "mamba_chunk_scan_combined",
+)
+
+
+def _force_install_mamba2_fused(
+ namespace,
+ wrapped,
+ source = None,
+) -> None:
+ # unsloth_compiled_cache imported the kernel globals before the mixer's __init__ loaded them, so sync
+ # them from source; forcing is_fast_path_available on would call a missing decode kernel.
+ if wrapped is None or not isinstance(namespace, dict):
+ return
+ for name in _MAMBA2_FUSED_NAMES:
+ namespace[name] = wrapped
+ if (
+ isinstance(source, dict)
+ and namespace is not source
+ and "unsloth_compiled" in str(namespace.get("__name__", ""))
+ ):
+ for name in _MAMBA2_KERNEL_GLOBALS:
+ if name in namespace and name in source:
+ namespace[name] = source[name]
+ for value in list(namespace.values()):
+ inner = getattr(value, "__dict__", None)
+ if not isinstance(inner, dict):
+ continue
+ for name in _MAMBA2_FUSED_NAMES:
+ if name in inner:
+ inner[name] = wrapped
+
+
+def _iter_mamba2_install_namespaces(mamba2_modules):
+ seen: set[int] = set()
+
+ def take(ns):
+ if isinstance(ns, dict) and id(ns) not in seen:
+ seen.add(id(ns))
+ return True
+ return False
+
+ for module in mamba2_modules:
+ modeling = inspect.getmodule(type(module))
+ ns = getattr(modeling, "__dict__", None)
+ if take(ns):
+ yield ns
+ for name, mod in list(sys.modules.items()):
+ lname = (name or "").lower()
+ if not any(s in lname for s in _MAMBA2_NAMESPACE_SUBSTR):
+ continue
+ ns = getattr(mod, "__dict__", None)
+ if take(ns):
+ yield ns
+
+
+def _mamba2_handshake_debug(modules) -> str:
+ if not modules:
+ return ""
+ module = modules[0]
+ cls = type(module)
+ modeling = inspect.getmodule(cls)
+ globs = getattr(modeling, "__dict__", {}) if modeling is not None else {}
+ return (
+ f"Mixer {cls.__name__} from {getattr(cls, '__module__', None)}: "
+ f"is_fast_path_available={globs.get('is_fast_path_available', '<missing>')} "
+ f"fused_hit={getattr(module, '_unsloth_varlen_fused_hit', None)} "
+ f"conv_hit={getattr(module, '_unsloth_varlen_conv_hit', None)} "
+ f"scan_hit={getattr(module, '_unsloth_varlen_scan_hit', None)}"
+ )
+
+
+def _call_as_packed_mamba2_prefill(fn, args, kwargs):
+ # transformers <= 5.15 takes the fused kernel only with an all-ones mask and no cache.
+ # Only binding sits in the try: a TypeError from inside fn must not re-run fn.
+ try:
+ sig = inspect.signature(fn)
+ bound = sig.bind_partial(*args, **kwargs)
+ except (TypeError, ValueError):
+ return fn(*args, **{**kwargs, "attention_mask": None, "cache_params": None})
+ for name in ("attention_mask", "cache_params"):
+ if name in sig.parameters:
+ bound.arguments[name] = None
+ call_kwargs = bound.kwargs
+ for name in ("attention_mask", "cache_params"):
+ if name in call_kwargs:
+ call_kwargs[name] = None
+ return fn(*bound.args, **call_kwargs)
+
+
+_MAMBA2_MASK_CLEAR_NAMES = ("cuda_kernels_forward",)
+
+
+def _is_mamba2_mask_clear_name(name: str, classes = ()) -> bool:
+ # Unsloth's compiler names hoisted methods "<Class>_<method>".
+ if name in _MAMBA2_MASK_CLEAR_NAMES:
+ return True
+ return any(name in (f"{c}_cuda_kernels_forward", f"{c}_forward") for c in classes)
+
+
+# Shared kernel wrappers live on module globals and outlive any one model, so they read the running
+# packed batch and SSD mixer from here instead of closing over a model.
+_PACKED: list = [None]
+_ACTIVE_MIXER: list = [None]
+
+
+def _active_mixer_varlen():
+ mixer = _ACTIVE_MIXER[0]
+ return None if mixer is None else getattr(mixer, "_unsloth_varlen", None)
+
+
+def _wrap_clear_attention_mask(fn, varlen_getter):
+ if fn is None or not callable(fn) or getattr(fn, "_unsloth_varlen_mask_cleared", False):
+ return fn
+
+ @wraps(fn)
+ def wrapped(*args, **kwargs):
+ if varlen_getter() is not None:
+ return _call_as_packed_mamba2_prefill(fn, args, kwargs)
+ return fn(*args, **kwargs)
+
+ wrapped._unsloth_varlen_mask_cleared = True
+ return wrapped
+
+
+def _install_mamba2_mask_clear(
+ namespace,
+ varlen_getter,
+ classes = (),
+) -> None:
+ if not isinstance(namespace, dict):
+ return
+ for name, value in list(namespace.items()):
+ if not _is_mamba2_mask_clear_name(name, classes) or not callable(value):
+ continue
+ namespace[name] = _wrap_clear_attention_mask(value, varlen_getter)
+
+
+_MAMBA2_FALLBACK_SEQ_IDX = {
+ "mamba_chunk_scan_combined": "_unsloth_varlen_scan_hit",
+ "causal_conv1d_fn": "_unsloth_varlen_conv_hit",
+}
+
+
+def _install_mamba2_seq_idx_fallbacks(namespace) -> None:
+ if not isinstance(namespace, dict):
+ return
+ for name, hit_attr in _MAMBA2_FALLBACK_SEQ_IDX.items():
+ fn = namespace.get(name)
+ if not callable(fn) or getattr(fn, "_unsloth_varlen_seq_idx_wrapped", False):
+ continue
+ namespace[name] = _wrap_mamba2_seq_idx_call(fn, hit_attr = hit_attr)
+
+
+def _resolve_mamba2_fused(module):
+ orig = getattr(module, "_unsloth_varlen_orig_fused", None)
+ if callable(orig):
+ return orig, ("instance", None, None)
+ for name in _MAMBA2_FUSED_NAMES:
+ fn = getattr(module, name, None)
+ if callable(fn):
+ return fn, ("instance", None, name)
+ modeling = inspect.getmodule(type(module))
+ if modeling is not None:
+ modeling_dict = getattr(modeling, "__dict__", None)
+ if isinstance(modeling_dict, dict):
+ for name in _MAMBA2_FUSED_NAMES:
+ fn = modeling_dict.get(name)
+ if callable(fn):
+ return fn, ("modeling", modeling, name)
+ try:
+ from mamba_ssm.ops.triton.ssd_combined import ( # type: ignore
+ mamba_split_conv1d_scan_combined as fn,
+ )
+ except Exception:
+ return None, None
+ return fn, ("ssm", None, "mamba_split_conv1d_scan_combined")
def _hybrid_varlen_kernels_available(gated_delta_modules) -> Optional[str]:
@@ -356,11 +617,15 @@ def _hybrid_varlen_kernels_available(gated_delta_modules) -> Optional[str]:
if not gated_delta_modules:
return "no gated-delta modules found"
for module in gated_delta_modules:
+ # Split q/k/v short convs were checked for cu_seqlens by _stateful_mixer_kind.
+ split_convs = _stateful_mixer_kind(module) == "gated_delta_qkv"
conv = getattr(module, "_unsloth_varlen_orig_conv", None) or getattr(
module,
"causal_conv1d_fn",
None,
)
+ if split_convs:
+ conv = getattr(module, "q_conv1d").forward
scan = getattr(module, "_unsloth_varlen_orig_scan", None) or getattr(
module,
"chunk_gated_delta_rule",
@@ -375,7 +640,7 @@ def _hybrid_varlen_kernels_available(gated_delta_modules) -> Optional[str]:
).startswith("torch_"):
return "pure-torch kernel fallback in use"
try:
- if "seq_idx" not in inspect.signature(conv).parameters:
+ if not split_convs and "seq_idx" not in inspect.signature(conv).parameters:
return "conv kernel does not accept seq_idx"
if "cu_seqlens" not in inspect.signature(scan).parameters:
return "scan kernel does not accept cu_seqlens"
@@ -384,6 +649,336 @@ def _hybrid_varlen_kernels_available(gated_delta_modules) -> Optional[str]:
return None
+def _mamba2_varlen_kernels_available(mamba2_modules) -> Optional[str]:
+ if not mamba2_modules:
+ return "no mamba2 modules found"
+ for module in mamba2_modules:
+ fn, _loc = _resolve_mamba2_fused(module)
+ if fn is None:
+ return "mamba2 fused kernel missing (install mamba_ssm)"
+ if getattr(fn, "__name__", "").startswith("torch_"):
+ return "pure-torch kernel fallback in use"
+ reason = _callable_accepts_named_seq_idx(fn)
+ if reason is not None:
+ return reason
+ if _mamba2_kernel_globals(module).get("is_fast_path_available", True) is False:
+ return "mamba2 fast path unavailable (install mamba_ssm and causal_conv1d)"
+ return None
+
+
+def _mamba2_kernel_globals(module) -> dict:
+ # The mixer's __init__ assigns the lazily loaded kernels into its own module globals.
+ globs = getattr(type(module).__init__, "__globals__", None)
+ return globs if isinstance(globs, dict) else {}
+
+
+def _hybrid_varlen_dispatched(module) -> bool:
+ if getattr(module, "_unsloth_varlen_kwargs_mode", False):
+ return bool(getattr(module, "_unsloth_varlen_kwargs_hit", False))
+ kind = _stateful_mixer_kind(module)
+ if kind == "short_conv":
+ return bool(getattr(module, "_unsloth_varlen_conv_hit", False))
+ if kind == "ssd":
+ if getattr(module, "_unsloth_varlen_fused_hit", False):
+ return True
+ return bool(
+ getattr(module, "_unsloth_varlen_conv_hit", False)
+ and getattr(module, "_unsloth_varlen_scan_hit", False)
+ )
+ return bool(
+ getattr(module, "_unsloth_varlen_conv_hit", False)
+ and getattr(module, "_unsloth_varlen_scan_hit", False)
+ )
+
+
+def _varlen_seq_idx_applies(seq_idx, args, kwargs) -> bool:
+ # generate() bypasses model.forward, so a stale training seq_idx must not reach a prompt.
+ if seq_idx is None:
+ return False
+ total = seq_idx.shape[-1]
+ tensor = None
+ for name in ("x", "hidden_states", "zxbcdt"):
+ candidate = kwargs.get(name)
+ if isinstance(candidate, torch.Tensor):
+ tensor = candidate
+ break
+ if tensor is None:
+ for arg in args:
+ if isinstance(arg, torch.Tensor):
+ tensor = arg
+ break
+ if tensor is None or tensor.dim() < 2 or seq_idx.shape[0] != tensor.shape[0]:
+ return False
+ # causal_conv1d_fn takes (batch, dim, seqlen), the others (batch, seqlen, ...).
+ return total in (tensor.shape[1], tensor.shape[-1])
+
+
+def _wrap_mamba2_seq_idx_call(orig, *, hit_attr = "_unsloth_varlen_fused_hit"):
+ # Wrap once: Nemotron-H mixers share one kernel name, nesting per layer hits RecursionError.
+ if getattr(orig, "_unsloth_varlen_seq_idx_wrapped", False):
+ return orig
+
+ @wraps(orig)
+ def wrapped(*args, **kwargs):
+ # The calling mixer's own stash, so recompute and a second patched model both resolve correctly.
+ mixer, varlen = _ACTIVE_MIXER[0], _active_mixer_varlen()
+ if varlen is not None:
+ if kwargs.get("seq_idx") is None and _varlen_seq_idx_applies(varlen[1], args, kwargs):
+ kwargs["seq_idx"] = varlen[1]
+ if kwargs.get("seq_idx") is not None:
+ setattr(mixer, hit_attr, True)
+ return orig(*args, **kwargs)
+
+ wrapped._unsloth_varlen_seq_idx_wrapped = True
+ return wrapped
+
+
+def _rebind_mamba2_fused_aliases(orig, wrapped) -> None:
+ # LOAD_GLOBAL resolves through the module dict at call time; misses are caught by the handshake.
+ if orig is None or wrapped is orig:
+ return
+ for mod in list(sys.modules.values()):
+ if mod is None:
+ continue
+ namespace = getattr(mod, "__dict__", None)
+ if not isinstance(namespace, dict):
+ continue
+ for key, value in list(namespace.items()):
+ if value is orig:
+ namespace[key] = wrapped
+
+
+def _wrap_mamba2_mixer_forward(module):
+ if getattr(module, "_unsloth_mamba2_forward_wrapped", False):
+ return
+ forward_orig = module.forward
+ cuda_orig = getattr(module, "cuda_kernels_forward", None)
+ # A **kwargs-only forward may splat into a kernel that also gets seq_idx (duplicate keyword).
+ forward_names_seq_idx = False
+ try:
+ forward_names_seq_idx = "seq_idx" in inspect.signature(forward_orig).parameters
+ except (TypeError, ValueError):
+ pass
+
+ def _packed():
+ return getattr(module, "_unsloth_varlen", None)
+
+ @wraps(forward_orig)
+ def mixer_forward(*args, **kwargs):
+ varlen = _packed()
+ outer, _ACTIVE_MIXER[0] = _ACTIVE_MIXER[0], module
+ try:
+ if varlen is None:
+ return forward_orig(*args, **kwargs)
+ if (
+ forward_names_seq_idx
+ and kwargs.get("seq_idx") is None
+ and _varlen_seq_idx_applies(varlen[1], args, kwargs)
+ ):
+ kwargs["seq_idx"] = varlen[1]
+ return _call_as_packed_mamba2_prefill(forward_orig, args, kwargs)
+ finally:
+ _ACTIVE_MIXER[0] = outer
+
+ module.forward = mixer_forward
+ if callable(cuda_orig) and not getattr(cuda_orig, "_unsloth_varlen_mask_cleared", False):
+
+ @wraps(cuda_orig)
+ def cuda_kernels_forward(*args, **kwargs):
+ if _packed() is not None:
+ return _call_as_packed_mamba2_prefill(cuda_orig, args, kwargs)
+ return cuda_orig(*args, **kwargs)
+
+ cuda_kernels_forward._unsloth_varlen_mask_cleared = True
+ module.cuda_kernels_forward = cuda_kernels_forward
+ module._unsloth_mamba2_forward_wrapped = True
+
+
+# transformers >= 5.16 mixers splat **kwargs into module-level kernels wrapped by
+# use_kernel_func_from_hub_with_fallback; each must bind an accelerated kernel taking this boundary.
+_KWARGS_KERNELS = {
+ "causal_conv1d_fn": "seq_idx",
+ "mamba2_split_conv1d_scan_combined": "seq_idx",
+ "mamba2_chunk_scan": "seq_idx",
+ "torch_chunk_gated_delta_rule": "cu_seqlens",
+}
+_KWARGS_TRACE: list = [None]
+
+
+def _hub_closure(fn) -> dict:
+ fn = getattr(fn, "_unsloth_varlen_probe_of", fn)
+ try:
+ return inspect.getclosurevars(fn).nonlocals
+ except (TypeError, ValueError):
+ return {}
+
+
+def _is_kwargs_mixer(module) -> bool:
+ if hasattr(module, "cuda_kernels_forward") or "causal_conv1d_fn" in vars(module):
+ return False
+ try:
+ params = inspect.signature(module.forward).parameters.values()
+ except (TypeError, ValueError):
+ return False
+ if not any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params):
+ return False
+ globs = getattr(inspect.getmodule(type(module)), "__dict__", {})
+ return "implementation" in _hub_closure(globs.get("causal_conv1d_fn"))
+
+
+def _kwargs_kernels_available(modules, recurrent_ids = ()) -> Optional[str]:
+ for module in modules:
+ globs = getattr(inspect.getmodule(type(module)), "__dict__", {})
+ kernels = {n: globs[n] for n in _KWARGS_KERNELS if callable(globs.get(n))}
+ if "causal_conv1d_fn" not in kernels:
+ return f"{type(module).__name__}: no module-level conv kernel"
+ if id(module) in recurrent_ids and len(kernels) < 2:
+ return f"{type(module).__name__}: no module-level recurrent kernel"
+ for name, fn in kernels.items():
+ closure = _hub_closure(fn)
+ # The hub wrapper drops kwargs its bound implementation does not name, silently.
+ impl = closure.get("implementation")
+ if impl is None or impl is closure.get("torch_function"):
+ return f"{name} has no accelerated kernel"
+ if _KWARGS_KERNELS[name] not in closure.get("applicable_params", ()):
+ return f"{name} kernel does not accept {_KWARGS_KERNELS[name]}"
+ return None
+
+
+def _install_kwargs_probes(namespace) -> None:
+ if not isinstance(namespace, dict):
+ return
+ for name, param in _KWARGS_KERNELS.items():
+ fn = namespace.get(name)
+ if not callable(fn) or getattr(fn, "_unsloth_varlen_probe_of", None) is not None:
+ continue
+
+ @wraps(fn)
+ def probe(
+ *args,
+ _fn = fn,
+ _name = name,
+ _param = param,
+ **kwargs,
+ ):
+ if _KWARGS_TRACE[0] is not None:
+ _KWARGS_TRACE[0].append((_name, kwargs.get(_param) is not None))
+ return _fn(*args, **kwargs)
+
+ probe._unsloth_varlen_probe_of = fn
+ namespace[name] = probe
+
+
+def _wrap_kwargs_mixer_forward(module) -> None:
+ forward_orig = module.forward
+
+ @wraps(forward_orig)
+ def forward(*args, **kwargs):
+ varlen = getattr(module, "_unsloth_varlen", None)
+ if varlen is None or not _varlen_seq_idx_applies(varlen[1], args, kwargs):
+ return forward_orig(*args, **kwargs)
+ if kwargs.get("seq_idx") is None:
+ kwargs["seq_idx"] = varlen[1]
+ if kwargs.get("cu_seq_lens_q") is None:
+ kwargs["cu_seq_lens_q"] = varlen[0]
+ outer, _KWARGS_TRACE[0] = _KWARGS_TRACE[0], []
+ try:
+ out = forward_orig(*args, **kwargs)
+ finally:
+ trace, _KWARGS_TRACE[0] = _KWARGS_TRACE[0], outer
+ # Every boundary-capable kernel this mixer ran, a recurrent one included, must have received it.
+ if all(ok for _, ok in trace) and any(n != "causal_conv1d_fn" for n, _ in trace):
+ module._unsloth_varlen_kwargs_hit = True
+ return out
+
+ module.forward = forward
+ module._unsloth_varlen_kwargs_mode = True
+
+
+_MASK_BUILDERS = ("create_causal_mask", "create_sliding_window_causal_mask")
+
+
+def _packed_position_ids(varlen):
+ cu_seqlens, seq_idx = varlen
+ if seq_idx.shape[0] != 1:
+ return None
+ seg = seq_idx[0].long()
+ pos = torch.arange(seg.numel(), device = seg.device) - cu_seqlens.to(seg.device).long()[seg]
+ return pos[None]
+
+
+def _install_packed_mask_positions(namespace, varlen_getter) -> None:
+ """Some hybrids (GraniteMoeHybrid) build the attention mask without position_ids, so attention
+ would span packed sequences; hand the builder per-sequence positions while packed."""
+ if not isinstance(namespace, dict):
+ return
+ for name in _MASK_BUILDERS:
+ fn = namespace.get(name)
+ if not callable(fn) or getattr(fn, "_unsloth_packed_positions", False):
+ continue
+
+ @wraps(fn)
+ def build(
+ *args,
+ _fn = fn,
+ **kwargs,
+ ):
+ varlen = varlen_getter()
+ if varlen is not None and kwargs.get("position_ids") is None:
+ kwargs["position_ids"] = _packed_position_ids(varlen)
+ return _fn(*args, **kwargs)
+
+ build._unsloth_packed_positions = True
+ namespace[name] = build
+
+
+def _wrap_qkv_conv_forward(conv, owner) -> None:
+ # fla ShortConvolution resets at cu_seqlens; the owning mixer holds the packed boundaries.
+ forward_orig = conv.forward
+
+ @wraps(forward_orig)
+ def forward(*args, **kwargs):
+ varlen = getattr(owner, "_unsloth_varlen", None)
+ if varlen is not None and kwargs.get("cu_seqlens") is None:
+ if _varlen_seq_idx_applies(varlen[1], args, kwargs):
+ kwargs["cu_seqlens"] = varlen[0]
+ if kwargs.get("cu_seqlens") is not None:
+ owner._unsloth_varlen_conv_hit = True
+ return forward_orig(*args, **kwargs)
+
+ conv.forward = forward
+
+
+def _wrap_short_conv_forward(module) -> None:
+ forward_orig = module.forward
+
+ @wraps(forward_orig)
+ def forward(*args, **kwargs):
+ varlen = getattr(module, "_unsloth_varlen", None)
+ if (
+ varlen is not None
+ and kwargs.get("seq_idx") is None
+ and _varlen_seq_idx_applies(varlen[1], args, kwargs)
+ ):
+ kwargs["seq_idx"] = varlen[1]
+ outer, _KWARGS_TRACE[0] = _KWARGS_TRACE[0], []
+ try:
+ out = forward_orig(*args, **kwargs)
+ finally:
+ trace, _KWARGS_TRACE[0] = _KWARGS_TRACE[0], outer
+ # A probed (hub) conv kernel must itself have received seq_idx; the torch fallback drops it.
+ if kwargs.get("seq_idx") is not None and all(ok for _, ok in trace):
+ module._unsloth_varlen_conv_hit = True
+ return out
+
+ module.forward = forward
+
+
+def _uses_hub_conv(module) -> bool:
+ globs = getattr(inspect.getmodule(type(module)), "__dict__", {})
+ return "implementation" in _hub_closure(globs.get("causal_conv1d_fn"))
+
+
def _varlen_from_position_ids(position_ids):
"""(cu_seqlens int32[n+1], seq_idx int32[1,T]) for a flattened padding-free
batch, else None. Padding-free position_ids reset to 0 at each sequence start;
@@ -469,34 +1064,67 @@ def _hybrid_varlen_metadata(kwargs):
def patch_hybrid_linear_attention_varlen(model) -> bool:
- """Feed seq_idx / cu_seqlens to the gated-delta conv + scan so packing and
- padding-free reset state at sequence boundaries. Gated by
- UNSLOTH_EXPERIMENTAL_HYBRID_PACKING and fail-closed. Returns True when the
- varlen path is active, so the caller may allow packing for the model.
- Idempotent: repeat calls on an already-patched model return True."""
- if not _hybrid_packing_enabled():
+ """Feed seq_idx / cu_seqlens to hybrid mixers so packing resets state at sequence boundaries.
+ Gated by UNSLOTH_EXPERIMENTAL_HYBRID_PACKING (short-conv-only models pack without it), fail-closed,
+ idempotent. True when active."""
+ mixers = _iter_stateful_mixers(model)
+ # Short-conv-only models (LFM2) reset at seq_idx on both kernel and torch paths, so they pack by default.
+ short_conv_only = bool(mixers) and all(kind == "short_conv" for _, kind in mixers)
+ if not (_hybrid_packing_enabled() or short_conv_only):
return False
- gated_delta_modules = _iter_gated_delta_modules(model)
+ unsupported = sorted({type(m).__name__ for m, kind in mixers if kind == "unsupported"})
+ if unsupported:
+ return _hybrid_reject(f"no varlen kernel path for {unsupported}")
+ gated_delta_modules = [m for m, kind in mixers if kind in ("gated_delta", "gated_delta_qkv")]
+ mamba2_modules = [m for m, kind in mixers if kind == "ssd"]
+ short_conv_modules = [m for m, kind in mixers if kind == "short_conv"]
+ hybrid_modules = gated_delta_modules + mamba2_modules + short_conv_modules
+ if not hybrid_modules:
+ return _hybrid_reject("no stateful mixers found")
+ kwargs_modules = [
+ m
+ for m in gated_delta_modules + mamba2_modules
+ if getattr(m, "_unsloth_varlen_kwargs_mode", False) or _is_kwargs_mixer(m)
+ ]
+ kwargs_ids = {id(m) for m in kwargs_modules}
+ gated_delta_modules = [m for m in gated_delta_modules if id(m) not in kwargs_ids]
+ mamba2_modules = [m for m in mamba2_modules if id(m) not in kwargs_ids]
# Idempotency: an already fully-patched model stays active without re-validation.
- if (
- getattr(model, "_unsloth_varlen_forward_wrapped", False)
- and gated_delta_modules
- and all(getattr(m, "_unsloth_varlen_wrapped", False) for m in gated_delta_modules)
+ if getattr(model, "_unsloth_varlen_forward_wrapped", False) and all(
+ getattr(m, "_unsloth_varlen_wrapped", False) for m in hybrid_modules
):
return True
- reason = _hybrid_varlen_kernels_available(gated_delta_modules)
- if reason is not None:
- return _hybrid_reject(reason)
+ hub_short_convs = [m for m in short_conv_modules if _uses_hub_conv(m)]
+ if kwargs_modules or hub_short_convs:
+ reason = _kwargs_kernels_available(
+ kwargs_modules + hub_short_convs, recurrent_ids = {id(m) for m in kwargs_modules}
+ )
+ if reason is not None:
+ return _hybrid_reject(reason)
+ if gated_delta_modules:
+ reason = _hybrid_varlen_kernels_available(gated_delta_modules)
+ if reason is not None:
+ return _hybrid_reject(reason)
+ if mamba2_modules:
+ reason = _mamba2_varlen_kernels_available(mamba2_modules)
+ if reason is not None:
+ return _hybrid_reject(reason)
# Transactional: every module validated above, now wrap each and stash originals.
for module in gated_delta_modules:
if getattr(module, "_unsloth_varlen_wrapped", False):
continue
- conv_orig, scan_orig = module.causal_conv1d_fn, module.chunk_gated_delta_rule
- module._unsloth_varlen_orig_conv = conv_orig
+ scan_orig = module.chunk_gated_delta_rule
module._unsloth_varlen_orig_scan = scan_orig
+ if _stateful_mixer_kind(module) == "gated_delta_qkv":
+ for conv_name in _QKV_CONVS:
+ _wrap_qkv_conv_forward(getattr(module, conv_name), module)
+ conv_orig = None
+ else:
+ conv_orig = module.causal_conv1d_fn
+ module._unsloth_varlen_orig_conv = conv_orig
@wraps(conv_orig)
def conv_fn(
@@ -526,11 +1154,77 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:
kwargs["cu_seqlens"] = varlen[0]
return _orig(*args, **kwargs)
- module.causal_conv1d_fn = conv_fn
+ if conv_orig is not None:
+ module.causal_conv1d_fn = conv_fn
module.chunk_gated_delta_rule = scan_fn
module._unsloth_varlen = None
module._unsloth_varlen_wrapped = True
+ for ns in _iter_mamba2_install_namespaces(hybrid_modules):
+ _install_packed_mask_positions(ns, lambda: _PACKED[0])
+ for ns in _iter_mamba2_install_namespaces(kwargs_modules + hub_short_convs):
+ _install_kwargs_probes(ns)
+ for module in kwargs_modules:
+ if not getattr(module, "_unsloth_varlen_wrapped", False):
+ _wrap_kwargs_mixer_forward(module)
+ module._unsloth_varlen = None
+ module._unsloth_varlen_wrapped = True
+ for module in short_conv_modules:
+ if not getattr(module, "_unsloth_varlen_wrapped", False):
+ _wrap_short_conv_forward(module)
+ module._unsloth_varlen = None
+ module._unsloth_varlen_wrapped = True
+
+ wrapped_fused: dict[int, Any] = {}
+
+ def _ensure_mamba2_fused_wrapped(fn):
+ if fn is None:
+ return None
+ if getattr(fn, "_unsloth_varlen_seq_idx_wrapped", False):
+ return fn
+ wrapped = wrapped_fused.get(id(fn))
+ if wrapped is None:
+ wrapped = _wrap_mamba2_seq_idx_call(fn)
+ wrapped_fused[id(fn)] = wrapped
+ _rebind_mamba2_fused_aliases(fn, wrapped)
+ return wrapped
+
+ wrapped_real = None
+ for module in mamba2_modules:
+ if getattr(module, "_unsloth_varlen_wrapped", False):
+ continue
+ fn, loc = _resolve_mamba2_fused(module)
+ wrapped = _ensure_mamba2_fused_wrapped(fn)
+ wrapped_real = wrapped_real or wrapped
+ kind = loc[0] if loc is not None else None
+ if kind == "instance" and wrapped is not None:
+ module._unsloth_varlen_orig_fused = fn
+ setattr(module, loc[2] or _MAMBA2_FUSED_NAMES[0], wrapped)
+ elif kind == "modeling" and wrapped is not None:
+ setattr(loc[1], loc[2], wrapped)
+ elif kind == "ssm":
+ module._unsloth_varlen_orig_fused = fn
+ _wrap_mamba2_mixer_forward(module)
+ module._unsloth_varlen = None
+ module._unsloth_varlen_wrapped = True
+ if mamba2_modules:
+ if wrapped_real is None:
+ try:
+ from mamba_ssm.ops.triton.ssd_combined import ( # type: ignore
+ mamba_split_conv1d_scan_combined as _ssm_fused,
+ )
+ except Exception:
+ _ssm_fused = None
+ wrapped_real = _ensure_mamba2_fused_wrapped(_ssm_fused)
+ source = _mamba2_kernel_globals(mamba2_modules[0])
+
+ classes = {type(m).__name__ for m in mamba2_modules}
+
+ for ns in _iter_mamba2_install_namespaces(mamba2_modules):
+ _force_install_mamba2_fused(ns, wrapped_real, source)
+ _install_mamba2_mask_clear(ns, _active_mixer_varlen, classes)
+ _install_mamba2_seq_idx_fallbacks(ns)
+
# Refresh the boundary stash on the outermost forward, once per step and outside gradient-checkpoint
# recompute so it stays valid for recomputed inner forwards.
if not getattr(model, "_unsloth_varlen_forward_wrapped", False):
@@ -554,41 +1248,68 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:
"_unsloth_varlen_handshake_done",
False,
)
- for module in gated_delta_modules:
+ for module in hybrid_modules:
module._unsloth_varlen = varlen
if first_pack:
module._unsloth_varlen_conv_hit = False
module._unsloth_varlen_scan_hit = False
- out = forward_orig(*args, **kwargs)
- # Runtime dispatch handshake: on the first packed forward, confirm BOTH boundary kernels ran for
- # EVERY module.
+ module._unsloth_varlen_fused_hit = False
+ module._unsloth_varlen_kwargs_hit = False
+ outer, _PACKED[0] = _PACKED[0], varlen
+ try:
+ out = forward_orig(*args, **kwargs)
+ finally:
+ _PACKED[0] = outer
+ # Handshake: on the first packed forward every module must have hit its boundary kernels.
if first_pack:
model._unsloth_varlen_handshake_done = True
missing = [
- type(m).__name__
- for m in gated_delta_modules
- if not (
- getattr(m, "_unsloth_varlen_conv_hit", False)
- and getattr(m, "_unsloth_varlen_scan_hit", False)
- )
+ type(m).__name__ for m in hybrid_modules if not _hybrid_varlen_dispatched(m)
]
if missing:
- for m in gated_delta_modules:
+ for m in hybrid_modules:
m._unsloth_varlen = None
- _hybrid_reject("varlen conv/scan not both dispatched (dispatch changed?)")
+ _hybrid_reject("varlen kernels not dispatched (dispatch changed?)")
raise RuntimeError(
"Unsloth: experimental hybrid packing cannot continue because the "
- "varlen conv/scan wrappers were not both invoked for "
+ "varlen boundary kernels were not invoked for "
f"{sorted(set(missing))}. Unset UNSLOTH_EXPERIMENTAL_HYBRID_PACKING "
- "to train these models on the padded path."
+ "to train these models on the padded path.\n"
+ + _mamba2_handshake_debug(
+ [m for m in hybrid_modules if _stateful_mixer_kind(m) == "ssd"]
+ or hybrid_modules
+ )
)
return out
model.forward = forward_with_varlen
model._unsloth_varlen_forward_wrapped = True
+
+ _wrap_generate_clears_varlen(model, hybrid_modules)
return True
+def _wrap_generate_clears_varlen(model, hybrid_modules) -> None:
+ generate_orig = getattr(model, "generate", None)
+ if not callable(generate_orig) or getattr(model, "_unsloth_varlen_generate_wrapped", False):
+ return
+
+ @wraps(generate_orig)
+ def generate_without_varlen(*args, **kwargs):
+ # Restore after: gradient-checkpoint recompute in a pending backward still needs the stash.
+ saved = [module._unsloth_varlen for module in hybrid_modules]
+ for module in hybrid_modules:
+ module._unsloth_varlen = None
+ try:
+ return generate_orig(*args, **kwargs)
+ finally:
+ for module, varlen in zip(hybrid_modules, saved):
+ module._unsloth_varlen = varlen
+
+ model.generate = generate_without_varlen
+ model._unsloth_varlen_generate_wrapped = True
+
+
def get_packed_info_from_kwargs(
kwargs: dict, device: torch.device
) -> Optional[Tuple[torch.Tensor, torch.Tensor, int]]: