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
ROCm: eager batch-1 NF4 decode takes the Triton GEMV (1.8x decode on gfx1151) (#14440)
Daniel Han1f2e2664b7d8
diff --git a/tests/test_bnb_integration_compile.py b/tests/test_bnb_integration_compile.pyindex d66e33cbf80..9637454d43a 100644--- a/tests/test_bnb_integration_compile.py+++ b/tests/test_bnb_integration_compile.py@@ -478,8 +478,9 @@ def test_fast_linear_forward_compiles_fullgraph(nf4_kernels, bsz):def test_eager_gemv_gate_off_takes_bitsandbytes(monkeypatch):- """Where the Triton GEMV is not the eager choice (HIP before Triton 3.7), eager decode takes- bitsandbytes' GEMV, on the live stream. On CUDA the Triton GEMV is the eager choice."""+ """Where the Triton GEMV is not the eager choice (HIP before Triton 3.6, or+ UNSLOTH_TRITON_GEMV_EAGER=0), eager decode takes bitsandbytes' GEMV, on the live stream.+ On CUDA the Triton GEMV is the eager choice."""from unsloth.kernels import nf4_gemvif torch.version.hip is None and _NF4_KERNELS_AVAILABLE:diff --git a/tests/test_nf4_triton_gemv.py b/tests/test_nf4_triton_gemv.pyindex e620f832f07..865bec544a5 100644--- a/tests/test_nf4_triton_gemv.py+++ b/tests/test_nf4_triton_gemv.py@@ -248,6 +248,10 @@ def test_one_row_into_a_taller_out_writes_only_that_row():def test_planned_rows_are_reused_without_an_out(monkeypatch):# fast_geglu_inference calls the gate and up projections with out = None.utils = _utils_with_kernels()+ from unsloth.kernels import triton_launch++ if not triton_launch._ENABLED:+ pytest.skip("plans are kept only with the direct launcher (off on HIP)")monkeypatch.setattr(utils, "_gemv_rows_cap", lambda device: 4)proj = _linear4bit(1024, 4096)W, W_quant = utils.get_lora_parameters_bias(proj)[:2]@@ -505,3 +509,96 @@ def test_the_bnb_gemm_runs_only_on_listed_archs_unless_forced(env, monkeypatch):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")+++ "hip, triton_version, env, eager",+ [+ (None, (3, 2), None, True),+ (None, (3, 6), None, True),+ (None, (3, 7), None, True),+ (None, (3, 6), "0", False),+ (None, (3, 6), "1", True),+ ("7.1", (3, 4), None, False),+ ("7.1", (3, 5), None, False),+ ("7.1", (3, 6), None, True),+ ("7.1", (3, 7), None, True),+ ("7.1", (3, 6), "0", False),+ ("7.1", (3, 5), "1", True),+ ("7.1", (3, 5), "yes", False),+ ],+)+def test_eager_gemv_gate_per_platform(monkeypatch, hip, triton_version, env, eager):+ """CUDA always; HIP from Triton 3.6; UNSLOTH_TRITON_GEMV_EAGER=0 / =1 overrides, others ignored."""+ monkeypatch.setattr(torch.version, "hip", hip)+ monkeypatch.setattr(nf4_gemv, "_TRITON_VERSION", triton_version)+ if env is None:+ monkeypatch.delenv("UNSLOTH_TRITON_GEMV_EAGER", raising = False)+ else:+ monkeypatch.setenv("UNSLOTH_TRITON_GEMV_EAGER", env)+ assert nf4_gemv.triton_gemv_eager() is eager++[email protected]("env", [None, "0"], ids = ["default", "switch_off"])+def test_rocm_batch_1_decode_takes_the_triton_gemv(monkeypatch, env):+ """A faked ROCm torch with Triton 3.6 (Triton's own launch path, as on HIP): batch-1 decode+ takes the Triton GEMV unless switched off, and decode rows still dequantize."""+ from unsloth.kernels import triton_launch, utils++ if not utils._USE_NF4_KERNELS:+ pytest.skip("NF4 kernels unavailable or disabled")+ monkeypatch.setattr(torch.version, "hip", "7.1")+ monkeypatch.setattr(nf4_gemv, "_TRITON_VERSION", (3, 6))+ monkeypatch.setattr(triton_launch, "_ENABLED", False)+ if env is None:+ monkeypatch.delenv("UNSLOTH_TRITON_GEMV_EAGER", raising = False)+ else:+ monkeypatch.setenv("UNSLOTH_TRITON_GEMV_EAGER", env)+ monkeypatch.delenv("UNSLOTH_GEMV_MAX_ROWS", raising = False)+ monkeypatch.setattr(utils, "_TRITON_GEMV_EAGER", nf4_gemv.triton_gemv_eager())+ monkeypatch.setattr(utils, "_GEMV_ROWS_CAP", {})+ calls = []+ for name in ("_fast_gemv_ctypes", "gemv_nf4_planned", "gemv_nf4"):+ real = getattr(utils, name)+ monkeypatch.setattr(+ utils, name, lambda *a, _r = real, _n = name, **k: calls.append(_n) or _r(*a, **k)+ )+ proj = _linear4bit(1024, 4096)+ q, s = proj.weight.data, proj.weight.quant_state+ X = torch.randn(1, 1, 4096, dtype = torch.bfloat16, device = "cuda")+ triton_out = gemv_nf4(X, *_args(q, s))+ bnb_out = _fast_gemv_ctypes(X, q, s)+ for _ in range(3):+ calls.clear()+ got = utils.fast_linear_forward(proj, X)+ if env is None:+ assert calls == ["gemv_nf4_planned"] and torch.equal(got, triton_out)+ else:+ assert calls == ["_fast_gemv_ctypes"] and torch.equal(got, bnb_out)+ assert getattr(s, "_unsloth_gemv_plan", None) is None # no direct relaunch on HIP+ X2 = torch.randn(2, 1, 4096, dtype = torch.bfloat16, device = "cuda")+ assert utils._gemv_rows(X2, q, s, None) is None++[email protected]("nested", [True, False], ids = ["nested", "flat"])[email protected]("dtype", DTYPES, ids = str)[email protected]("shape", SHAPES + [(12288, 4096), (256, 256)], ids = str)+def test_eager_decode_route_matches_dequantize_matmul(shape, dtype, nested):+ """The route eager batch-1 decode takes on this GPU (on ROCm with Triton 3.6+, the Triton+ GEMV) against dequantize + fp32 matmul, on the Llama 3 8B / Qwen3 8B decode shapes. Reruns+ of a weight's planned launch must give the same result."""+ from unsloth.kernels import utils++ if torch.version.hip and nf4_gemv._TRITON_VERSION >= nf4_gemv._HIP_EAGER_MIN_TRITON:+ assert utils._USE_NF4_KERNELS and utils._TRITON_GEMV_EAGER, "ROCm decode kept bitsandbytes"+ if not nested and not (utils._USE_NF4_KERNELS and utils._TRITON_GEMV_EAGER):+ pytest.skip("the ctypes GEMV only takes double quantized states")+ n, k = shape+ q, s = _quant(n, k, dtype, nested)+ X = torch.randn(1, 1, k, dtype = dtype, device = "cuda")+ ref = (X.float().view(1, k) @ utils.fast_dequantize(q, s).float().t()).view(1, 1, n)+ got = utils.fast_gemv(X, q, s)+ assert got.shape == (1, 1, n) and got.dtype == dtype+ assert _rel_err(got, ref) < TOL[dtype]+ for _ in range(2):+ assert torch.equal(utils.fast_gemv(X, q, s), got)diff --git a/unsloth/kernels/nf4_gemv.py b/unsloth/kernels/nf4_gemv.pyindex 97c73e6c94c..a78e4e0fce9 100644--- a/unsloth/kernels/nf4_gemv.py+++ b/unsloth/kernels/nf4_gemv.py@@ -161,17 +161,24 @@ def _gemv_nf4_words_kernel(tl.store(OUT + rows, acc.to(OUT.dtype.element_ty), mask = rmask)-_TRITON_37 = tuple(int(x) for x in triton.__version__.split(".")[:2]) >= (3, 7)+_TRITON_VERSION = tuple(int(x) for x in triton.__version__.split(".")[:2])+_TRITON_37 = _TRITON_VERSION >= (3, 7)# None picks per GPU and Triton version below; "bytes" or "words" forces one kernel (tests, sweeps)._FORCE_KERNEL = None+# Oldest Triton whose eager GEMV was measured faster than bitsandbytes' on HIP (gfx1151, Triton 3.6).+_HIP_EAGER_MIN_TRITON = (3, 6)def triton_gemv_eager(device = None):"""Whether eager (uncompiled) decode should take the Triton GEMV. On CUDA it does: with thedirect launch (triton_launch.py) it beat bitsandbytes' GEMV in batch-1 decode on T4, L4, A100,- RTX PRO 6000 and B200. HIP launches through Triton's own path, which only paid off from- Triton 3.7."""- return torch.version.hip is None or _TRITON_37+ RTX PRO 6000 and B200. HIP launches through Triton's own path; on gfx1151 with Triton 3.6 the+ words kernel still ran Llama 8B decode shapes 1.5x to 3.4x faster than bitsandbytes' GEMV.+ UNSLOTH_TRITON_GEMV_EAGER=0 keeps bitsandbytes' GEMV, =1 takes the Triton GEMV on any GPU."""+ env = os.environ.get("UNSLOTH_TRITON_GEMV_EAGER")+ if env in ("0", "1"):+ return env == "1"+ return torch.version.hip is None or _TRITON_VERSION >= _HIP_EAGER_MIN_TRITONdef _word_aligned(W):