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
FP8 block GEMM: TMA descriptor kernel with a 4-stage K loop on B200 (#15136)
Daniel Han8f6e39d6d48c
diff --git a/tests/test_fp8_tma_block_gemm.py b/tests/test_fp8_tma_block_gemm.pynew file mode 100644index 00000000000..0b93e0c37b4--- /dev/null+++ b/tests/test_fp8_tma_block_gemm.py@@ -0,0 +1,95 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Block FP8 GEMM: the TMA descriptor kernel (datacenter Blackwell) must match the pointer kernel bit for bit."""++import pytest+import torch++if not torch.cuda.is_available() or torch.version.hip is not None:+ pytest.skip("needs an NVIDIA CUDA device", allow_module_level = True)++from unsloth.kernels import fp8 as fp8_mod+++def _inputs(+ M,+ N,+ K,+ seed = 0,+):+ g = torch.Generator(device = "cuda").manual_seed(seed)+ A = torch.randn(M, K, device = "cuda", generator = g, dtype = torch.float32).to(torch.bfloat16)+ W = torch.randn(N, K, device = "cuda", generator = g) * 0.05+ nb, kb = -(-N // 128), -(-K // 128)+ Wp = torch.zeros(nb * 128, kb * 128, device = "cuda")+ Wp[:N, :K] = W+ s = Wp.view(nb, 128, kb, 128).abs().amax(dim = (1, 3)).clamp(min = 1e-12) / 448.0+ Wq = (Wp.view(nb, 128, kb, 128) / s[:, None, :, None]).view(nb * 128, kb * 128)[:N, :K]+ Wq = Wq.contiguous().to(torch.float8_e4m3fn)+ qa, sa = fp8_mod.act_quant(A, 128) if K % 128 == 0 else (None, None)+ return A, Wq, s.contiguous(), qa, sa+++def _pointer(qa, Wq, sa, Ws, dtype, monkeypatch):+ monkeypatch.setattr(fp8_mod, "_FP8_TMA_GEMM", False)+ out = fp8_mod.w8a8_block_fp8_matmul_triton(qa, Wq, sa, Ws, [128, 128], output_dtype = dtype)+ monkeypatch.undo()+ return out+++def _blackwell():+ return torch.cuda.get_device_capability()[0] == 10++[email protected](not _blackwell(), reason = "TMA block FP8 GEMM only routes on sm_100")+ "M, N, K",+ [+ (8192, 4096, 4096),+ (200, 256, 512),+ (1000, 6144, 4096),+ (4096, 4160, 1024),+ (300, 1024, 14336),+ ],+)[email protected]("dtype", [torch.bfloat16, torch.float16, torch.float32])+def test_tma_matches_pointer_kernel_bitwise(M, N, K, dtype, monkeypatch):+ _, Wq, Ws, qa, sa = _inputs(M, N, K)+ calls = []+ real = fp8_mod._launch_fp8_tma_gemm+ monkeypatch.setattr(+ fp8_mod, "_launch_fp8_tma_gemm", lambda *a: (calls.append(a[5]), real(*a))[1]+ )+ out = fp8_mod.w8a8_block_fp8_matmul_triton(qa, Wq, sa, Ws, [128, 128], output_dtype = dtype)+ monkeypatch.undo()+ assert (+ M in calls+ ), "TMA path did not run for this GEMM" # a[5] is M; the self check uses M = 200+ assert fp8_mod._FP8_TMA_GEMM, "self check disabled the TMA path"+ ref = _pointer(qa, Wq, sa, Ws, dtype, monkeypatch)+ bits = {2: torch.int16, 4: torch.int32}[out.element_size()]+ assert torch.equal(out.view(bits), ref.view(bits))++[email protected](not _blackwell(), reason = "TMA block FP8 GEMM only routes on sm_100")+def test_kill_switch_and_small_m_use_the_pointer_kernel(monkeypatch):+ _, Wq, Ws, qa, sa = _inputs(256, 256, 256)+ calls = []+ monkeypatch.setattr(fp8_mod, "_launch_fp8_tma_gemm", lambda *a: calls.append(1))+ monkeypatch.setattr(fp8_mod, "_FP8_TMA_GEMM", False)+ fp8_mod.w8a8_block_fp8_matmul_triton(qa, Wq, sa, Ws, [128, 128], output_dtype = torch.bfloat16)+ monkeypatch.setattr(fp8_mod, "_FP8_TMA_GEMM", True)+ _, Wq, Ws, qa, sa = _inputs(64, 256, 256) # M < 128 -> 64-row tiles, pointer kernel+ fp8_mod.w8a8_block_fp8_matmul_triton(qa, Wq, sa, Ws, [128, 128], output_dtype = torch.bfloat16)+ assert calls == []++[email protected]("capability", [(7, 5), (8, 0), (8, 9), (9, 0), (12, 0)])+def test_other_archs_never_route_to_tma(capability, monkeypatch):+ fp8_mod._fp8_tma_gemm_arch_at.cache_clear()+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda index = None: capability)+ try:+ assert fp8_mod._fp8_tma_gemm_arch_at(0) is False+ finally:+ fp8_mod._fp8_tma_gemm_arch_at.cache_clear()diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex 9775287ff7b..b3cd321cfc4 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -478,6 +478,208 @@ def _w8a8_block_fp8_matmul(tl.store(c_ptrs, c, mask = c_mask)+try:+ from triton.tools.tensor_descriptor import TensorDescriptor as _TensorDescriptor+except Exception:+ _TensorDescriptor = None++# UNSLOTH_FP8_TMA_GEMM=0 keeps the pointer kernel above on every GPU.+_FP8_TMA_GEMM = os.environ.get("UNSLOTH_FP8_TMA_GEMM", "1").strip().lower() not in (+ "0",+ "false",+ "no",+ "off",+)+_TL_OUT_DTYPES = {torch.bfloat16: tl.bfloat16, torch.float16: tl.float16, torch.float32: tl.float32}+++def _w8a8_block_fp8_matmul_tma(+ a_desc,+ b_desc,+ c_desc,+ As,+ Bs,+ M,+ N,+ K,+ stride_As_m,+ stride_As_k,+ stride_Bs_k,+ stride_Bs_n,+ BLOCK_SIZE_M: tl.constexpr,+ BLOCK_SIZE_N: tl.constexpr,+ BLOCK_SIZE_K: tl.constexpr,+ GROUP_SIZE_M: tl.constexpr,+ NUM_STAGES: tl.constexpr,+ OUT_DTYPE: tl.constexpr,+):+ # _w8a8_block_fp8_matmul with A, B and C moved by TMA descriptors (out-of-range rows and K tail+ # are zero filled on load, clipped on store) and a pipelined K loop; same per-tile math and order,+ # so outputs are bitwise identical. BLOCK_SIZE_N == group_n and BLOCK_SIZE_K == group_k.+ pid = tl.program_id(axis = 0)+ num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)+ num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)+ num_pid_in_group = GROUP_SIZE_M * num_pid_n+ group_id = pid // num_pid_in_group+ first_pid_m = group_id * GROUP_SIZE_M+ group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)+ pid_m = first_pid_m + (pid % group_size_m)+ pid_n = (pid % num_pid_in_group) // group_size_m++ offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M+ As_ptrs = As + offs_am * stride_As_m+ Bs_ptrs = Bs + pid_n * stride_Bs_n++ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype = tl.float32)+ for k in tl.range(0, tl.cdiv(K, BLOCK_SIZE_K), num_stages = NUM_STAGES):+ a = a_desc.load([pid_m * BLOCK_SIZE_M, k * BLOCK_SIZE_K])+ b = b_desc.load([pid_n * BLOCK_SIZE_N, k * BLOCK_SIZE_K])+ a_s = tl.load(As_ptrs + k * stride_As_k)+ b_s = tl.load(Bs_ptrs + k * stride_Bs_k)+ accumulator += tl.dot(a, b.T) * a_s[:, None] * b_s+ c_desc.store([pid_m * BLOCK_SIZE_M, pid_n * BLOCK_SIZE_N], accumulator.to(OUT_DTYPE))++[email protected]_cache(maxsize = None)+def _fp8_tma_gemm_arch_at(index):+ # Measured on B200 only (2.2-2.4x over the pointer kernel at 8192-token training shapes): 4 stages+ # of 128 x 128 fp8 A and B tiles need 128 KB of shared memory, more than sm_120 / sm_89 have.+ return torch.version.hip is None and torch.cuda.get_device_capability(index)[0] == 10+++def _fp8_tma_gemm_disable(reason):+ global _FP8_TMA_GEMM+ if _FP8_TMA_GEMM:+ _FP8_TMA_GEMM = False+ logger.warning(+ f"Unsloth: TMA block FP8 GEMM disabled ({reason}); using the pointer kernel."+ )+++def _fp8_tma_gemm_ok(A, B, C, BLOCK_SIZE_M, block_n, block_k, long_idx):+ if not _FP8_TMA_GEMM or _TensorDescriptor is None or torch.compiler.is_compiling():+ return False+ if A.device.type != "cuda" or C.dtype not in _TL_OUT_DTYPES or long_idx:+ return False+ if BLOCK_SIZE_M != 128 or block_n != 128 or block_k != 128:+ return False+ K = A.shape[-1]+ N = B.shape[0]+ # TMA: 16-byte aligned bases and row pitches.+ if K % 16 != 0 or (N * C.element_size()) % 16 != 0:+ return False+ if A.data_ptr() % 16 or B.data_ptr() % 16 or C.data_ptr() % 16:+ return False+ index = A.device.index if A.device.index is not None else torch.cuda.current_device()+ if not _fp8_tma_gemm_arch_at(index):+ return False+ checked = _FP8_TMA_SELF_CHECKED.get(index)+ if checked is None:+ if torch.cuda.is_current_stream_capturing():+ return False # the self check allocates and syncs: run it outside graph capture+ checked = _FP8_TMA_SELF_CHECKED[index] = _fp8_tma_gemm_self_check(index)+ return checked+++def _launch_fp8_tma_gemm(A, B, C, As, Bs, M, N, K, block_n, block_k):+ BLOCK_SIZE_M = 128+ a_desc = _TensorDescriptor.from_tensor(A.view(M, K), [BLOCK_SIZE_M, block_k])+ b_desc = _TensorDescriptor.from_tensor(B, [block_n, block_k])+ c_desc = _TensorDescriptor.from_tensor(C.view(M, N), [BLOCK_SIZE_M, block_n])+ grid = (triton.cdiv(M, BLOCK_SIZE_M) * triton.cdiv(N, block_n),)+ _w8a8_block_fp8_matmul_tma[grid](+ a_desc,+ b_desc,+ c_desc,+ As,+ Bs,+ M,+ N,+ K,+ As.stride(-2),+ As.stride(-1),+ Bs.stride(1),+ Bs.stride(0),+ BLOCK_SIZE_M = BLOCK_SIZE_M,+ BLOCK_SIZE_N = block_n,+ BLOCK_SIZE_K = block_k,+ GROUP_SIZE_M = 8,+ NUM_STAGES = 4,+ OUT_DTYPE = _TL_OUT_DTYPES[C.dtype],+ num_warps = 8,+ enable_fp_fusion = True,+ )+++def _fp8_gemm_must_raise(error):+ return (+ isinstance(error, torch.cuda.OutOfMemoryError)+ or type(error).__module__.startswith(("torch._dynamo", "torch._inductor"))+ or torch.compiler.is_compiling()+ )+++_FP8_TMA_SELF_CHECKED = {}+++def _fp8_tma_gemm_self_check(index):+ # Once per device: the TMA kernel must reproduce the pointer kernel bit for bit (ragged M, K tail).+ from torch.utils._python_dispatch import _disable_current_modes++ device = torch.device("cuda", index)+ try:+ with _disable_current_modes(), torch.no_grad():+ g = torch.Generator(device = device).manual_seed(3407)+ M, N, K = 200, 256, 400+ A = (torch.randn(M, K, device = device, generator = g) * 4).to(torch.float8_e4m3fn)+ B = (torch.randn(N, K, device = device, generator = g) * 4).to(torch.float8_e4m3fn)+ As = torch.rand(M, 4, device = device, generator = g) + 0.5+ Bs = torch.rand(2, 4, device = device, generator = g) + 0.5+ ref = torch.empty(M, N, device = device, dtype = torch.bfloat16)+ out = torch.empty_like(ref)+ with _disable_current_modes(), torch.no_grad(), _fp8_triton_device_context(A):+ _w8a8_block_fp8_matmul[(2 * 2,)](+ A,+ B,+ ref,+ As,+ Bs,+ M,+ N,+ K,+ 128,+ 128,+ A.stride(-2),+ A.stride(-1),+ B.stride(1),+ B.stride(0),+ ref.stride(-2),+ ref.stride(-1),+ As.stride(-2),+ As.stride(-1),+ Bs.stride(1),+ Bs.stride(0),+ BLOCK_SIZE_M = 128,+ BLOCK_SIZE_N = 128,+ BLOCK_SIZE_K = 128,+ GROUP_SIZE_M = 8,+ LONG_INDEXING = False,+ num_warps = 8,+ enable_fp_fusion = True,+ )+ _launch_fp8_tma_gemm(A, B, out, As, Bs, M, N, K, 128, 128)+ ok = torch.equal(out.view(torch.int16), ref.view(torch.int16))+ except Exception as error:+ if _fp8_gemm_must_raise(error):+ raise+ _fp8_tma_gemm_disable(f"{type(error).__name__}: {error}")+ return False+ if not ok:+ _fp8_tma_gemm_disable("self check mismatch")+ return ok++@_opaque_under_compile("fp8_block_matmul_triton",lambda A, B, As, Bs, block_size, output_dtype = torch.float32: A.new_empty(@@ -519,7 +721,16 @@ def w8a8_block_fp8_matmul_triton(def grid(META):return (triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]),)+ LONG_INDEXING = long_indexing(A, B, C)with _fp8_triton_device_context(A):+ if _fp8_tma_gemm_ok(A, B, C, BLOCK_SIZE_M, block_n, block_k, LONG_INDEXING):+ try:+ _launch_fp8_tma_gemm(A, B, C, As, Bs, M, N, K, block_n, block_k)+ return C+ except Exception as error:+ if _fp8_gemm_must_raise(error):+ raise+ _fp8_tma_gemm_disable(f"{type(error).__name__}: {error}")_w8a8_block_fp8_matmul[grid](A,B,@@ -545,7 +756,7 @@ def w8a8_block_fp8_matmul_triton(BLOCK_SIZE_N = BLOCK_SIZE_N,BLOCK_SIZE_K = BLOCK_SIZE_K,GROUP_SIZE_M = 8,- LONG_INDEXING = long_indexing(A, B, C),+ LONG_INDEXING = LONG_INDEXING,# Default 4 warps starve 128x128 tiles (8 is 1.3-2.1x faster from M >= 128); smaller decode tiles gain nothing.num_warps = 8 if BLOCK_SIZE_M == 128 else 4,enable_fp_fusion = True,