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.

Keep Mamba x_proj and out_proj unquantized for the fused mamba_ssm training path (#15377)

Daniel Hanbea21e25177d
diff --git a/tests/test_mamba_dt_proj_bnb_skip.py b/tests/test_mamba_dt_proj_bnb_skip.py
index 448ee87c195..4ecb0dd7200 100644
--- a/tests/test_mamba_dt_proj_bnb_skip.py
+++ b/tests/test_mamba_dt_proj_bnb_skip.py
@@ -4,15 +4,38 @@
"""Mamba QLoRA must keep mixer.dt_proj unquantized: transformers 5's Mamba slow path runs
``self.dt_proj.weight @ time_step``, which fails on a packed Params4bit."""
+import importlib.util
+
import torch
+def _mamba_ssm(monkeypatch, present):
+ real = importlib.util.find_spec
+ monkeypatch.setattr(
+ importlib.util,
+ "find_spec",
+ lambda name, *a, **k: (object() if present else None)
+ if name == "mamba_ssm"
+ else real(name, *a, **k),
+ )
+
+
def test_mamba_skips_dt_proj():
from unsloth.models.vision import _architecture_skip_modules
assert "dt_proj" in _architecture_skip_modules(["mamba"])
-def test_falcon_mamba_and_others_unchanged():
+def test_mamba_skips_fused_kernel_dense_weights(monkeypatch):
+ _mamba_ssm(monkeypatch, True)
+ from unsloth.models.vision import _architecture_skip_modules
+
+ skip = _architecture_skip_modules(["mamba"])
+ assert "x_proj" in skip and "out_proj" in skip
+ assert "in_proj" not in skip
+
+
+def test_falcon_mamba_and_others_unchanged(monkeypatch):
+ _mamba_ssm(monkeypatch, False)
from unsloth.models.vision import _architecture_skip_modules
assert "dt_proj" not in _architecture_skip_modules(["falcon_mamba"])
@@ -20,17 +43,19 @@ def test_falcon_mamba_and_others_unchanged():
assert _architecture_skip_modules(["llama"]) == []
-def test_user_bnb_config_gets_mamba_dt_proj():
+def test_user_bnb_config_gets_mamba_dt_proj(monkeypatch):
+ _mamba_ssm(monkeypatch, True)
from transformers import BitsAndBytesConfig
from unsloth.models.vision import _with_architecture_skip_modules
user = BitsAndBytesConfig(load_in_4bit = True, llm_int8_skip_modules = ["lm_head"])
out = _with_architecture_skip_modules(user, ["mamba"])
- assert out.llm_int8_skip_modules == ["lm_head", "dt_proj"]
+ assert out.llm_int8_skip_modules == ["lm_head", "dt_proj", "x_proj", "out_proj"]
assert user.llm_int8_skip_modules == ["lm_head"]
-def test_skip_key_keeps_tiny_mamba_dt_proj_out_of_bnb():
+def test_skip_key_keeps_tiny_mamba_dt_proj_out_of_bnb(monkeypatch):
+ _mamba_ssm(monkeypatch, True)
import pytest
pytest.importorskip("bitsandbytes")
@@ -59,15 +84,75 @@ def test_skip_key_keeps_tiny_mamba_dt_proj_out_of_bnb():
kinds = {
name: type(m).__name__
for name, m in model.named_modules()
- if name.endswith(("dt_proj", "in_proj", "x_proj"))
+ if name.endswith(("dt_proj", "in_proj", "x_proj", "out_proj"))
}
assert all(
not isinstance(model.get_submodule(n), bnb.nn.Linear4bit)
for n in kinds
- if n.endswith("dt_proj")
+ if n.endswith(("dt_proj", "x_proj", "out_proj"))
), kinds
assert any(
isinstance(model.get_submodule(n), bnb.nn.Linear4bit)
for n in kinds
if n.endswith("in_proj")
), kinds
+
+
+def test_fused_mamba_kernel_trains_with_skip_list():
+ """Real mamba_ssm training step on a random NF4 Mamba built with the skip list."""
+ import pytest
+
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ pytest.importorskip("bitsandbytes")
+ pytest.importorskip("mamba_ssm")
+ pytest.importorskip("causal_conv1d")
+ import bitsandbytes as bnb
+ from transformers import BitsAndBytesConfig, MambaConfig, MambaForCausalLM
+ from transformers.integrations import bitsandbytes as tbnb
+ from transformers.models.mamba import modeling_mamba
+ from unsloth.models.vision import _architecture_skip_modules
+
+ config = MambaConfig(vocab_size = 64, hidden_size = 64, state_size = 8, num_hidden_layers = 2, expand = 2)
+ torch.manual_seed(0)
+ model = MambaForCausalLM(config)
+ state = {n: p.detach().clone() for n, p in model.named_parameters()}
+ skip = ["lm_head"] + _architecture_skip_modules(["mamba"])
+ qc = BitsAndBytesConfig(
+ load_in_4bit = True, bnb_4bit_compute_dtype = torch.float32, llm_int8_skip_modules = skip
+ )
+ try:
+ model = tbnb.replace_with_bnb_linear(
+ model, modules_to_not_convert = skip, quantization_config = qc
+ )
+ except TypeError:
+ model = tbnb.replace_with_bnb_linear(
+ model, modules_to_not_convert = skip, quantization_config = qc, pre_quantized = False
+ )
+ for name, module in model.named_modules():
+ if isinstance(module, torch.nn.Linear) and name + ".weight" in state:
+ module.weight = torch.nn.Parameter(state[name + ".weight"])
+ if isinstance(module, bnb.nn.Linear4bit):
+ module.weight = bnb.nn.Params4bit(
+ state[name + ".weight"], requires_grad = False, quant_type = "nf4"
+ )
+ model = model.cuda()
+ assert isinstance(model.backbone.layers[0].mixer.in_proj, bnb.nn.Linear4bit)
+
+ calls = {"n": 0}
+ original = modeling_mamba.mamba_inner_fn
+
+ def counting(*args, **kwargs):
+ calls["n"] += 1
+ return original(*args, **kwargs)
+
+ modeling_mamba.mamba_inner_fn = counting
+ try:
+ model.train()
+ ids = torch.randint(0, 64, (2, 16), device = "cuda")
+ loss = model(input_ids = ids, labels = ids, use_cache = False).loss
+ loss.backward()
+ finally:
+ modeling_mamba.mamba_inner_fn = original
+ assert calls["n"] > 0
+ assert torch.isfinite(loss)
diff --git a/tests/test_mamba_fused_skip_gated.py b/tests/test_mamba_fused_skip_gated.py
new file mode 100644
index 00000000000..e22f14909df
--- /dev/null
+++ b/tests/test_mamba_fused_skip_gated.py
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+import importlib.util
+
+import pytest
+
+
+def _spec(present):
+ real = importlib.util.find_spec
+
+ def fake(name, *a, **k):
+ if name == "mamba_ssm":
+ return object() if present else None
+ return real(name, *a, **k)
+
+ return fake
+
+
[email protected]("mt", ["mamba", "falcon_mamba"])
+def test_fused_kernel_weights_dense_when_mamba_ssm_importable(monkeypatch, mt):
+ from unsloth.models.vision import _architecture_skip_modules
+
+ monkeypatch.setattr(importlib.util, "find_spec", _spec(True))
+ skip = _architecture_skip_modules([mt])
+ assert {"dt_proj", "x_proj", "out_proj"} <= set(skip) and "in_proj" not in skip
+ assert len(skip) == len(set(skip))
+
+
+def test_without_mamba_ssm_only_dt_proj_stays_dense(monkeypatch):
+ from unsloth.models.vision import _architecture_skip_modules
+
+ monkeypatch.setattr(importlib.util, "find_spec", _spec(False))
+ assert _architecture_skip_modules(["mamba"]) == ["dt_proj"]
+ assert _architecture_skip_modules(["falcon_mamba"]) == []
+ assert _architecture_skip_modules(["nemotron_h"]) == ["out_proj"]
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 6651734b174..bc608fc57a9 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -2786,6 +2786,14 @@ def _target_parameters_in_layers(
return [key for key in keys if _in_layers(key, layers_to_transform, layers_pattern)] or None
+def _mamba_ssm_importable():
+ import importlib.util
+ try:
+ return importlib.util.find_spec("mamba_ssm") is not None
+ except (ImportError, ValueError):
+ return True # unknown: keep the dense weights the fused kernel needs
+
+
def _architecture_skip_modules(model_types):
"""Extra modules kept out of bitsandbytes; shared by the device-map planner and the load."""
model_types = model_types or []
@@ -2796,6 +2804,9 @@ def _architecture_skip_modules(model_types):
# Mamba's transformers 5 slow path does dt_proj.weight @ time_step, which fails on Params4bit; dt_proj is tiny.
if any(mt == "mamba" for mt in model_types):
skip.append("dt_proj")
+ # mamba_ssm's fused mamba_inner_fn reads these .weight as dense matrices; the slow path is fine with 4-bit.
+ if any(mt in ("mamba", "falcon_mamba") for mt in model_types) and _mamba_ssm_importable():
+ skip.extend(m for m in ("dt_proj", "x_proj", "out_proj") if m not in skip)
# LongCat-Flash MLA: NF4 on q_b_proj / kv_b_proj badly hurts loss; both are small.
if any(mt in ("longcat_flash", "longcat_flash_lsa") for mt in model_types):
skip.extend(("q_b_proj", "kv_b_proj"))