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
Dequantize 4-bit nn.MultiheadAttention out_proj after load (#13090)
Daniel Han1c946d17a0c8
diff --git a/tests/test_mha_out_proj_bnb_dequant.py b/tests/test_mha_out_proj_bnb_dequant.pynew file mode 100644index 00000000000..b71db493824--- /dev/null+++ b/tests/test_mha_out_proj_bnb_dequant.py@@ -0,0 +1,71 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A 4-bit out_proj inside nn.MultiheadAttention (granite-vision's SigLIP pooling head, #2672) must run."""++import pytest+import torch++bnb = pytest.importorskip("bitsandbytes")++from unsloth.models.loader_utils import _dequantize_multihead_attention_out_proj++DEVICE = "cuda" if torch.cuda.is_available() else "cpu"+DTYPE = torch.bfloat16+++def _pooling_head():+ torch.manual_seed(0)+ head = torch.nn.Module()+ head.attention = torch.nn.MultiheadAttention(64, 4, batch_first = True)+ head.mlp = torch.nn.Linear(64, 64)+ head.to(DEVICE, DTYPE)+ reference = head.attention.out_proj+ packed = bnb.nn.Linear4bit(64, 64, compute_dtype = DTYPE, quant_type = "nf4")+ packed.weight = bnb.nn.Params4bit(+ reference.weight.data.cpu(), requires_grad = False, quant_type = "nf4"+ )+ packed.bias = reference.bias+ try:+ packed = packed.to(DEVICE)+ except Exception as e:+ pytest.skip(f"bitsandbytes cannot quantize on {DEVICE}: {e}")+ if getattr(packed.weight, "quant_state", None) is None:+ pytest.skip(f"bitsandbytes did not quantize on {DEVICE}")+ head.attention.out_proj = packed+ return head+++def _attend(attention):+ q = torch.randn(2, 1, 64, device = DEVICE, dtype = DTYPE)+ kv = torch.randn(2, 5, 64, device = DEVICE, dtype = DTYPE)+ return attention(q, kv, kv)[0]+++def test_packed_out_proj_fails_then_runs_after_dequant():+ head = _pooling_head()+ packed = head.attention.out_proj+ with pytest.raises(RuntimeError, match = "same dtype"):+ _attend(head.attention)++ assert _dequantize_multihead_attention_out_proj(head) == 1+ out_proj = head.attention.out_proj+ assert type(out_proj) is torch.nn.modules.linear.NonDynamicallyQuantizableLinear+ assert out_proj.weight.dtype == DTYPE and not out_proj.weight.requires_grad+ expected = bnb.functional.dequantize_4bit(packed.weight.data, packed.weight.quant_state).to(+ DTYPE+ )+ assert torch.equal(out_proj.weight, expected)+ assert out_proj.bias is packed.bias+ assert torch.isfinite(_attend(head.attention)).all()+ # The sibling Linear is untouched and a second pass is a no-op.+ assert type(head.mlp) is torch.nn.Linear+ assert _dequantize_multihead_attention_out_proj(head) == 0+++def test_float_out_proj_untouched():+ head = torch.nn.Module()+ head.attention = torch.nn.MultiheadAttention(64, 4, batch_first = True)+ before = head.attention.out_proj+ assert _dequantize_multihead_attention_out_proj(head) == 0+ assert head.attention.out_proj is beforediff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex 81f885dbefe..600152e3aa1 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -2454,6 +2454,43 @@ def _offload_store_set(store, key, value):raise TypeError(f"Unsloth: cannot write offloaded tensor into {type(store).__name__}")+def _dequantize_multihead_attention_out_proj(model):+ """nn.MultiheadAttention passes out_proj.weight straight to F.linear, so a bitsandbytes 4-bit out_proj+ (SigLIP pooling head, granite-vision, #2672; transformers 4.x quantizes it) fails with "Half and Byte".+ Swap each for a float Linear holding the dequantized weight, as transformers 5 loads it. Returns the count."""+ try:+ import bitsandbytes as bnb+ except Exception:+ return 0+ n = 0+ for module in model.modules():+ if not isinstance(module, torch.nn.MultiheadAttention):+ continue+ out_proj = module.out_proj+ quant_state = getattr(getattr(out_proj, "weight", None), "quant_state", None)+ if not isinstance(out_proj, bnb.nn.Linear4bit) or quant_state is None:+ continue+ dtype = (+ module.in_proj_weight.dtype if module.in_proj_weight is not None else quant_state.dtype+ )+ weight = bnb.functional.dequantize_4bit(out_proj.weight.data, quant_state).to(dtype)+ new = torch.nn.modules.linear.NonDynamicallyQuantizableLinear(+ out_proj.in_features,+ out_proj.out_features,+ bias = out_proj.bias is not None,+ device = "meta",+ )+ new.weight = torch.nn.Parameter(weight, requires_grad = False)+ if out_proj.bias is not None:+ new.bias = out_proj.bias+ if hasattr(out_proj, "_hf_hook"):+ from accelerate.hooks import add_hook_to_module+ add_hook_to_module(new, out_proj._hf_hook)+ module.out_proj = new+ n += 1+ return n++def _restore_dropped_fp8_scales(model,model_name,diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 49f6b481deb..64be4931d58 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -150,6 +150,7 @@ from .loader_utils import (_get_fp8_mode_and_check_settings,_dequantize_leftover_fp8_params,_restore_dropped_fp8_scales,+ _dequantize_multihead_attention_out_proj,_prepare_compressed_tensors_model,_dequantize_bitsandbytes_for_full_finetuning,planner_class_mismatch_reason,@@ -3630,6 +3631,10 @@ class FastBaseModel:variant = kwargs.get("variant"),dtype = torch_dtype,)+ if _dequantize_multihead_attention_out_proj(model):+ logger.info(+ "Unsloth: dequantized 4-bit nn.MultiheadAttention out_proj weights."+ )_prepare_compressed_tensors_model(model, full_finetuning = full_finetuning)if full_finetuning:_dequantize_bitsandbytes_for_full_finetuning(model, torch_dtype, model_name)