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.

Kernel follow-ups: NVFP4 shape-aware fused gate, MoE fallback tiles, test fixes across torch 2.10 - 2.14 (#14122)

Daniel Han4487b0ac8590
diff --git a/tests/test_cross_entropy_eviction_hints.py b/tests/test_cross_entropy_eviction_hints.py
index 5b6f29fa13e..cbf63bc0c60 100644
--- a/tests/test_cross_entropy_eviction_hints.py
+++ b/tests/test_cross_entropy_eviction_hints.py
@@ -50,11 +50,17 @@ def _compile(evict, cc):
fn = ce_mod._chunked_cross_entropy_forward.fn
signature = {name: _SIGNATURE.get(name, "constexpr") for name in fn.arg_names}
constexprs = dict(_CHUNKED, EVICT = evict, **_COMMON)
- return triton.compile(
- ASTSource(fn, signature = signature, constexprs = constexprs),
- target = GPUTarget("cuda", cc, 32),
- options = {"num_warps": 32},
- )
+ try:
+ return triton.compile(
+ ASTSource(fn, signature = signature, constexprs = constexprs),
+ target = GPUTarget("cuda", cc, 32),
+ options = {"num_warps": 32},
+ )
+ except Exception as error:
+ # CUDA 13 ptxas (torch's, picked once Inductor sets TRITON_PTXAS_PATH) has no sm_52 to sm_72.
+ if "is not defined for option 'gpu-name'" in str(error):
+ pytest.skip(f"the active ptxas cannot target sm_{cc}")
+ raise
@pytest.mark.parametrize("capability", [(5, 2), (6, 1)])
diff --git a/tests/test_layernorm_weight_grad.py b/tests/test_layernorm_weight_grad.py
index 0dc7e5316cb..bc101b3e0ab 100644
--- a/tests/test_layernorm_weight_grad.py
+++ b/tests/test_layernorm_weight_grad.py
@@ -114,13 +114,17 @@ def test_layernorm_only_weight_trainable():
_close(dw, _exact(layer, inputs, grad)[2], torch.bfloat16)
-def test_layernorm_compiled_matches_eager_bytes():
[email protected]("dtype", [torch.float16, torch.bfloat16])
+def test_layernorm_compiled_matches_eager_bytes(dtype):
from unsloth.kernels.layernorm import fast_layernorm
+ # Inductor raises SkipFrame for bf16 graphs without native bf16 (T4, sm_75), so fullgraph fails.
+ if dtype == torch.bfloat16 and not torch.cuda.is_bf16_supported(including_emulation = False):
+ pytest.skip("Inductor does not compile bf16 without native bf16 support")
torch.manual_seed(6)
- inputs = torch.randn(3000, 1000, device = "cuda", dtype = torch.bfloat16)
- grad = torch.randn(3000, 1000, device = "cuda", dtype = torch.bfloat16)
- layer = _layer(1000, torch.bfloat16)
+ inputs = torch.randn(3000, 1000, device = "cuda", dtype = dtype)
+ grad = torch.randn(3000, 1000, device = "cuda", dtype = dtype)
+ layer = _layer(1000, dtype)
eager = _fast(layer, inputs, grad)
layer.zero_grad(set_to_none = True)
compiled = torch.compile(lambda x: fast_layernorm(layer, x), fullgraph = True)
diff --git a/tests/test_moe_fallback_tile_dims.py b/tests/test_moe_fallback_tile_dims.py
new file mode 100644
index 00000000000..7e817b20b38
--- /dev/null
+++ b/tests/test_moe_fallback_tile_dims.py
@@ -0,0 +1,220 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The heuristic (UNSLOTH_MOE_DISABLE_AUTOTUNE=1) and default (autotune failed) MoE
+kernel configs used fixed tiles. The grouped GEMM kernels static_assert that BLOCK_SIZE_K
+divides K (forward, dX) and BLOCK_SIZE_N divides N (dX), so e.g. intermediate size 1408
+(DeepSeek-V2-Lite, Qwen1.5-MoE-A2.7B) crashed in the heuristic backward (BLOCK_SIZE_K 256).
+The tiles now shrink per GEMM to a power of two dividing N / K, and shapes that already
+divided keep exactly the old configs."""
+
+import importlib
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("triton")
+pytest.importorskip("pandas")
+
+MOE_DIR = ROOT / "unsloth" / "kernels" / "moe"
+
+# Fixed tiles before the fix: (BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K, num_warps, num_stages)
+OLD_HEURISTIC = ((64, 128, 128, 8, 3), (64, 64, 256, 8, 4), (64, 64, 256, 8, 4))
+OLD_DEFAULT = ((128, 128, 64, 8, 3),) * 3
+
+# (hidden_size, moe_intermediate_size)
+SHAPES = [(2048, 1408), (2048, 768), (4096, 1536), (2880, 2880), (4096, 14336), (1024, 352)]
+# Qwen3-30B-A3B, Qwen3-235B-A22B, Mixtral-8x7B, OLMoE-1B-7B: their configs must stay byte-identical.
+UNCHANGED_SHAPES = [(2048, 768), (4096, 1536), (4096, 14336), (2048, 1024)]
+
+
+def ac(monkeypatch):
+ # Import autotune_cache without running unsloth/__init__.py (needs a GPU).
+ for name, path in (
+ ("unsloth", ROOT / "unsloth"),
+ ("unsloth.kernels", ROOT / "unsloth" / "kernels"),
+ ("unsloth.kernels.moe", MOE_DIR),
+ ):
+ pkg = types.ModuleType(name)
+ pkg.__path__ = [str(path)]
+ monkeypatch.setitem(sys.modules, name, pkg)
+ for name in list(sys.modules):
+ if name.startswith("unsloth.kernels.moe."):
+ monkeypatch.delitem(sys.modules, name)
+ module = importlib.import_module("unsloth.kernels.moe.autotune_cache")
+ yield module
+ for name in list(sys.modules):
+ if name.startswith("unsloth.kernels.moe."):
+ sys.modules.pop(name, None)
+
+
+def _gemms(hidden, inter):
+ # As unsloth_zoo forward_triton_grouped_gemm calls it. GEMM1: K = H, N = 2I. GEMM2: K = I, N = H.
+ return [
+ (dict(hidden_dim = hidden, intermediate_dim = inter), (2 * inter, hidden)),
+ (
+ dict(
+ hidden_dim = inter,
+ intermediate_dim = hidden // 2 if hidden % 2 == 0 else hidden,
+ ),
+ (hidden, inter),
+ ),
+ ]
+
+
+def _tiles(configs):
+ return tuple(
+ (c.BLOCK_SIZE_M, c.BLOCK_SIZE_N, c.BLOCK_SIZE_K, c.num_warps, c.num_stages) for c in configs
+ )
+
+
+def _divides(old, n, k):
+ return all(n % t[1] == 0 and k % t[2] == 0 for t in old)
+
+
[email protected]("hidden,inter", SHAPES + [(2048, 1024)])
[email protected]("which", ["heuristic", "default"])
+def test_fallback_tiles_divide_each_gemm(ac, hidden, inter, which):
+ fn = ac._get_heuristic_configs if which == "heuristic" else ac._get_default_configs
+ old = OLD_HEURISTIC if which == "heuristic" else OLD_DEFAULT
+ for kwargs, (n, k) in _gemms(hidden, inter):
+ tiles = _tiles(fn(n_dim = 2 * kwargs["intermediate_dim"], k_dim = kwargs["hidden_dim"]))
+ for tile, old_tile in zip(tiles, old):
+ m, bn, bk, warps, stages = tile
+ assert n % bn == 0 and k % bk == 0, (which, hidden, inter, n, k, tile)
+ assert bn >= 16 and bk >= 16
+ assert bn <= old_tile[1] and bk <= old_tile[2]
+ assert (m, warps, stages) == (old_tile[0], old_tile[3], old_tile[4])
+ if _divides(old, n, k):
+ assert tiles == old, (which, hidden, inter, n, k)
+
+
[email protected]("hidden,inter", UNCHANGED_SHAPES)
[email protected]("which", ["heuristic", "default"])
+def test_working_shapes_keep_exact_configs(ac, hidden, inter, which):
+ fn = ac._get_heuristic_configs if which == "heuristic" else ac._get_default_configs
+ for kwargs, _ in _gemms(hidden, inter):
+ new = fn(n_dim = 2 * kwargs["intermediate_dim"], k_dim = kwargs["hidden_dim"])
+ assert [c.__dict__ for c in new] == [c.__dict__ for c in fn()]
+
+
+def test_no_dims_keeps_old_configs(ac):
+ assert _tiles(ac._get_heuristic_configs()) == OLD_HEURISTIC
+ assert _tiles(ac._get_default_configs()) == OLD_DEFAULT
+
+
+def test_1408_backward_k_shrinks(ac):
+ # GEMM2 of DeepSeek-V2-Lite / Qwen1.5-MoE: K = 1408 = 128 * 11.
+ _, dx, dw = ac._get_heuristic_configs(n_dim = 2048, k_dim = 1408)
+ assert (dx.BLOCK_SIZE_K, dw.BLOCK_SIZE_K) == (128, 128)
+ assert (dx.BLOCK_SIZE_N, dw.BLOCK_SIZE_N) == (64, 64)
+
+
+def test_fit_block_size_edges(ac):
+ fit = ac._fit_block_size
+ assert fit(256, 1408) == 128
+ assert fit(128, 2880) == 64
+ assert fit(256, 352) == 32
+ assert fit(64, None) == 64
+ # No power of two >= 16 divides: keep today's tile (kernel asserts as before).
+ assert fit(128, 2 * 2881) == 128
+ assert fit(64, 24) == 64
+
+
[email protected]("hidden,inter", SHAPES)
+def test_get_or_autotune_wires_dims(ac, monkeypatch, hidden, inter):
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a, **k: (7, 5))
+ monkeypatch.setattr(ac, "load_cached_config", lambda key: None)
+ monkeypatch.setattr(ac, "save_cached_config", lambda *a, **k: None)
+
+ def boom(*a, **k):
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ monkeypatch.setattr(ac, "_run_moe_autotuning", boom)
+ for env in ("1", "0"):
+ monkeypatch.setenv("UNSLOTH_MOE_DISABLE_AUTOTUNE", env)
+ ac.clear_cache()
+ for kwargs, (n, k) in _gemms(hidden, inter):
+ configs = ac.get_or_autotune_moe_kernels(
+ num_experts = 8, top_k = 2, dtype = torch.bfloat16, **kwargs
+ )
+ for c in configs:
+ assert n % c.BLOCK_SIZE_N == 0 and k % c.BLOCK_SIZE_K == 0, (env, n, k, c)
+
+
+def _device(ac, monkeypatch, capability, smem):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a, **k: capability)
+ monkeypatch.setattr(ac, "_device_smem_per_block", lambda: smem)
+
+
[email protected]("capability", [(8, 6), (8, 9), (12, 0)])
+def test_heuristic_dx_steps_down_on_small_smem(ac, monkeypatch, capability):
+ _device(ac, monkeypatch, capability, 101376)
+ fwd, dx, dw = ac._get_heuristic_configs(n_dim = 1536, k_dim = 2048)
+ assert _tiles((fwd, dx, dw)) == (OLD_HEURISTIC[0], (64, 64, 256, 8, 3), OLD_HEURISTIC[2])
+
+
+ "capability,smem",
+ [((7, 5), 65536), ((8, 0), 166912), ((9, 0), 232448), ((10, 0), 232448), ((8, 7), 166912)],
+)
[email protected]("hidden,inter", UNCHANGED_SHAPES)
+def test_heuristic_unchanged_with_enough_smem(ac, monkeypatch, capability, smem, hidden, inter):
+ for kwargs, _ in _gemms(hidden, inter):
+ dims = dict(n_dim = 2 * kwargs["intermediate_dim"], k_dim = kwargs["hidden_dim"])
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ old = [c.__dict__ for c in ac._get_heuristic_configs(**dims)]
+ _device(ac, monkeypatch, capability, smem)
+ assert [c.__dict__ for c in ac._get_heuristic_configs(**dims)] == old
+
+
+def test_heuristic_shrunk_dx_is_not_stepped(ac, monkeypatch):
+ # 1408 GEMM2: dX already 64x64x128 x 4 stages after the dims fit (73,728 B), not in the table.
+ _device(ac, monkeypatch, (8, 9), 101376)
+ _, dx, _ = ac._get_heuristic_configs(n_dim = 2048, k_dim = 1408)
+ assert (dx.BLOCK_SIZE_K, dx.num_stages) == (128, 4)
+
+
[email protected]("smem", [None, 65536])
+def test_heuristic_unknown_or_tiny_smem_keeps_config(ac, monkeypatch, smem):
+ # Unknown limit, or one the step-down does not fit either (81,920 B): keep today's config.
+ _device(ac, monkeypatch, (8, 9), smem)
+ assert _tiles(ac._get_heuristic_configs(n_dim = 1536, k_dim = 2048)) == OLD_HEURISTIC
+
+
+def test_default_configs_not_stepped(ac, monkeypatch):
+ _device(ac, monkeypatch, (8, 9), 101376)
+ assert _tiles(ac._get_default_configs(n_dim = 1536, k_dim = 2048)) == OLD_DEFAULT
+
+
+def test_get_or_autotune_heuristic_steps_down(ac, monkeypatch):
+ _device(ac, monkeypatch, (8, 9), 101376)
+ monkeypatch.setenv("UNSLOTH_MOE_DISABLE_AUTOTUNE", "1")
+ _, dx, _ = ac.get_or_autotune_moe_kernels(
+ num_experts = 128, hidden_dim = 2048, intermediate_dim = 768, top_k = 8, dtype = torch.bfloat16
+ )
+ assert dx.num_stages == 3
+
+
+def test_smem_limit_follows_the_current_device(ac, monkeypatch):
+ # Mixed GPUs in one process: the limit must come from the current device, not the first one seen.
+ import types
+
+ limits = {0: 166912, 1: 101376}
+ current = {"index": 0}
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: current["index"])
+ monkeypatch.setattr(
+ torch.cuda,
+ "get_device_properties",
+ lambda index: types.SimpleNamespace(shared_memory_per_block_optin = limits[index]),
+ )
+ assert ac._device_smem_per_block() == 166912
+ current["index"] = 1
+ assert ac._device_smem_per_block() == 101376
diff --git a/tests/test_norm_fast_launch.py b/tests/test_norm_fast_launch.py
index 1abfb3d2447..642e93f47d7 100644
--- a/tests/test_norm_fast_launch.py
+++ b/tests/test_norm_fast_launch.py
@@ -124,6 +124,11 @@ def test_compiled_calls_never_use_fast_launch(monkeypatch, kind, width, gemma):
fn = lambda x: rms_layernorm.fast_rms_layernorm(norm, x, gemma = gemma)
else:
fn = lambda x: layernorm.fast_layernorm(norm, x)
+ # The narrow-row self-check runs real eager kernels once per shape; on torch <= 2.12 Dynamo's
+ # fake-tensor pass reaches it with is_compiling() False. Run it first: only the graph is measured.
+ with torch.no_grad():
+ fn(torch.randn(4, 64, width, device = "cuda"))
+ calls.clear()
torch._dynamo.reset()
x = torch.randn(4, 64, width, device = "cuda", requires_grad = True)
torch.compile(fn, fullgraph = True)(x).sum().backward()
diff --git a/tests/test_nvfp4_fused_gate_shape.py b/tests/test_nvfp4_fused_gate_shape.py
new file mode 100644
index 00000000000..42811268562
--- /dev/null
+++ b/tests/test_nvfp4_fused_gate_shape.py
@@ -0,0 +1,129 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# CPU only: the per-GPU NVFP4 fused row gate scales with the weight size (capability monkeypatched).
+import os
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+
+def N(monkeypatch):
+ os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")
+ from unsloth.kernels import nvfp4
+
+ monkeypatch.setattr(nvfp4, "_IS_HIP", False)
+ return nvfp4
+
+
+def _weight(n, k):
+ packed = torch.zeros((n, k // 2), dtype = torch.uint8)
+ scale = torch.ones((n, k // 16), dtype = torch.float32)
+ return packed, scale, torch.tensor([1.0])
+
+
+def _rows(rows, width):
+ # A CPU tensor dressed as CUDA: the gate reads only shape, dtype, device and is_cuda.
+ t = torch.zeros((rows, width), dtype = torch.bfloat16)
+ return types.SimpleNamespace(
+ is_cuda = True,
+ get_device = lambda: 0,
+ numel = t.numel,
+ dtype = t.dtype,
+ shape = t.shape,
+ device = t.device,
+ )
+
+
+def _decide(
+ N,
+ monkeypatch,
+ cap,
+ rows,
+ n,
+ k,
+ dx = False,
+ mode = "auto",
+ max_rows = None,
+):
+ monkeypatch.setattr(N, "_fused_env", lambda: (mode, max_rows))
+ monkeypatch.setattr(N, "_device_capability", lambda index: cap)
+ packed, scale, gs = _weight(n, k)
+ inner = n if dx else k
+ return N._fused_ok(_rows(rows, inner), packed, scale, gs, inner, dx = dx)
+
+
+# (capability, direction, N, K, rows fused up to): the measured crossovers of the bf16 sweep.
+CASES = [
+ ((8, 0), "fwd", 4096, 4096, 42), # was 64 rows: slower than dense at M=64
+ ((8, 0), "fwd", 3072, 768, 64), # narrow reduction: c // K
+ ((8, 0), "fwd", 4096, 14336, 64),
+ ((8, 0), "dx", 2048, 2048, 16),
+ ((8, 0), "dx", 8192, 8192, 64),
+ ((8, 9), "fwd", 4096, 4096, 85),
+ ((8, 9), "dx", 4096, 4096, 170), # dX turns over later than forward
+ ((8, 9), "dx", 3072, 768, 32),
+ ((8, 9), "fwd", 4096, 14336, 256),
+ ((12, 0), "fwd", 4096, 4096, 42), # was 128 rows: +12% slower than dense at M=64
+ ((12, 0), "dx", 4096, 4096, 73), # fused dX still wins at M=64 here
+ ((12, 0), "dx", 1024, 4096, 32), # wide dX output: K // c
+ ((12, 0), "dx", 3072, 768, 16),
+ ((12, 0), "fwd", 3072, 768, 85),
+ ((12, 0), "fwd", 8192, 8192, 128),
+ ((12, 0), "dx", 8192, 8192, 256),
+ ((12, 0), "dx", 2880, 2880, 16), # N, K not multiples of 128: the floor
+ ((8, 9), "fwd", 2880, 2880, 32),
+]
+
+
[email protected]("cap, direction, n, k, limit", CASES)
+def test_row_limit_scales_with_weight(N, monkeypatch, cap, direction, n, k, limit):
+ dx = direction == "dx"
+ assert N._fused_max_rows(cap, n, k, dx) == limit
+ assert _decide(N, monkeypatch, cap, limit, n, k, dx)
+ assert not _decide(N, monkeypatch, cap, limit + 1, n, k, dx)
+
+
[email protected]("cap", [(7, 5), (8, 6), (9, 0), (10, 0), (12, 1)])
+def test_unmeasured_gpus_stay_dense(N, monkeypatch, cap):
+ assert N._fused_max_rows(cap, 8192, 8192) == 0
+ assert not _decide(N, monkeypatch, cap, 1, 8192, 8192)
+ assert not _decide(N, monkeypatch, cap, 1, 8192, 8192, dx = True)
+
+
+def test_env_overrides(N, monkeypatch):
+ # UNSLOTH_NVFP4_FUSED=1 fuses past the gate (even on unmeasured GPUs), 0 never fuses, _MAX_ROWS is a flat limit.
+ assert _decide(N, monkeypatch, (9, 0), 4096, 4096, 4096, mode = "1")
+ assert _decide(N, monkeypatch, (12, 0), 4096, 4096, 4096, dx = True, mode = "1")
+ assert not _decide(N, monkeypatch, (12, 0), 1, 8192, 8192, mode = "0")
+ assert _decide(N, monkeypatch, (8, 0), 200, 3072, 768, max_rows = 200)
+ assert not _decide(N, monkeypatch, (8, 0), 201, 3072, 768, max_rows = 200)
+ assert _decide(N, monkeypatch, (9, 0), 200, 3072, 768, dx = True, max_rows = 200)
+
+
+def test_env_parsing(N, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_NVFP4_FUSED_MAX_ROWS", "96")
+ monkeypatch.delenv("UNSLOTH_NVFP4_FUSED", raising = False)
+ assert N._read_fused_env() == ("auto", 96)
+ monkeypatch.setenv("UNSLOTH_NVFP4_FUSED", " Off ")
+ assert N._read_fused_env()[0] in N._FUSED_OFF
+
+
+def test_gate_is_monotone_in_weight_size(N):
+ # At a fixed K the row limit never shrinks as N grows, and tops out at max_rows.
+ for cap, gates in N._FUSED_ROW_GATE.items():
+ for dx in (False, True):
+ for k in (768, 4096, 16384):
+ limits = [N._fused_max_rows(cap, 128 * i, k, dx) for i in range(1, 4097)]
+ assert limits == sorted(limits) and limits[0] > 0 and limits[-1] == gates[dx][3]
+
+
+def test_degenerate_weights_stay_dense(N, monkeypatch):
+ assert (
+ N._fused_max_rows((12, 0), 0, 4096) == 0 and N._fused_max_rows((12, 0), 4096, 0, True) == 0
+ )
+ monkeypatch.setattr(N, "_fused_env", lambda: ("auto", None))
+ monkeypatch.setattr(N, "_device_capability", lambda index: (12, 0))
+ flat = torch.zeros(4096 * 2048, dtype = torch.uint8)
+ assert not N._fused_ok(_rows(1, 4096), flat, torch.ones(1, 1), torch.tensor([1.0]), 4096)
diff --git a/unsloth/kernels/moe/autotune_cache.py b/unsloth/kernels/moe/autotune_cache.py
index c608676cb23..89bc2e314f5 100644
--- a/unsloth/kernels/moe/autotune_cache.py
+++ b/unsloth/kernels/moe/autotune_cache.py
@@ -159,7 +159,7 @@ def get_or_autotune_moe_kernels(
logger.info(
f"UNSLOTH_MOE_DISABLE_AUTOTUNE=1: Using Heuristic (Safe) MoE kernel configs for SM{device_capability[0]}{device_capability[1]}"
)
- return _get_heuristic_configs()
+ return _get_heuristic_configs(n_dim = 2 * intermediate_dim, k_dim = hidden_dim)
if not force_autotune and cache_key in _kernel_config_cache:
logger.info(f"Using in-memory cached MoE kernel configs: {cache_key}")
return _kernel_config_cache[cache_key]
@@ -224,7 +224,7 @@ def get_or_autotune_moe_kernels(
"Unsloth: Your Triton version might be incompatible with TMA features. Falling back to default configs."
)
logger.info("Falling back to default kernel configurations")
- return _get_default_configs()
+ return _get_default_configs(n_dim = 2 * intermediate_dim, k_dim = hidden_dim)
def _run_moe_autotuning(
@@ -355,10 +355,83 @@ def _run_moe_autotuning(
return config_fwd, config_bwd_dx, config_bwd_dw
- return config_fwd, config_bwd_dx, config_bwd_dw
+
+_MIN_FALLBACK_BLOCK_SIZE = 16
+
+
+def _fit_block_size(block_size: int, dim: Optional[int]) -> int:
+ # Largest power of two <= block_size and >= 16 dividing dim; else unchanged (the kernel asserts still fire).
+ if dim is None or dim <= 0 or dim % block_size == 0:
+ return block_size
+ candidate = 1 << (block_size.bit_length() - 1)
+ while candidate >= _MIN_FALLBACK_BLOCK_SIZE:
+ if dim % candidate == 0:
+ return candidate
+ candidate >>= 1
+ return block_size
+
+
+def _fit_configs_to_dims(
+ configs: Tuple[Any, Any, Any], n_dim: Optional[int], k_dim: Optional[int]
+) -> Tuple[Any, Any, Any]:
+ # The kernels static_assert K % BLOCK_SIZE_K == 0 and N % BLOCK_SIZE_N == 0; W is [E, N, K] for all three.
+ # BLOCK_SIZE_M tiles the masked per-expert token count, so it stays.
+ for config in configs:
+ config.BLOCK_SIZE_N = _fit_block_size(config.BLOCK_SIZE_N, n_dim)
+ config.BLOCK_SIZE_K = _fit_block_size(config.BLOCK_SIZE_K, k_dim)
+ return configs
-def _get_heuristic_configs() -> Tuple[Any, Any, Any]:
+# Triton metadata.shared (16-bit) of the 4-stage 64x64x256 dX: 122,880 B, over the 101,376 B of L4 / RTX PRO 6000;
+# 3 stages need 81,920 B. sm_75 needs 65,536 B (no cp.async multi-buffering), so it is excluded.
+# kind -> {(BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K, num_stages): (bytes, fitting num_stages, its bytes)}
+_HEURISTIC_SMEM_STEP_DOWN = {
+ "dX": {(64, 64, 256, 4): (122880, 3, 81920)},
+}
+
+
+def _device_smem_per_block() -> Optional[int]:
+ # Per current device: tuning.get_device_properties() caches the first device's limit process-wide.
+ try:
+ index = torch.cuda.current_device()
+ except Exception:
+ return None
+ try:
+ return int(torch.cuda.get_device_properties(index).shared_memory_per_block_optin)
+ except Exception:
+ try:
+ return int(
+ triton.runtime.driver.active.utils.get_device_properties(index)["max_shared_mem"]
+ )
+ except Exception:
+ return None
+
+
+def _fit_heuristic_configs_to_smem(configs: Tuple[Any, Any, Any]) -> Tuple[Any, Any, Any]:
+ try:
+ if not torch.cuda.is_available() or getattr(torch.version, "hip", None):
+ return configs
+ if torch.cuda.get_device_capability()[0] < 8:
+ return configs
+ except Exception:
+ return configs
+ smem = _device_smem_per_block()
+ if smem is None:
+ return configs
+ for kind, config in zip(("fwd", "dX", "dW"), configs):
+ key = (config.BLOCK_SIZE_M, config.BLOCK_SIZE_N, config.BLOCK_SIZE_K, config.num_stages)
+ entry = _HEURISTIC_SMEM_STEP_DOWN.get(kind, {}).get(key)
+ if entry is not None and entry[2] <= smem < entry[0]:
+ config.num_stages = entry[1]
+ logger.info(
+ f"MoE heuristic {kind} config: num_stages {key[3]} -> {entry[1]} to fit {smem} B shared memory"
+ )
+ return configs
+
+
+def _get_heuristic_configs(
+ n_dim: Optional[int] = None, k_dim: Optional[int] = None
+) -> Tuple[Any, Any, Any]:
"""
Get 'Safe Heuristic' kernel configurations.
These are verified to be safe on A100 (SM80) and provide ~9x speedup on H100/B200.
@@ -409,10 +482,13 @@ def _get_heuristic_configs() -> Tuple[Any, Any, Any]:
use_tma_store = False,
)
- return config_fwd, config_bwd_dx, config_bwd_dw
+ configs = _fit_configs_to_dims((config_fwd, config_bwd_dx, config_bwd_dw), n_dim, k_dim)
+ return _fit_heuristic_configs_to_smem(configs)
-def _get_default_configs() -> Tuple[Any, Any, Any]:
+def _get_default_configs(
+ n_dim: Optional[int] = None, k_dim: Optional[int] = None
+) -> Tuple[Any, Any, Any]:
"""Get default kernel configurations as fallback."""
from .grouped_gemm.kernels.tuning import (
KernelConfigForward,
@@ -455,7 +531,7 @@ def _get_default_configs() -> Tuple[Any, Any, Any]:
use_tma_store = False,
)
- return config_fwd, config_bwd_dx, config_bwd_dw
+ return _fit_configs_to_dims((config_fwd, config_bwd_dx, config_bwd_dw), n_dim, k_dim)
def clear_cache() -> None:
diff --git a/unsloth/kernels/nvfp4.py b/unsloth/kernels/nvfp4.py
index 7272e0354b4..7fdfc78b249 100644
--- a/unsloth/kernels/nvfp4.py
+++ b/unsloth/kernels/nvfp4.py
@@ -408,7 +408,7 @@ _FUSED_CALLS = {"fwd": 0, "bwd": 0}
def _read_fused_env():
- # UNSLOTH_NVFP4_FUSED: 0 dense, 1 fused, unset = per-GPU row gate (UNSLOTH_NVFP4_FUSED_MAX_ROWS overrides it).
+ # UNSLOTH_NVFP4_FUSED: 0 dense, 1 fused, unset = per-GPU row gate (UNSLOTH_NVFP4_FUSED_MAX_ROWS: a flat row limit).
rows = os.environ.get("UNSLOTH_NVFP4_FUSED_MAX_ROWS")
return os.environ.get("UNSLOTH_NVFP4_FUSED", "auto").strip().lower(), int(
rows
@@ -436,15 +436,45 @@ _FUSED_FORCE = ("1", "true", "on", "yes", "force")
_IS_HIP = torch.version.hip is not None
-def _fused_ok(A, packed, scale, global_scale, inner):
+def _fused_max_rows(
+ capability,
+ n,
+ k,
+ dx = False,
+):
+ # Rows of X (forward) or of the output gradient (dX) up to which fused beats dense; 0 = never (unmeasured GPU).
+ gate = _FUSED_ROW_GATE.get(capability)
+ if gate is None or not n or not k:
+ return 0
+ div, c, floor, max_rows = gate[dx]
+ if n % 128 or k % 128: # masked edge tiles: fused only up to the floor
+ return floor
+ # A narrow reduction (forward, small K) or a wide output (dX, large K) also keeps fused ahead.
+ k_rows = (k // c if dx else c // k) if c else 0
+ return max(floor, min(max_rows, max(n * k // div, k_rows)))
+
+
+def _fused_ok(
+ A,
+ packed,
+ scale,
+ global_scale,
+ inner,
+ dx = False,
+):
# Anything unusual keeps the dense path (and its errors).
mode, rows = _fused_env()
if mode in _FUSED_OFF or _IS_HIP or not A.is_cuda:
return False
index = A.get_device()
if mode not in _FUSED_FORCE:
- limit = rows if rows is not None else _FUSED_MAX_ROWS.get(_device_capability(index), 0)
- if A.numel() > limit * inner: # unmeasured GPUs (limit 0) leave here
+ if rows is None:
+ if packed.dim() != 2:
+ return False
+ rows = _fused_max_rows(
+ _device_capability(index), packed.shape[0], packed.shape[1] * 2, dx
+ )
+ if A.numel() > rows * inner: # unmeasured GPUs (limit 0) leave here
return False
if A.dtype not in (torch.float16, torch.bfloat16) or A.numel() == 0 or A.shape[-1] != inner:
return False
@@ -467,8 +497,15 @@ def _fused_ok(A, packed, scale, global_scale, inner):
)
-# Max rows where fused beats dense (measured at N, K multiples of 64); unmeasured GPUs stay dense.
-_FUSED_MAX_ROWS = {(8, 0): 64, (8, 9): 256, (12, 0): 128}
+# Fused beats dense while the weight (N * K elements) gives the GPU enough tiles:
+# rows <= clamp(max(N * K // div, k_rows), floor, max_rows), k_rows = c // K forward, K // c for dX (c = 0: none).
+# capability: ((div, c, floor, max_rows) forward, (...) dX). Fitted to a bf16 sweep (rows 1 to 256, N * K 2.4M to 67M)
+# on A100, L4 and RTX PRO 6000; unmeasured GPUs stay dense.
+_FUSED_ROW_GATE = {
+ (8, 0): ((3 << 17, 3 << 14, 32, 64), (3 << 17, 0, 16, 64)),
+ (8, 9): ((3 << 16, 3 << 14, 32, 256), (3 << 15, 0, 32, 256)),
+ (12, 0): ((3 << 17, 1 << 16, 32, 128), (7 << 15, 128, 16, 256)),
+}
def _scale_args(scale):
@@ -640,7 +677,7 @@ def _nvfp4_matmul_bwd(
) -> torch.Tensor:
# create_graph: the raw launch has no autograd history, so differentiate through the dense matmul.
if not (grad.requires_grad and torch.is_grad_enabled()) and _fused_ok(
- grad, packed, scale, global_scale, packed.shape[0]
+ grad, packed, scale, global_scale, packed.shape[0], dx = True
):
return _nvfp4_matmul_dx_fused(grad, packed, scale, global_scale.reshape(-1)[:1])
return torch.matmul(grad, nvfp4_dequantize(packed, scale, global_scale, grad.dtype))