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.

Studio diffusion: load the int8 GEMM operands through TMA descriptors on sm120 (#15829)

Daniel Han6cdce47fecbe
diff --git a/studio/backend/core/inference/diffusion_int8_gemm.py b/studio/backend/core/inference/diffusion_int8_gemm.py
index af744793d03..c14488cd940 100644
--- a/studio/backend/core/inference/diffusion_int8_gemm.py
+++ b/studio/backend/core/inference/diffusion_int8_gemm.py
@@ -4,6 +4,7 @@
"""int8 GEMM with torchao dequant epilogue in Triton, bf16 out; sm80/sm89/sm120 measured, other sm80+ behind a
bit-exact probe and a latency check (UNSLOTH_DIFFUSION_INT8_GEMM_UNLISTED=0 keeps them stock), sm100 / sm103 stock
(ROCm and CPU never reach it); Linear output bit-identical, compiled block not end to end;
+sm120 loads its operands through TMA descriptors (UNSLOTH_DIFFUSION_INT8_GEMM_TMA=0 keeps pointer loads);
UNSLOTH_DIFFUSION_INT8_GEMM=0 disables."""
from __future__ import annotations
@@ -21,6 +22,7 @@ INT8_GEMM_STREAMED_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED"
INT8_GEMM_TILES_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_TILES"
INT8_SWIGLU_STREAMED_ENV = "UNSLOTH_DIFFUSION_INT8_SWIGLU_STREAMED"
INT8_GEMM_UNLISTED_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_UNLISTED"
+INT8_GEMM_TMA_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_TMA"
_MIN_TRITON = (3, 2)
# torch._int_mm needs M > 16; below that the stock path (safe_int_mm padding) stays in charge.
_MIN_ROWS = 17
@@ -38,6 +40,7 @@ _LOCK = threading.Lock()
_OP_HANDLE: Any = None
# Engagement census; never read inside a traced region.
_CALLS = [0]
+_TMA_CALLS = [0]
# (BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, num_warps, num_stages) per (major, minor), tuned on DiT shapes. Absent = off.
_ARCH_CONFIG = {
@@ -69,6 +72,10 @@ _SHAPE_TILES: dict = {
}
_SHAPE_MIN_M = 1024
+# Same kernel and epilogue with host TMA descriptors for A / W, one tile for M >= _SHAPE_MIN_M (replaces
+# _SHAPE_TILES there); below that the pointer-load kernel is faster.
+_TMA_CONFIG = {(12, 0): (128, 128, 64, 8, 4, 4)}
+
def int8_gemm_mode() -> str:
"""'off', 'force' or 'auto' from the environment."""
@@ -100,6 +107,17 @@ def tiles_enabled() -> bool:
return raw not in ("0", "off", "false", "no")
+def tma_enabled() -> bool:
+ raw = (os.environ.get(INT8_GEMM_TMA_ENV) or "").strip().lower()
+ return raw not in ("0", "off", "false", "no")
+
+
+def tma_config(capability: Optional[tuple]) -> Optional[tuple]:
+ if capability is None or not tma_enabled():
+ return None
+ return _TMA_CONFIG.get((int(capability[0]), int(capability[1])))
+
+
def _triton_version_ok(version: Optional[str] = None) -> bool:
if version is None:
try:
@@ -238,11 +256,69 @@ def _kernels() -> Optional[types.SimpleNamespace]:
mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
tl.store(c_ptrs, y.to(tl.bfloat16), mask = mask)
- return types.SimpleNamespace(i8mm_dq = i8mm_dq)
+ @triton.jit
+ def i8mm_dq_tma(
+ a_desc,
+ w_desc,
+ xs_ptr,
+ ws_ptr,
+ b_ptr,
+ c_ptr,
+ M,
+ N,
+ K,
+ stride_cm,
+ HAS_BIAS: tl.constexpr,
+ XS_FP32: tl.constexpr,
+ WS_FP32: tl.constexpr,
+ BLOCK_M: tl.constexpr,
+ BLOCK_N: tl.constexpr,
+ BLOCK_K: tl.constexpr,
+ GROUP_M: tl.constexpr,
+ ):
+ pid = tl.program_id(0)
+ num_pid_m = tl.cdiv(M, BLOCK_M)
+ num_pid_n = tl.cdiv(N, BLOCK_N)
+ num_pid_in_group = GROUP_M * num_pid_n
+ group_id = pid // num_pid_in_group
+ first_pid_m = group_id * GROUP_M
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
+ pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
+ pid_n = (pid % num_pid_in_group) // group_size_m
+ om = pid_m * BLOCK_M
+ on = pid_n * BLOCK_N
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype = tl.int32)
+ for k in range(0, tl.cdiv(K, BLOCK_K)):
+ a = a_desc.load([om, k * BLOCK_K])
+ b = w_desc.load([on, k * BLOCK_K])
+ acc = tl.dot(a, b.T, acc, out_dtype = tl.int32)
+
+ offs_m = om.to(tl.int64) + tl.arange(0, BLOCK_M)
+ offs_n = on.to(tl.int64) + tl.arange(0, BLOCK_N)
+ rm = offs_m % M
+ rn = offs_n % N
+ xs = tl.load(xs_ptr + rm).to(tl.float32)
+ ws = tl.load(ws_ptr + rn).to(tl.float32)
+ if XS_FP32:
+ y = acc.to(tl.float32)
+ else:
+ y = _rbf16(tl.extra.cuda.libdevice.int2float_rn(acc))
+ y = _rbf16(y * xs[:, None])
+ y = tl.extra.cuda.libdevice.mul_rn(y, ws[None, :])
+ if not WS_FP32:
+ y = _rbf16(y)
+ if HAS_BIAS:
+ y = tl.extra.cuda.libdevice.add_rn(y, tl.load(b_ptr + rn).to(tl.float32)[None, :])
+ c_ptrs = c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :]
+ mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
+ tl.store(c_ptrs, y.to(tl.bfloat16), mask = mask)
+
+ return types.SimpleNamespace(i8mm_dq = i8mm_dq, i8mm_dq_tma = i8mm_dq_tma)
# device index -> probed tile (None = stock).
_DEVICE_CFG: dict = {}
+_DEVICE_TMA: dict = {}
# device index -> the per-shape rules whose tile passed the probe on that device.
_DEVICE_TILES: dict = {}
@@ -300,6 +376,52 @@ def _launch(a: Any, w: Any, xs: Any, ws: Any, bias: Any, cfg: tuple) -> Any:
return out
+@lru_cache(maxsize = 1)
+def _tensor_descriptor() -> Any:
+ try:
+ from triton.tools.tensor_descriptor import TensorDescriptor
+ except Exception: # noqa: BLE001 - Triton before host descriptors
+ return None
+ return TensorDescriptor
+
+
+def _launch_tma(a: Any, w: Any, xs: Any, ws: Any, bias: Any, cfg: tuple) -> Any:
+ import torch
+ import triton
+
+ k = _kernels()
+ desc = _tensor_descriptor()
+ m, kk = a.shape
+ n = w.shape[0]
+ bm, bn, bk, gm, warps, stages = cfg
+ out = torch.empty((m, n), device = a.device, dtype = torch.bfloat16)
+ grid = (triton.cdiv(m, bm) * triton.cdiv(n, bn),)
+ with torch.cuda.device(a.device):
+ k.i8mm_dq_tma[grid](
+ desc.from_tensor(a, [bm, bk]),
+ desc.from_tensor(w, [bn, bk]),
+ xs,
+ ws,
+ bias if bias is not None else ws,
+ out,
+ m,
+ n,
+ kk,
+ out.stride(0),
+ HAS_BIAS = bias is not None,
+ XS_FP32 = xs.dtype == torch.float32,
+ WS_FP32 = ws.dtype == torch.float32,
+ BLOCK_M = bm,
+ BLOCK_N = bn,
+ BLOCK_K = bk,
+ GROUP_M = gm,
+ num_warps = warps,
+ num_stages = stages,
+ enable_fp_fusion = False,
+ )
+ return out
+
+
def _aligned(a: Any, w: Any) -> bool:
"""K, N, both row strides and both int8 base pointers on 16 bytes. Triton specialises on these, and an off-16 variant
spills; the driver then reserves that local memory device-wide for the process, outside PyTorch's allocator."""
@@ -324,6 +446,11 @@ def tile_for(index: Any, m: int, n: int, k: int) -> Optional[tuple]:
return cfg
+def tma_tile_for(index: Any, m: int) -> Optional[tuple]:
+ tile = _DEVICE_TMA.get(index)
+ return None if m < _SHAPE_MIN_M else tile
+
+
def _run(a: Any, w: Any, xs: Any, ws: Any, bias: Any) -> Any:
"""Op body: the probed tile for this device and shape, else (launch failure, ``_aligned`` false) the stock
epilogue."""
@@ -332,6 +459,14 @@ def _run(a: Any, w: Any, xs: Any, ws: Any, bias: Any) -> Any:
index = a.device.index
cfg = tile_for(index, a.shape[0], w.shape[0], a.shape[1])
if cfg is not None and w.stride(-1) == 1 and w.device == a.device and _aligned(a, w):
+ tma = tma_tile_for(index, a.shape[0])
+ if tma is not None:
+ try:
+ out = _launch_tma(a, w, xs, ws, bias, tma)
+ _TMA_CALLS[0] += 1
+ return out
+ except Exception: # noqa: BLE001 - pointer loads, same math
+ _DEVICE_TMA[index] = None
try:
return _launch(a, w, xs, ws, bias, cfg)
except Exception: # noqa: BLE001 - a failed launch keeps the stock math
@@ -382,6 +517,16 @@ def shape_tiles(capability: Optional[tuple]) -> tuple:
return tuple(_SHAPE_TILES.get((int(capability[0]), int(capability[1])), ()))
+def _tma_probe(index: int, capability: tuple) -> Optional[tuple]:
+ """This arch's TMA tile when its kernel matches the eager epilogue bit for bit (``_probe``), else None."""
+ tma = tma_config(capability)
+ try:
+ ok = tma is not None and _tensor_descriptor() is not None and _probe(index, tma, tma = True)
+ except Exception: # noqa: BLE001 - pointer loads stay
+ ok = False
+ return tma if ok else None
+
+
def device_config(index: int) -> Optional[tuple]:
"""Probe once per device: arch gate, Triton, op registration, then a launch that must match the eager torchao
epilogue bit for bit (bf16 and fp32 activation scales, bias, ragged M / N / K). None keeps the stock path. Each
@@ -391,6 +536,7 @@ def device_config(index: int) -> Optional[tuple]:
return unlisted_config(index)
if index in _DEVICE_CFG:
return _DEVICE_CFG[index]
+ _DEVICE_TMA.pop(index, None)
cfg = None
rules: tuple = ()
try:
@@ -418,6 +564,9 @@ def device_config(index: int) -> Optional[tuple]:
if tile not in ok:
ok[tile] = tile == cfg or _probe(index, tile)
rules = tuple(rule for rule in shape_tiles(cap) if ok[rule[4]])
+ tma = _tma_probe(index, cap)
+ if tma is not None:
+ _DEVICE_TMA[index] = tma
except Exception: # noqa: BLE001
cfg = None
_DEVICE_TILES[index] = rules if cfg is not None else ()
@@ -526,9 +675,14 @@ _PROBE_SHAPES = (
)
-def _probe(index: int, cfg: tuple) -> bool:
+def _probe(
+ index: int,
+ cfg: tuple,
+ tma: bool = False,
+) -> bool:
import torch
+ launch = _launch_tma if tma else _launch
dev = torch.device("cuda", index)
g = torch.Generator(device = "cpu").manual_seed(0)
try:
@@ -540,12 +694,12 @@ def _probe(index: int, cfg: tuple) -> bool:
ws = (torch.rand(n, generator = g) * 0.002 + 1e-5).to(torch.bfloat16).to(dev)
ws = ws.float() if xs32 else ws
b = (torch.randn(n, generator = g) * 0.1).to(torch.bfloat16).to(dev) if bias else None
- if not torch.equal(_launch(a, w, xs, ws, b, cfg), reference(a, w, xs, ws, b)):
+ if not torch.equal(launch(a, w, xs, ws, b, cfg), reference(a, w, xs, ws, b)):
return False
a, w = tie_operands(dev)
xs = torch.ones(a.shape[0], device = dev, dtype = torch.bfloat16)
ws = torch.ones(w.shape[0], device = dev, dtype = torch.bfloat16)
- if not torch.equal(_launch(a, w, xs, ws, None, cfg), reference(a, w, xs, ws, None)):
+ if not torch.equal(launch(a, w, xs, ws, None, cfg), reference(a, w, xs, ws, None)):
return False
from .diffusion_cuda_graph import synchronize_outside_capture
@@ -1204,7 +1358,12 @@ def _swap_on(
logger.info(
"diffusion.int8_gemm: %d int8 Linear(s) %s on sm_%d%d%s%s%s",
count,
- "run the fused-dequant GEMM (bf16 out)" if gemm else "keep cuBLAS",
+ (
+ "run the fused-dequant GEMM (bf16 out"
+ + (", TMA loads)" if _DEVICE_TMA.get(index) else ")")
+ )
+ if gemm
+ else "keep cuBLAS",
*torch.cuda.get_device_capability(index),
f" (latency check: {timing['fused']:.0f} vs {timing['stock']:.0f} us cuBLAS)"
if timing
@@ -1298,3 +1457,7 @@ def is_installed(module: Any) -> bool:
def call_count() -> int:
return _CALLS[0]
+
+
+def tma_call_count() -> int:
+ return _TMA_CALLS[0]
diff --git a/studio/backend/tests/test_diffusion_int8_gemm_tma.py b/studio/backend/tests/test_diffusion_int8_gemm_tma.py
new file mode 100644
index 00000000000..2cb11fae871
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_int8_gemm_tma.py
@@ -0,0 +1,296 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the TMA int8 GEMM; kernel tests need an sm90+ GPU with Triton host descriptors."""
+
+from __future__ import annotations
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from core.inference import diffusion_int8_gemm as g8
+
+
+def _reset():
+ for d in (
+ g8._DEVICE_CFG,
+ g8._DEVICE_TILES,
+ g8._DEVICE_TMA,
+ g8._UNLISTED_PROBE,
+ g8._UNLISTED_OK,
+ ):
+ d.clear()
+ g8._UNLISTED_CARDS.clear()
+
+
[email protected](autouse = True)
+def _clean(monkeypatch):
+ for name in (
+ g8.INT8_GEMM_ENV,
+ g8.INT8_GEMM_TMA_ENV,
+ g8.INT8_GEMM_TILES_ENV,
+ g8.INT8_GEMM_UNLISTED_ENV,
+ ):
+ monkeypatch.delenv(name, raising = False)
+ _reset()
+ yield
+ _reset()
+
+
+class _Fake:
+ def __init__(
+ self,
+ monkeypatch,
+ cap,
+ probe = True,
+ tma_probe = True,
+ ):
+ self.probes = []
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda index = None: cap)
+ monkeypatch.setattr(g8, "is_rocm_torch", lambda t: False)
+ monkeypatch.setattr(g8, "_triton_version_ok", lambda version = None: True)
+ monkeypatch.setattr(g8, "_kernels", lambda: object())
+ monkeypatch.setattr(g8, "_op", lambda: "op")
+ monkeypatch.setattr(g8, "_tensor_descriptor", lambda: object())
+
+ def fake_probe(
+ index,
+ cfg,
+ tma = False,
+ ):
+ self.probes.append((cfg, tma))
+ if tma and isinstance(tma_probe, Exception):
+ raise tma_probe
+ return tma_probe if tma else probe
+
+ monkeypatch.setattr(g8, "_probe", fake_probe)
+
+
[email protected]("cap", [(8, 0), (8, 6), (8, 9), (9, 0), (10, 0), (12, 1)])
+def test_tma_only_on_measured_archs(monkeypatch, cap):
+ fake = _Fake(monkeypatch, cap)
+ g8.device_config(0)
+ assert g8._DEVICE_TMA.get(0) is None
+ assert all(not tma for _, tma in fake.probes)
+
+
+def test_sm120_probes_and_arms_the_tma_tile(monkeypatch):
+ fake = _Fake(monkeypatch, (12, 0))
+ assert g8.device_config(0) == g8._ARCH_CONFIG[(12, 0)]
+ assert g8._DEVICE_TMA[0] == g8._TMA_CONFIG[(12, 0)]
+ assert (g8._TMA_CONFIG[(12, 0)], True) in fake.probes
+
+
+def test_tma_tile_only_from_shape_min_m():
+ g8._DEVICE_TMA[0] = g8._TMA_CONFIG[(12, 0)]
+ assert g8.tma_tile_for(0, g8._SHAPE_MIN_M - 1) is None
+ assert g8.tma_tile_for(0, g8._SHAPE_MIN_M) == g8._TMA_CONFIG[(12, 0)]
+ assert g8.tma_tile_for(1, 19315) is None
+
+
[email protected]("value", ["0", "off", "false"])
+def test_kill_switch_keeps_pointer_loads_and_never_probes(monkeypatch, value):
+ monkeypatch.setenv(g8.INT8_GEMM_TMA_ENV, value)
+ fake = _Fake(monkeypatch, (12, 0))
+ assert g8.device_config(0) == g8._ARCH_CONFIG[(12, 0)]
+ assert g8._DEVICE_TMA.get(0) is None
+ assert all(not tma for _, tma in fake.probes)
+
+
[email protected]("result", [False, RuntimeError("no TMA")])
+def test_failed_tma_probe_keeps_the_pointer_kernel(monkeypatch, result):
+ _Fake(monkeypatch, (12, 0), tma_probe = result)
+ assert g8.device_config(0) == g8._ARCH_CONFIG[(12, 0)]
+ assert g8._DEVICE_TMA.get(0) is None
+ assert g8._DEVICE_TILES[0]
+
+
+def test_no_descriptor_api_keeps_the_pointer_kernel(monkeypatch):
+ fake = _Fake(monkeypatch, (12, 0))
+ monkeypatch.setattr(g8, "_tensor_descriptor", lambda: None)
+ assert g8.device_config(0) == g8._ARCH_CONFIG[(12, 0)]
+ assert g8._DEVICE_TMA.get(0) is None
+ assert all(not tma for _, tma in fake.probes)
+
+
+def test_failed_pointer_probe_leaves_everything_off(monkeypatch):
+ _Fake(monkeypatch, (12, 0), probe = False)
+ assert g8.device_config(0) is None
+ assert g8._DEVICE_TMA.get(0) is None
+
+
+def test_reprobe_drops_a_stale_tma_tile(monkeypatch):
+ _Fake(monkeypatch, (12, 0))
+ g8.device_config(0)
+ assert g8._DEVICE_TMA[0]
+ g8._DEVICE_CFG.clear()
+ monkeypatch.setenv(g8.INT8_GEMM_TMA_ENV, "0")
+ g8.device_config(0)
+ assert g8._DEVICE_TMA.get(0) is None
+
+
+class _T:
+ def __init__(self, shape):
+ self.shape = shape
+ self.device = types_device
+
+ def stride(self, dim = None):
+ s = (self.shape[1], 1)
+ return s if dim is None else s[dim]
+
+ def data_ptr(self):
+ return 0
+
+ def contiguous(self):
+ return self
+
+
+class _Dev:
+ index = 0
+
+ def __eq__(self, other):
+ return isinstance(other, _Dev)
+
+
+types_device = _Dev()
+
+
+def _armed(monkeypatch, tma_raises = False):
+ calls = []
+ g8._DEVICE_CFG[0] = g8._ARCH_CONFIG[(12, 0)]
+ g8._DEVICE_TILES[0] = ()
+ g8._DEVICE_TMA[0] = g8._TMA_CONFIG[(12, 0)]
+
+ def tma(a, w, xs, ws, bias, cfg):
+ calls.append(("tma", cfg))
+ if tma_raises:
+ raise RuntimeError("descriptor refused")
+ return "tma-out"
+
+ def ptr(a, w, xs, ws, bias, cfg):
+ calls.append(("ptr", cfg))
+ return "ptr-out"
+
+ monkeypatch.setattr(g8, "_launch_tma", tma)
+ monkeypatch.setattr(g8, "_launch", ptr)
+ monkeypatch.setattr(g8, "reference", lambda *a: "stock-out")
+ return calls
+
+
+def test_run_takes_the_tma_kernel_and_counts_it(monkeypatch):
+ calls = _armed(monkeypatch)
+ before = g8.tma_call_count()
+ assert g8._run(_T((2048, 4096)), _T((4096, 4096)), None, None, None) == "tma-out"
+ assert calls == [("tma", g8._TMA_CONFIG[(12, 0)])]
+ assert g8.tma_call_count() == before + 1
+
+
+def test_tma_launch_failure_falls_back_to_pointer_loads_for_good(monkeypatch):
+ calls = _armed(monkeypatch, tma_raises = True)
+ before = g8.tma_call_count()
+ assert g8._run(_T((2048, 4096)), _T((4096, 4096)), None, None, None) == "ptr-out"
+ assert g8._DEVICE_TMA[0] is None
+ assert g8._run(_T((2048, 4096)), _T((4096, 4096)), None, None, None) == "ptr-out"
+ assert [c[0] for c in calls] == ["tma", "ptr", "ptr"]
+ assert g8.tma_call_count() == before
+
+
+def test_small_m_takes_the_pointer_kernel(monkeypatch):
+ calls = _armed(monkeypatch)
+ assert g8._run(_T((300, 4096)), _T((4096, 4096)), None, None, None) == "ptr-out"
+ assert calls == [("ptr", g8._ARCH_CONFIG[(12, 0)])]
+
+
+def test_misaligned_operands_skip_both_kernels(monkeypatch):
+ calls = _armed(monkeypatch)
+ assert g8._run(_T((2048, 4100)), _T((4096, 4100)), None, None, None) == "stock-out"
+ assert calls == []
+
+
+def _tma_ready() -> bool:
+ try:
+ if not torch.cuda.is_available() or g8.is_rocm_torch(torch):
+ return False
+ if torch.cuda.get_device_capability(0) < (9, 0):
+ return False
+ return g8._kernels() is not None and g8._tensor_descriptor() is not None
+ except Exception: # noqa: BLE001
+ return False
+
+
+needs_tma = pytest.mark.skipif(
+ not _tma_ready(), reason = "needs an sm90+ NVIDIA GPU and Triton host descriptors"
+)
+
+
+@needs_tma
+ "m, k, n, bias, xs32",
+ [
+ (4096, 4096, 4096, False, False),
+ (1037, 528, 1400, True, False),
+ (17, 256, 1024, True, True),
+ (300, 12288, 256, False, False),
+ (2053, 5376, 5376, False, True),
+ ],
+)
[email protected]("ws32", [False, True])
[email protected]("cfg", sorted(set(g8._TMA_CONFIG.values())))
+def test_tma_kernel_is_bit_exact_vs_torchao_epilogue(m, k, n, bias, xs32, ws32, cfg):
+ g = torch.Generator().manual_seed(m + k + n)
+ a = torch.randint(-127, 128, (m, k), generator = g, dtype = torch.int8).cuda()
+ w = torch.randint(-127, 128, (n, k), generator = g, dtype = torch.int8).cuda()
+ xs = (torch.rand(m, generator = g) * 0.02 + 1e-4).to(torch.bfloat16)
+ xs = (xs.float() if xs32 else xs).cuda()
+ ws = (torch.rand(n, generator = g) * 0.002 + 1e-5).to(torch.bfloat16).cuda()
+ ws = ws.float() if ws32 else ws
+ b = (torch.randn(n, generator = g) * 0.1).to(torch.bfloat16).cuda() if bias else None
+ assert torch.equal(g8._launch_tma(a, w, xs, ws, b, cfg), g8.reference(a, w, xs, ws, b))
+
+
+@needs_tma
[email protected]("cfg", sorted(set(g8._TMA_CONFIG.values())))
+def test_tma_probe_passes_including_the_rounding_ties(cfg):
+ assert g8._probe(0, cfg, tma = True)
+ a, w = g8.tie_operands(torch.device("cuda", 0))
+ xs = torch.ones(a.shape[0], device = "cuda", dtype = torch.bfloat16)
+ ws = torch.ones(w.shape[0], device = "cuda", dtype = torch.bfloat16)
+ assert torch.equal(g8._launch_tma(a, w, xs, ws, None, cfg), g8.reference(a, w, xs, ws, None))
+
+
+@needs_tma
+def test_compiled_swapped_linear_runs_the_tma_kernel_without_breaks():
+ from torch._dynamo.utils import counters
+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_
+
+ if g8.device_config(0) is None or not g8._DEVICE_TMA.get(0):
+ pytest.skip("TMA tile not armed on this device")
+
+ def lin():
+ torch.manual_seed(0)
+ m = torch.nn.Linear(1024, 768, bias = True).cuda().to(torch.bfloat16)
+ quantize_(m, Int8DynamicActivationInt8WeightConfig(version = 2, set_inductor_config = False))
+ return m
+
+ stock, fused = lin(), lin()
+ holder = torch.nn.Sequential(fused)
+ assert g8.install(holder) == 1
+ x = torch.randn(2, 600, 1024, device = "cuda", dtype = torch.bfloat16) # M >= _SHAPE_MIN_M
+ with torch.inference_mode():
+ before = g8.tma_call_count()
+ assert torch.equal(fused(x), stock(x))
+ assert g8.tma_call_count() == before + 1
+ counters.clear()
+ torch._dynamo.reset()
+ with torch._inductor.config.patch(emulate_precision_casts = True):
+ fn = torch.compile(fused, fullgraph = True)
+ out = fn(x)
+ again = fn(x)
+ assert torch.equal(out, again)
+ assert torch.equal(out, torch.compile(stock, fullgraph = True)(x))
+ assert not counters["graph_break"]
+ assert counters["stats"]["unique_graphs"] == 2 # this Linear + the stock one, no recompile
+ assert g8.tma_call_count() >= before + 3
+ g8.uninstall(holder)