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
NF4 decode on T4: use the bitsandbytes 4-bit GEMM above the GEMV row cap (#14386)
Daniel Han9731b3ace7dc
diff --git a/tests/test_nf4_triton_gemv.py b/tests/test_nf4_triton_gemv.pyindex 9d12519075c..e620f832f07 100644--- a/tests/test_nf4_triton_gemv.py+++ b/tests/test_nf4_triton_gemv.py@@ -169,11 +169,12 @@ def _linear4bit(n,k,seed = 0,+ dtype = torch.bfloat16,):bnb = pytest.importorskip("bitsandbytes")torch.manual_seed(seed)- proj = bnb.nn.Linear4bit(k, n, bias = False, compute_dtype = torch.bfloat16, quant_type = "nf4")- W = torch.randn(n, k, dtype = torch.bfloat16)+ proj = bnb.nn.Linear4bit(k, n, bias = False, compute_dtype = dtype, quant_type = "nf4")+ W = torch.randn(n, k, dtype = dtype)proj.weight = bnb.nn.Params4bit(W, requires_grad = False, quant_type = "nf4")return proj.to("cuda")@@ -205,6 +206,8 @@ def test_small_decode_batches_skip_the_dequantize(bsz, monkeypatch):@ F.dequantize_4bit(proj.weight.data, proj.weight.quant_state).float().t())monkeypatch.setattr(utils, "_gemv_rows_cap", lambda device: 4)+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT", True)+ monkeypatch.setattr(utils, "_bnb_gemm_4bit_device_ok", lambda device: True)monkeypatch.setattr(utils, "fast_dequantize", lambda *a, **k: pytest.fail("dequantized"))first = utils.fast_linear_forward(proj, X)assert _rel_err(first.view(bsz, -1), ref) < TOL[torch.bfloat16]@@ -407,3 +410,98 @@ def test_small_and_odd_k_tiles_match_fp32(shape, dtype, rows, kernel):out = torch.empty(rows, 1, n, dtype = dtype, device = "cuda")gemv_nf4_rows(X, *a[:-1], out)assert _rel_err(out.view(rows, n), ref) < TOL[dtype]+++def _bnb_gemm_utils():+ from unsloth.kernels import utils+ if not hasattr(torch.ops.bitsandbytes, "gemm_4bit") or torch.version.hip:+ pytest.skip("bitsandbytes has no fused gemm_4bit here")+ return utils++[email protected]("bsz", [5, 8, 16])+def test_decode_rows_above_the_gemv_cap_use_the_bnb_gemm(bsz, monkeypatch):+ utils = _bnb_gemm_utils()+ proj = _linear4bit(1024, 4096, dtype = torch.float16)+ X = torch.randn(bsz, 1, 4096, dtype = torch.float16, device = "cuda")+ ref = (+ X.float().view(bsz, -1)+ @ F.dequantize_4bit(proj.weight.data, proj.weight.quant_state).float().t()+ )+ monkeypatch.setattr(utils, "_gemv_rows_cap", lambda device: 4)+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT", True)+ monkeypatch.setattr(utils, "_bnb_gemm_4bit_device_ok", lambda device: True)+ monkeypatch.setattr(utils, "fast_dequantize", lambda *a, **k: pytest.fail("dequantized"))+ with torch.no_grad():+ first = utils.fast_linear_forward(proj, X)+ assert first.shape == (bsz, 1, 1024)+ assert _rel_err(first.view(bsz, -1), ref) < TOL[torch.float16]+ out = torch.empty(bsz, 1, 1024, dtype = torch.float16, device = "cuda")+ assert utils.fast_linear_forward(proj, X, out = out) is out+ assert torch.equal(out, first)+++ "case",+ [+ "switch_off",+ "other_arch",+ "too_many_rows",+ "grad",+ "bf16",+ "weight_elsewhere",+ "unaligned_k",+ ],+)+def test_the_bnb_gemm_is_skipped_where_it_does_not_apply(case, monkeypatch):+ utils = _bnb_gemm_utils()+ bsz = utils._BNB_GEMM_4BIT_MAX_ROWS + 1 if case == "too_many_rows" else 8+ dtype = torch.bfloat16 if case == "bf16" else torch.float16+ proj = _linear4bit(1024, 4096, dtype = dtype)+ X = torch.randn(bsz, 1, 4096, dtype = dtype, device = "cuda")+ monkeypatch.setattr(utils, "_gemv_rows_cap", lambda device: 4)+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT", case != "switch_off")+ if case == "other_arch":+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT_ARCHS", set())+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT_DEVICE", {})+ else:+ monkeypatch.setattr(utils, "_bnb_gemm_4bit_device_ok", lambda device: True)+ if case == "unaligned_k":+ # K not a multiple of the 64 blocksize.+ proj = _linear4bit(1024, 4128, dtype = dtype)+ X = torch.randn(bsz, 1, 4128, dtype = dtype, device = "cuda")+ if case == "weight_elsewhere":+ assert not utils._bnb_gemm_4bit_ok(+ X.view(bsz, -1), proj.weight.data.cpu(), proj.weight.quant_state+ )+ return+ calls = []+ real = utils.fast_dequantize+ monkeypatch.setattr(utils, "fast_dequantize", lambda *a, **k: calls.append(1) or real(*a, **k))+ with torch.set_grad_enabled(case == "grad"):+ utils.fast_linear_forward(proj, X)+ assert calls, case++[email protected]("env", [None, "0", "1"])+def test_the_bnb_gemm_runs_only_on_listed_archs_unless_forced(env, monkeypatch):+ utils = _bnb_gemm_utils()+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT", None)+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT_DEVICE", {})+ monkeypatch.setattr(utils, "_BNB_GEMM_4BIT_DTYPES", utils._BNB_GEMM_4BIT_DTYPES)+ if env is None:+ monkeypatch.delenv("UNSLOTH_BNB_GEMM_4BIT", raising = False)+ else:+ monkeypatch.setenv("UNSLOTH_BNB_GEMM_4BIT", env)+ proj = _linear4bit(1024, 4096, dtype = torch.float16)+ X = torch.randn(8, 4096, dtype = torch.float16, device = "cuda")+ listed = [+ torch.cuda.get_device_capability(i) in utils._BNB_GEMM_4BIT_ARCHS+ for i in range(torch.cuda.device_count())+ ]+ with torch.no_grad():+ ok = utils._bnb_gemm_4bit_ok(X, proj.weight.data, proj.weight.quant_state)+ # Decided once for the process: off when no visible GPU is listed, so the decode loop skips the check.+ assert utils._BNB_GEMM_4BIT == (env != "0" and (env == "1" or any(listed)))+ assert ok == (env != "0" and (env == "1" or listed[X.device.index]))+ assert (torch.bfloat16 in utils._BNB_GEMM_4BIT_DTYPES) == (env == "1")diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.pyindex b78385f5efd..d9fa8a8f086 100644--- a/unsloth/kernels/utils.py+++ b/unsloth/kernels/utils.py@@ -1482,6 +1482,70 @@ def _gemv_rows_cap(device):return cap+# bitsandbytes >= 0.50 fused 4-bit GEMM above the GEMV cap: faster end to end only where the GPU, not the+# launch loop, bounds decode (T4; slower on A100). UNSLOTH_BNB_GEMM_4BIT=0 off, =1 any arch and dtype.+_BNB_GEMM_4BIT_MAX_ROWS = 16+_BNB_GEMM_4BIT_ARCHS = {(7, 5)}+# sm75 has fp16 MMA only: bitsandbytes itself dequantizes bf16 batches of 8+ there.+_BNB_GEMM_4BIT_DTYPES = (torch.float16,)+# None = undecided; False lets fast_linear_forward skip the check.+_BNB_GEMM_4BIT = None+_BNB_GEMM_4BIT_DEVICE = {}+++def _bnb_gemm_4bit_arch_ok(device):+ return (+ os.environ.get("UNSLOTH_BNB_GEMM_4BIT") == "1"+ or torch.cuda.get_device_capability(device) in _BNB_GEMM_4BIT_ARCHS+ )+++def _bnb_gemm_4bit_device_ok(device):+ index = device.index+ ok = _BNB_GEMM_4BIT_DEVICE.get(index)+ if ok is None:+ try:+ ok = _bnb_gemm_4bit_arch_ok(device)+ except Exception:+ ok = False+ _BNB_GEMM_4BIT_DEVICE[index] = ok+ return ok+++def _bnb_gemm_4bit_ok(X, W, quant_state):+ global _BNB_GEMM_4BIT, _BNB_GEMM_4BIT_DTYPES+ if _BNB_GEMM_4BIT is None:+ if os.environ.get("UNSLOTH_BNB_GEMM_4BIT") == "1":+ _BNB_GEMM_4BIT_DTYPES = (torch.float16, torch.bfloat16)+ try:+ _BNB_GEMM_4BIT = (+ bnb is not None+ and torch.version.hip is None+ and os.environ.get("UNSLOTH_BNB_GEMM_4BIT") != "0"+ and hasattr(torch.ops.bitsandbytes, "gemm_4bit")+ and any(_bnb_gemm_4bit_arch_ok(i) for i in range(torch.cuda.device_count()))+ )+ except Exception:+ _BNB_GEMM_4BIT = False+ return (+ _BNB_GEMM_4BIT+ and X.dtype in _BNB_GEMM_4BIT_DTYPES+ and X.is_cuda+ and _bnb_gemm_4bit_device_ok(X.device)+ # bitsandbytes passes raw pointers to the kernel on X's device.+ and W.device == X.device+ and type(quant_state) is not list+ and quant_state.absmax.device == X.device+ and getattr(quant_state, "quant_type", None) in ("nf4", "fp4")+ # bitsandbytes dequantizes (and warns) itself when K is not a multiple of the blocksize.+ and quant_state.shape[-1] % quant_state.blocksize == 0+ # matmul_4bit raises for any other nested blocksize.+ and (not quant_state.nested or quant_state.state2.blocksize == 256)+ and not torch.is_grad_enabled()+ and not _is_compiling()+ )++def _gemv_rows(X, W, quant_state, out):"""One gemv_nf4_rows launch for 2.._GEMV_MAX_ROWS decode rows (#2798); None = dequantize."""M = X.shape[0]@@ -1631,6 +1695,12 @@ def fast_linear_forward(and (rows := _gemv_rows(X, W, W_quant, out)) is not None):out = rows+ elif (+ _BNB_GEMM_4BIT is not False+ and bsz <= _BNB_GEMM_4BIT_MAX_ROWS+ and _bnb_gemm_4bit_ok(X, W, W_quant)+ ):+ out = bnb.matmul_4bit(X, W.t(), quant_state = W_quant, out = out)else:W = fast_dequantize(W.t(), W_quant, use_global_buffer = True)out = torch_matmul(X, W, out = out)