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
MoE grouped GEMM: require sm90 on every visible card for TMA and launch on the operands' device (#14358)
Daniel Han9b5e9b90c0b0
diff --git a/tests/test_grouped_gemm_mixed_tma_device.py b/tests/test_grouped_gemm_mixed_tma_device.pynew file mode 100644index 00000000000..eaf9770b621--- /dev/null+++ b/tests/test_grouped_gemm_mixed_tma_device.py@@ -0,0 +1,287 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Mixed H100+A100: TMA must hold on every card; launches and scratch follow the operands' device."""++import ast+import contextlib+import importlib.util+import sys+import types+import typing+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")+pytest.importorskip("triton")+import torch._dynamo # noqa: E402,F401 # import before custom_op is stubbed out below+from torch._subclasses.fake_tensor import FakeTensorMode # noqa: E402++ROOT = Path(__file__).resolve().parents[1]+GG_DIR = ROOT / "unsloth" / "kernels" / "moe" / "grouped_gemm"+PKG = "_unsloth_gg_spoof"+++def _cuda_visible_capabilities():+ """The real unsloth.device_type helper, without importing the GPU-only package."""+ source = (ROOT / "unsloth" / "device_type.py").read_text(encoding = "utf-8")+ node = next(+ n+ for n in ast.parse(source).body+ if isinstance(n, ast.FunctionDef) and n.name == "cuda_visible_capabilities"+ )+ namespace = {"torch": torch}+ exec(compile(ast.Module([node], []), "device_type.py", "exec"), namespace)+ return namespace["cuda_visible_capabilities"]+++class _Kernel:+ def __init__(self, launches, guard_stack):+ self.launches, self.guard_stack, self.best_config = launches, guard_stack, None++ def __getitem__(self, grid):+ def launch(**kwargs):+ self.launches.append(self.guard_stack[-1] if self.guard_stack else None)+ return types.SimpleNamespace(name = "k", n_regs = 0, n_spills = 0, metadata = {})++ return launch+++def _load(+ monkeypatch,+ caps,+ triton_has_tma = True,+):+ """interface.py under a throwaway package, with stubbed unsloth imports and spoofed cards."""+ launches, guard_stack = [], []++ @contextlib.contextmanager+ def torch_gpu_device(device):+ guard_stack.append(device)+ try:+ yield+ finally:+ guard_stack.pop()++ state = {"current": 0}+ monkeypatch.setattr(torch.cuda, "device_count", lambda: len(caps))+ monkeypatch.setattr(+ torch.cuda,+ "get_device_capability",+ lambda device = None: caps[state["current"] if device is None else device],+ )+ monkeypatch.setattr(+ torch.cuda,+ "get_device_properties",+ lambda device = None: types.SimpleNamespace(multi_processor_count = 4),+ )+ # No custom-op registration from the spoofed module.+ monkeypatch.setattr(torch.library, "custom_op", None, raising = False)++ import triton.language as tl++ for name in ("make_tensor_descriptor", "_experimental_make_tensor_descriptor"):+ if triton_has_tma:+ monkeypatch.setattr(tl, name, object(), raising = False)+ else:+ monkeypatch.delattr(tl, name, raising = False)++ stubs = {+ "unsloth": types.SimpleNamespace(DEVICE_TYPE = "cuda"),+ "unsloth.device_type": types.SimpleNamespace(+ cuda_visible_capabilities = _cuda_visible_capabilities()+ ),+ "unsloth.kernels.utils": types.SimpleNamespace(torch_gpu_device = torch_gpu_device),+ PKG: types.ModuleType(PKG),+ f"{PKG}.kernels": types.ModuleType(f"{PKG}.kernels"),+ f"{PKG}.kernels.backward": types.SimpleNamespace(+ **{+ n: _Kernel(launches, guard_stack)+ for n in (+ "_autotuned_grouped_gemm_dW_kernel",+ "_autotuned_grouped_gemm_dX_kernel",+ "_grouped_gemm_dW_kernel",+ "_grouped_gemm_dX_kernel",+ )+ }+ ),+ f"{PKG}.kernels.forward": types.SimpleNamespace(+ _autotuned_grouped_gemm_forward_kernel = _Kernel(launches, guard_stack),+ _grouped_gemm_forward_kernel = _Kernel(launches, guard_stack),+ ),+ f"{PKG}.kernels.tuning": types.SimpleNamespace(+ KernelConfigBackward_dW = object,+ KernelConfigBackward_dX = object,+ KernelConfigForward = object,+ ),+ }+ stubs[PKG].__path__ = [str(GG_DIR)]+ for name, module in stubs.items():+ monkeypatch.setitem(sys.modules, name, module)+ spec = importlib.util.spec_from_file_location(f"{PKG}.interface", GG_DIR / "interface.py")+ module = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, spec.name, module)+ spec.loader.exec_module(module)+ module._is_tracing = lambda *tensors: False # fake tensors stand in for real cuda ones+ return module, launches+++H100, A100, B200, L4 = (9, 0), (8, 0), (10, 0), (8, 9)+++ "caps, expected",+ [+ pytest.param([H100, A100], False, id = "h100+a100"),+ pytest.param([A100, H100], False, id = "a100+h100"),+ pytest.param([H100, L4, H100], False, id = "h100+l4+h100"),+ pytest.param([H100, H100], True, id = "h100x2"),+ pytest.param([H100, B200], True, id = "h100+b200"),+ pytest.param([H100], True, id = "h100"),+ pytest.param([A100], False, id = "a100"),+ pytest.param([A100, A100], False, id = "a100x2"),+ ],+)+def test_tma_needs_every_visible_card(monkeypatch, caps, expected):+ module, _ = _load(monkeypatch, caps)+ assert module.supports_tma() is expected+++def test_tma_still_needs_the_triton_api(monkeypatch):+ module, _ = _load(monkeypatch, [H100, H100], triton_has_tma = False)+ assert module.supports_tma() is False+++def test_an_unreadable_card_disables_tma(monkeypatch):+ module, _ = _load(monkeypatch, [H100, H100])++ def get_device_capability(device = None):+ if device == 1:+ raise RuntimeError("unreadable")+ return H100++ monkeypatch.setattr(torch.cuda, "get_device_capability", get_device_capability)+ assert module._check_tma_support() is False+++def test_launches_are_guarded_on_the_operands_device(monkeypatch):+ module, launches = _load(monkeypatch, [H100, A100])+ allocations = []+ monkeypatch.setattr(module.triton, "set_allocator", allocations.append, raising = False)+ monkeypatch.setattr(module, "_HAS_SET_ALLOCATOR", True)+ E, T, N, K = 2, 8, 16, 16+ with FakeTensorMode():+ dev = torch.device("cuda", 1)+ X = torch.empty(T, K, device = dev, dtype = torch.bfloat16)+ W = torch.empty(E, N, K, device = dev, dtype = torch.bfloat16)+ dY = torch.empty(T, N, device = dev, dtype = torch.bfloat16)+ m_sizes = torch.empty(E, device = dev, dtype = torch.int32)+ common = dict(m_sizes = m_sizes, gather_indices = None, topk = 1, autotune = True)+ module._grouped_gemm_forward_impl(X = X, W = W, **common)+ module._grouped_gemm_dX_impl(dY = dY, W = W, **common)+ module._grouped_gemm_dW_impl(X = X, dY = dY, **common)+ scratch = [alloc(128, 128, 0).device for alloc in allocations]+ assert launches == [dev, dev, dev]+ # set_allocator is process-wide: follow the current device, never capture one launch's card.+ assert scratch and all(d.type == "cuda" and d.index in (None, 0) for d in scratch)+++class _Tuner:+ def __init__(self):+ self.cache = {}+++def test_each_card_autotunes_its_own_copy(monkeypatch):+ module, _ = _load(monkeypatch, [H100, A100])+ monkeypatch.setattr(module.torch.cuda, "device_count", lambda: 2)+ base = _Tuner()+ base.cache["shape"] = "h100-config"+ tuner0 = module._autotuner_for(base, torch.device("cuda", 0))+ tuner1 = module._autotuner_for(base, torch.device("cuda", 1))+ assert tuner0 is not tuner1 and tuner0.cache == {} and tuner1.cache == {}+ assert module._autotuner_for(base, torch.device("cuda", 1)) is tuner1+ assert base.cache == {"shape": "h100-config"}+++def test_single_card_keeps_the_shared_autotuner(monkeypatch):+ module, _ = _load(monkeypatch, [H100])+ monkeypatch.setattr(module.torch.cuda, "device_count", lambda: 1)+ base = _Tuner()+ assert module._autotuner_for(base, torch.device("cuda", 0)) is base+++def test_device_properties_are_read_per_card(monkeypatch):+ import ast+ from dataclasses import dataclass++ source = (GG_DIR / "kernels" / "tuning.py").read_text()+ wanted = {"DeviceProperties", "_DEVICE_PROPERTIES", "get_device_properties"}+ nodes = [+ node+ for node in ast.parse(source).body+ if getattr(node, "name", None) in wanted+ or any(+ getattr(t, "id", None) in wanted+ for t in getattr(node, "targets", []) + [getattr(node, "target", None)]+ )+ ]+ smem = {0: 232448, 1: 166912}+ fake_utils = types.SimpleNamespace(+ get_device_properties = lambda index: {+ "multiprocessor_count": 132,+ "max_num_regs": 65536,+ "max_shared_mem": smem[index],+ "warpSize": 32,+ }+ )+ fake_triton = types.SimpleNamespace(+ runtime = types.SimpleNamespace(+ driver = types.SimpleNamespace(active = types.SimpleNamespace(utils = fake_utils))+ )+ )+ namespace = {+ "torch": torch,+ "triton": fake_triton,+ "dataclass": dataclass,+ "Optional": typing.Optional,+ }+ exec(compile(ast.Module(body = nodes, type_ignores = []), "tuning.py", "exec"), namespace)+ tuning = types.SimpleNamespace(**namespace)+ current = {"device": 0}+ monkeypatch.setattr(torch.cuda, "current_device", lambda: current["device"])+ assert tuning.get_device_properties().SIZE_SMEM == smem[0]+ current["device"] = 1+ assert tuning.get_device_properties().SIZE_SMEM == smem[1]+++def test_autotune_cache_reads_the_per_card_tuners_config():+ # The selected config lives on the per-card copy on multi-GPU hosts; reading the shared kernel misses it.+ import ast++ tree = ast.parse((GG_DIR.parent / "autotune_cache.py").read_text())+ reads = [n for n in ast.walk(tree) if isinstance(n, ast.Attribute) and n.attr == "best_config"]+ assert reads and all(+ isinstance(n.value, ast.Call) and getattr(n.value.func, "id", None) == "_autotuner_for"+ for n in reads+ )+++def test_benchmark_postprocesses_the_per_card_tuner():+ # postprocess_autotune_results reads .cache; on several GPUs only the per-card copy has it.+ import ast++ tree = ast.parse((GG_DIR.parent / "benchmark" / "utils.py").read_text())+ fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_autotuner")+ kernels = [+ n+ for n in ast.walk(fn)+ if isinstance(n, ast.Name) and n.id.startswith("_autotuned_grouped_gemm_")+ ]+ wrapped = {+ id(a)+ for c in ast.walk(fn)+ if isinstance(c, ast.Call) and getattr(c.func, "id", None) == "_autotuner_for"+ for a in c.args[:1]+ }+ assert kernels and all(id(n) in wrapped for n in kernels)diff --git a/unsloth/kernels/moe/autotune_cache.py b/unsloth/kernels/moe/autotune_cache.pyindex 89bc2e314f5..0135c16b8c8 100644--- a/unsloth/kernels/moe/autotune_cache.py+++ b/unsloth/kernels/moe/autotune_cache.py@@ -264,6 +264,7 @@ def _run_moe_autotuning(# Autotune via the interface function with autotune=True (lets triton tune)from .grouped_gemm.interface import (+ _autotuner_for,grouped_gemm_forward,grouped_gemm_dX,grouped_gemm_dW,@@ -290,7 +291,9 @@ def _run_moe_autotuning(permute_y = False,autotune = True,)- triton_config_fwd = _autotuned_grouped_gemm_forward_kernel.best_config+ triton_config_fwd = _autotuner_for(+ _autotuned_grouped_gemm_forward_kernel, hidden_states.device+ ).best_configconfig_fwd = KernelConfigForward(BLOCK_SIZE_M = triton_config_fwd.kwargs["BLOCK_SIZE_M"],@@ -315,7 +318,9 @@ def _run_moe_autotuning(permute_y = False,autotune = True,)- triton_config_bwd_dx = _autotuned_grouped_gemm_dX_kernel.best_config+ triton_config_bwd_dx = _autotuner_for(+ _autotuned_grouped_gemm_dX_kernel, dummy_grad.device+ ).best_config# Safe Backward Configs: 64x64x256config_bwd_dx = KernelConfigBackward_dX(@@ -340,7 +345,9 @@ def _run_moe_autotuning(permute_y = False,autotune = True,)- triton_config_bwd_dw = _autotuned_grouped_gemm_dW_kernel.best_config+ triton_config_bwd_dw = _autotuner_for(+ _autotuned_grouped_gemm_dW_kernel, hidden_states.device+ ).best_configconfig_bwd_dw = KernelConfigBackward_dW(BLOCK_SIZE_M = triton_config_bwd_dw.kwargs["BLOCK_SIZE_M"],@@ -391,7 +398,7 @@ _HEURISTIC_SMEM_STEP_DOWN = {def _device_smem_per_block() -> Optional[int]:- # Per current device: tuning.get_device_properties() caches the first device's limit process-wide.+ # Read per current device: the launching card on a mixed host.try:index = torch.cuda.current_device()except Exception:diff --git a/unsloth/kernels/moe/benchmark/utils.py b/unsloth/kernels/moe/benchmark/utils.pyindex 13514a6873a..c673566bdb9 100644--- a/unsloth/kernels/moe/benchmark/utils.py+++ b/unsloth/kernels/moe/benchmark/utils.py@@ -184,21 +184,27 @@ def save_autotune_results(autotune_cache, mode, ref_time, fused_time, results_didef get_autotuner(mode):+ # The benchmark runs on the current card; on several GPUs that card tunes its own copy.+ from grouped_gemm.interface import _autotuner_for+ device = torch.device("cuda", torch.cuda.current_device())if mode == "forward":from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel- return _autotuned_grouped_gemm_forward_kernel+ return _autotuner_for(_autotuned_grouped_gemm_forward_kernel, device)elif mode == "dW":from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dW_kernel- return _autotuned_grouped_gemm_dW_kernel+ return _autotuner_for(_autotuned_grouped_gemm_dW_kernel, device)elif mode == "dX":from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dX_kernel- return _autotuned_grouped_gemm_dX_kernel+ return _autotuner_for(_autotuned_grouped_gemm_dX_kernel, device)elif mode == "backward":from grouped_gemm.kernels.backward import (_autotuned_grouped_gemm_dW_kernel,_autotuned_grouped_gemm_dX_kernel,)- return _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel+ return (+ _autotuner_for(_autotuned_grouped_gemm_dW_kernel, device),+ _autotuner_for(_autotuned_grouped_gemm_dX_kernel, device),+ )else:raise ValueError(f"Invalid mode: {mode}")diff --git a/unsloth/kernels/moe/grouped_gemm/interface.py b/unsloth/kernels/moe/grouped_gemm/interface.pyindex bcbc885c03b..5e2870f7ca3 100644--- a/unsloth/kernels/moe/grouped_gemm/interface.py+++ b/unsloth/kernels/moe/grouped_gemm/interface.py@@ -1,6 +1,7 @@# SPDX-License-Identifier: GNU Affero General Public License v3.0# Copyright 2023-present the Unsloth team. All rights reserved.+import copyimport functoolsimport inspectimport logging@@ -8,6 +9,8 @@ import warningsfrom typing import Optionalfrom dataclasses import asdictfrom unsloth import DEVICE_TYPE+from unsloth.device_type import cuda_visible_capabilities+from unsloth.kernels.utils import torch_gpu_deviceimport torchimport triton@@ -37,12 +40,16 @@ logger.addHandler(ch)# Precompute TMA support (NVIDIA capability >= 9 plus a triton carrying make_tensor_descriptor) to avoid graph breaks.+# Process-wide, so every visible card must be sm90+ (experts may sit on any); an unreadable card means False.def _check_tma_support():if DEVICE_TYPE in ("xpu", "hip"):return Falseimport triton.language as tl- gpu_supports_tma = torch.cuda.get_device_capability()[0] >= 9+ caps = cuda_visible_capabilities()+ gpu_supports_tma = (+ bool(caps) and len(caps) == torch.cuda.device_count() and min(c[0] for c in caps) >= 9+ )triton_has_tma_api = hasattr(tl, "make_tensor_descriptor") or hasattr(tl, "_experimental_make_tensor_descriptor")@@ -51,6 +58,21 @@ def _check_tma_support():_SUPPORTS_TMA = _check_tma_support()+_DEVICE_AUTOTUNERS = {}+++def _autotuner_for(kernel, device):+ """Triton's autotune key omits the device, so on several GPUs each card tunes its own copy."""+ if torch.cuda.device_count() <= 1 or not hasattr(kernel, "cache"):+ return kernel+ key = (id(kernel), device.index)+ if key not in _DEVICE_AUTOTUNERS:+ tuner = copy.copy(kernel)+ tuner.cache = {}+ _DEVICE_AUTOTUNERS[key] = tuner+ return _DEVICE_AUTOTUNERS[key]++# triton.set_allocator is Triton 3.0+._HAS_SET_ALLOCATOR = hasattr(triton, "set_allocator")@@ -213,7 +235,7 @@ def _grouped_gemm_forward_impl(y = torch.empty((total_tokens, N), device = X.device, dtype = X.dtype)- NUM_SMS = torch.cuda.get_device_properties("cuda").multi_processor_count+ NUM_SMS = torch.cuda.get_device_properties(X.device).multi_processor_countdef grid(META):return (NUM_SMS,)@@ -259,13 +281,19 @@ def _grouped_gemm_forward_impl(})- kernel = _autotuned_grouped_gemm_forward_kernel if autotune else _grouped_gemm_forward_kernel+ kernel = (+ _autotuner_for(_autotuned_grouped_gemm_forward_kernel, X.device)+ if autotune+ else _grouped_gemm_forward_kernel+ )is_fake = _is_tracing(X, W)if not is_fake:- compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](- **kernel_args, enable_fp_fusion = True- )+ # Triton launches on the current device: pin it to the operands' card.+ with torch_gpu_device(X.device):+ compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](+ **kernel_args, enable_fp_fusion = True+ )if autotune:log_kernel_info(compiled_kernel, kernel.best_config)else:@@ -358,7 +386,7 @@ def _grouped_gemm_dX_impl(output_shape = (total_tokens, K)dX = torch.zeros(output_shape, device = dY.device, dtype = dY.dtype)- NUM_SMS = torch.cuda.get_device_properties("cuda").multi_processor_count+ NUM_SMS = torch.cuda.get_device_properties(dY.device).multi_processor_countdef grid(META):return (NUM_SMS,)@@ -401,13 +429,18 @@ def _grouped_gemm_dX_impl("USE_TMA_STORE": use_tma_store,})- kernel = _autotuned_grouped_gemm_dX_kernel if autotune else _grouped_gemm_dX_kernel+ kernel = (+ _autotuner_for(_autotuned_grouped_gemm_dX_kernel, dY.device)+ if autotune+ else _grouped_gemm_dX_kernel+ )is_fake = _is_tracing(dY, W)if not is_fake:- compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](- **kernel_args, enable_fp_fusion = True- )+ with torch_gpu_device(dY.device):+ compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](+ **kernel_args, enable_fp_fusion = True+ )if autotune:log_kernel_info(compiled_kernel, kernel.best_config)@@ -445,7 +478,7 @@ def _grouped_gemm_dW_impl("""assert not fuse_mul_pre, "fuse_mul_pre not supported"assert not fuse_mul_post, "fuse_mul_post not supported"- NUM_SMS = torch.cuda.get_device_properties("cuda").multi_processor_count if not debug else 1+ NUM_SMS = torch.cuda.get_device_properties(X.device).multi_processor_count if not debug else 1X = X.view(-1, X.shape[-1]).contiguous()dY = dY.contiguous()m_sizes = m_sizes.contiguous()@@ -548,13 +581,18 @@ def _grouped_gemm_dW_impl(})- kernel = _autotuned_grouped_gemm_dW_kernel if autotune else _grouped_gemm_dW_kernel+ kernel = (+ _autotuner_for(_autotuned_grouped_gemm_dW_kernel, X.device)+ if autotune+ else _grouped_gemm_dW_kernel+ )is_fake = _is_tracing(X, dY)if not is_fake:- compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](- **kernel_args, enable_fp_fusion = True- )+ with torch_gpu_device(X.device):+ compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](+ **kernel_args, enable_fp_fusion = True+ )if autotune:log_kernel_info(compiled_kernel, kernel.best_config)diff --git a/unsloth/kernels/moe/grouped_gemm/kernels/tuning.py b/unsloth/kernels/moe/grouped_gemm/kernels/tuning.pyindex 35d6ff7504b..027e6185230 100644--- a/unsloth/kernels/moe/grouped_gemm/kernels/tuning.py+++ b/unsloth/kernels/moe/grouped_gemm/kernels/tuning.py@@ -31,21 +31,20 @@ class DeviceProperties:WARP_SIZE: int-_DEVICE_PROPERTIES: Optional[DeviceProperties] = None+# Per device: config pruning runs on the launching card, which differs on a mixed host.+_DEVICE_PROPERTIES: dict = {}def get_device_properties():- global _DEVICE_PROPERTIES- if _DEVICE_PROPERTIES is None:- properties = triton.runtime.driver.active.utils.get_device_properties(- torch.cuda.current_device()- )+ device = torch.cuda.current_device()+ if device not in _DEVICE_PROPERTIES:+ properties = triton.runtime.driver.active.utils.get_device_properties(device)NUM_SM = properties["multiprocessor_count"]NUM_REGS = properties["max_num_regs"]SIZE_SMEM = properties["max_shared_mem"]WARP_SIZE = properties["warpSize"]- _DEVICE_PROPERTIES = DeviceProperties(NUM_SM, NUM_REGS, SIZE_SMEM, WARP_SIZE)- return _DEVICE_PROPERTIES+ _DEVICE_PROPERTIES[device] = DeviceProperties(NUM_SM, NUM_REGS, SIZE_SMEM, WARP_SIZE)+ return _DEVICE_PROPERTIES[device]@dataclass