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.

LayerNorm / RMSNorm: per-GPU num_warps tables (#15180)

Daniel Han90164297d814
diff --git a/tests/test_norm_arch_warps.py b/tests/test_norm_arch_warps.py
new file mode 100644
index 00000000000..da0b383d2f7
--- /dev/null
+++ b/tests/test_norm_arch_warps.py
@@ -0,0 +1,153 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Per-(GPU, width) num_warps table for the LayerNorm / RMSNorm kernels: routing, and the table's warps keep
+outputs as accurate as the default ones against an fp64 reference (forward, frozen-W and dW backward)."""
+
+import pytest
+import torch
+
+from unsloth.kernels import layernorm as LN
+from unsloth.kernels import rms_layernorm as RMS
+from unsloth.kernels import utils as U
+from unsloth.kernels.utils import calculate_settings
+
+T4 = (7, 5)
+# Read before any fixture runs: the `capability` fixture sets torch.version.hip to None to reach the CUDA tables.
+IS_HIP = bool(torch.version.hip)
+
+
+def _uncached(mod):
+ # The eager cache keys on (width, device, dw); these tests change the capability, flag and tables.
+ original = mod._settings
+
+ def settings(*args, **kwargs):
+ mod._cached_arch_settings.cache_clear()
+ RMS._dw_row_config.cache_clear()
+ return original(*args, **kwargs)
+
+ return settings
+
+
+def capability(monkeypatch):
+ cap = {"value": T4}
+ monkeypatch.setattr(U, "_cuda_capability", lambda index: cap["value"])
+ monkeypatch.setattr(U, "_NORM_ARCH_WARPS", True)
+ monkeypatch.setattr(U.torch.version, "hip", None)
+ for mod in (RMS, LN):
+ monkeypatch.setattr(mod, "_settings", _uncached(mod))
+ yield cap
+ for mod in (RMS, LN):
+ mod._cached_arch_settings.cache_clear()
+ RMS._dw_row_config.cache_clear()
+
+
[email protected]("dw", [False, True], ids = ["row", "dw"])
[email protected]("mod", [RMS, LN], ids = ["rms", "ln"])
+def test_table_routing(mod, dw, capability, monkeypatch):
+ dev = torch.device("cuda", 0)
+ table = mod._DW_NUM_WARPS if dw else mod._NUM_WARPS
+ other = mod._NUM_WARPS if dw else mod._DW_NUM_WARPS
+ for (cap, n_cols), warps in table.items():
+ capability["value"] = cap
+ assert mod._settings(n_cols, dev, dw = dw) == (calculate_settings(n_cols)[0], warps)
+ # the other table only: its own entry or the default
+ assert mod._settings(n_cols, dev, dw = not dw)[1] == other.get(
+ (cap, n_cols), calculate_settings(n_cols)[1]
+ )
+ # no device (callers outside the table's kernels), other GPUs: calculate_settings unchanged
+ assert mod._settings(n_cols, dw = dw) == calculate_settings(n_cols)
+ capability["value"] = (6, 1)
+ assert mod._settings(n_cols, dev, dw = dw) == calculate_settings(n_cols)
+ capability["value"] = cap
+ assert mod._settings(n_cols, torch.device("cpu"), dw = dw) == calculate_settings(n_cols)
+ monkeypatch.setattr(U.torch.version, "hip", "6.4")
+ assert mod._settings(n_cols, dev, dw = dw) == calculate_settings(n_cols)
+ monkeypatch.setattr(U.torch.version, "hip", None)
+ monkeypatch.setattr(U, "_NORM_ARCH_WARPS", False)
+ assert mod._settings(n_cols, dev, dw = dw) == calculate_settings(n_cols)
+ monkeypatch.setattr(U, "_NORM_ARCH_WARPS", True)
+ # widths outside the table keep the default
+ for width in (1000, 3072, 4095, 14336):
+ assert mod._settings(width, dev, dw = dw) == calculate_settings(width)
+
+
+def test_tables_are_sane():
+ for mod in (RMS, LN):
+ for table in (mod._NUM_WARPS, mod._DW_NUM_WARPS):
+ for (cap, n_cols), warps in table.items():
+ block = calculate_settings(n_cols)[0]
+ assert warps in (1, 2, 4, 8, 16, 32) and 32 * warps <= block <= 64 * 32 * warps
+ assert warps != calculate_settings(n_cols)[1]
+
+
+def _run(mod, X, W, b, dY, train_w):
+ X = X.clone().requires_grad_(True)
+ W = W.clone().requires_grad_(train_w)
+ if mod is LN:
+ b = b.clone().requires_grad_(train_w)
+ Y = LN.Fast_Layernorm.apply(X, W, b, 1e-5)
+ else:
+ Y = RMS.Fast_RMS_Layernorm.apply(X, W, 1e-6, False, False, False)
+ Y.backward(dY)
+ out = {"y": Y.detach(), "dx": X.grad}
+ if train_w:
+ out["dw"] = W.grad
+ if mod is LN:
+ out["db"] = b.grad
+ return out
+
+
+def _ref(mod, X, W, b, dY):
+ Xd = X.double().requires_grad_(True)
+ Wd = W.double().requires_grad_(True)
+ bd = b.double().requires_grad_(True)
+ if mod is LN:
+ Y = torch.nn.functional.layer_norm(Xd, (X.shape[-1],), Wd, bd, 1e-5)
+ else:
+ Y = Xd * torch.rsqrt(Xd.pow(2).mean(-1, keepdim = True) + 1e-6) * Wd
+ Y.backward(dY.double())
+ return {"y": Y.detach(), "dx": Xd.grad, "dw": Wd.grad, "db": bd.grad}
+
+
[email protected](not torch.cuda.is_available(), reason = "needs CUDA")
[email protected]("mod", [RMS, LN], ids = ["rms", "ln"])
[email protected]("dtype", [torch.float16, torch.bfloat16], ids = ["fp16", "bf16"])
+def test_table_warps_match_default_accuracy(mod, dtype, capability, monkeypatch):
+ # Run every table entry on this GPU (the capability is faked) against the default warps.
+ if IS_HIP:
+ # The fixture fakes a CUDA identity, so the dW launch would pass maxnreg, which HIP Triton rejects.
+ monkeypatch.setattr(RMS, "_max_sm_threads", lambda device: 0)
+ entries = sorted(set(mod._NUM_WARPS) | set(mod._DW_NUM_WARPS))
+ gen = torch.Generator(device = "cuda").manual_seed(3407)
+ for cap, n_cols in entries:
+ for rows in (1, 777, 4096):
+ X = torch.randn(rows, n_cols, device = "cuda", generator = gen).to(dtype)
+ W = (1 + 0.1 * torch.randn(n_cols, device = "cuda", generator = gen)).to(dtype)
+ b = (0.1 * torch.randn(n_cols, device = "cuda", generator = gen)).to(dtype)
+ dY = torch.randn(rows, n_cols, device = "cuda", generator = gen).to(dtype)
+ ref = _ref(mod, X, W, b, dY)
+ results = {}
+ for arm in ("default", "table"):
+ capability["value"] = cap if arm == "table" else (6, 1)
+ RMS._dw_row_config.cache_clear()
+ row = mod._NUM_WARPS.get((cap, n_cols)) if arm == "table" else None
+ dw = mod._DW_NUM_WARPS.get((cap, n_cols)) if arm == "table" else None
+ assert mod._settings(n_cols, X.device)[1] == (row or calculate_settings(n_cols)[1])
+ assert mod._settings(n_cols, X.device, dw = True)[1] == (
+ dw or calculate_settings(n_cols)[1]
+ )
+ frozen = _run(mod, X, W, b, dY, False)
+ trained = _run(mod, X, W, b, dY, True)
+ results[arm] = {**frozen, **{k + "_w": v for k, v in trained.items()}}
+ RMS._dw_row_config.cache_clear()
+ for key, value in results["table"].items():
+ base = key[:-2] if key.endswith("_w") else key
+ default = results["default"][key]
+ err = (value.double() - ref[base]).abs().max().item()
+ err_default = (default.double() - ref[base]).abs().max().item()
+ ulp = torch.finfo(dtype).eps * max(ref[base].abs().max().item(), 1.0)
+ assert torch.isfinite(value).all()
+ # A different reduction tree: allow one output ulp over the default's max error.
+ assert err <= err_default + ulp, (cap, n_cols, rows, key, err, err_default)
diff --git a/unsloth/kernels/layernorm.py b/unsloth/kernels/layernorm.py
index 70772ab6078..adc07c89b45 100644
--- a/unsloth/kernels/layernorm.py
+++ b/unsloth/kernels/layernorm.py
@@ -14,7 +14,7 @@ import functools
import triton
import triton.language as tl
import torch
-from .utils import calculate_settings, long_indexing, torch_gpu_device
+from .utils import calculate_settings, long_indexing, norm_num_warps, torch_gpu_device
from . import triton_launch
from .triton_launch import launch
from unsloth_zoo.patching_utils import (
@@ -211,14 +211,46 @@ def _dw_slots(device):
return 128, 32
-_cached_settings = functools.lru_cache(maxsize = None)(calculate_settings)
-
-
-def _settings(n_cols):
- # Cached per width for eager calls (host bound at small shapes); tracing calls it directly.
+# num_warps per (compute capability, n_cols), replacing calculate_settings' where a sweep (fp16 + bf16 on
+# sm_80+, fp16 on T4; 2k and 16k rows) found a width faster outside the run's A/A band in some cell and never
+# slower in any, at least 3% on the geometric mean, with max error vs fp64 no worse than the default's; every
+# entry then won again against main on torch 2.14.1 (same GPU tier, interleaved, outside A/A, never slower).
+# _NUM_WARPS: forward + frozen-W backward; _DW_NUM_WARPS: the dW / dB backward.
+_NUM_WARPS = {
+ ((7, 5), 2560): 16,
+ ((7, 5), 4096): 16,
+ ((8, 0), 2560): 2,
+ ((8, 9), 2048): 4,
+ ((9, 0), 2560): 2,
+ ((9, 0), 5120): 4,
+ ((12, 0), 5120): 4,
+}
+_DW_NUM_WARPS = {
+ ((7, 5), 4096): 16,
+ ((8, 0), 5120): 32,
+ ((9, 0), 5120): 32,
+ ((12, 0), 4096): 16,
+}
+
+
+def _arch_settings(n_cols, device, dw):
+ BLOCK_SIZE, num_warps = calculate_settings(n_cols)
+ table = _DW_NUM_WARPS if dw else _NUM_WARPS
+ return BLOCK_SIZE, norm_num_warps(table, n_cols, num_warps, device)
+
+
+_cached_arch_settings = functools.lru_cache(maxsize = None)(_arch_settings)
+
+
+def _settings(
+ n_cols,
+ device = None,
+ dw = False,
+):
+ # Cached per (width, device) for eager calls (host bound at small shapes); tracing calls it directly.
if torch.compiler.is_compiling():
- return calculate_settings(n_cols)
- return _cached_settings(n_cols)
+ return _arch_settings(n_cols, device, dw)
+ return _cached_arch_settings(n_cols, device, dw)
def _launch(kernel, grid, args, n_tensors, constexprs, device, **options):
@@ -241,8 +273,8 @@ class Fast_Layernorm(torch.autograd.Function):
has_bias = b is not None
b = b.contiguous() if has_bias else W
n_rows, n_cols = X.shape
- BLOCK_SIZE, num_warps = _settings(n_cols)
device = X.device
+ BLOCK_SIZE, num_warps = _settings(n_cols, device)
Y = torch.empty((n_rows, n_cols), dtype = X.dtype, device = device)
r = torch.empty(n_rows, dtype = torch.float32, device = device)
mu = torch.empty(n_rows, dtype = torch.float32, device = device)
@@ -307,7 +339,8 @@ class Fast_Layernorm(torch.autograd.Function):
)
return dX.view(*shape), None, None, None
- programs, rows_per_program = _dw_programs(device, n_rows, ctx.num_warps)
+ dw_warps = _settings(n_cols, device, dw = True)[1]
+ programs, rows_per_program = _dw_programs(device, n_rows, dw_warps)
# every program stores its partial row, so empty works unless no program launches
alloc = torch.empty if n_rows > 0 else torch.zeros
partials = alloc((train_w + train_b, programs, n_cols), dtype = torch.float32, device = device)
@@ -337,7 +370,7 @@ class Fast_Layernorm(torch.autograd.Function):
TRAIN_B = train_b,
),
device,
- num_warps = ctx.num_warps,
+ num_warps = dw_warps,
enable_fp_fusion = True,
)
_launch(
diff --git a/unsloth/kernels/rms_layernorm.py b/unsloth/kernels/rms_layernorm.py
index f841e3565ee..a7aba6d0f44 100644
--- a/unsloth/kernels/rms_layernorm.py
+++ b/unsloth/kernels/rms_layernorm.py
@@ -17,7 +17,7 @@ import triton
import triton.language as tl
import torch
from typing import Tuple
-from .utils import calculate_settings, long_indexing, torch_gpu_device
+from .utils import calculate_settings, long_indexing, norm_num_warps, torch_gpu_device
from . import triton_launch
from .triton_launch import launch
@@ -509,14 +509,48 @@ def _cdiv(a, b):
return (a + b - 1) // b
-_cached_settings = functools.lru_cache(maxsize = None)(calculate_settings)
-
-
-def _settings(n_cols):
- # Cached per width for eager calls (host bound at small shapes); tracing calls it directly.
+# num_warps per (compute capability, n_cols), replacing calculate_settings' where a sweep (fp16 + bf16 on
+# sm_80+, fp16 on T4; 2k and 16k rows) found a width faster outside the run's A/A band in some cell and never
+# slower in any, at least 3% on the geometric mean, with max error vs fp64 no worse than the default's; every
+# entry then won again against main on torch 2.14.1 (same GPU tier, interleaved, outside A/A, never slower).
+# _NUM_WARPS: one-row forward + frozen-W backward; _DW_NUM_WARPS: the dW backward.
+_NUM_WARPS = {
+ ((7, 5), 1024): 8,
+ ((7, 5), 2048): 16,
+ ((7, 5), 2560): 16,
+ ((7, 5), 4096): 32,
+ ((7, 5), 5120): 32,
+ ((7, 5), 8192): 32,
+ ((9, 0), 5120): 4,
+}
+_DW_NUM_WARPS = {
+ ((8, 9), 2560): 4,
+ ((8, 9), 4096): 2,
+ ((12, 0), 1024): 8,
+ ((12, 0), 2560): 4,
+ ((12, 0), 5120): 8,
+ ((12, 0), 8192): 4,
+}
+
+
+def _arch_settings(n_cols, device, dw):
+ BLOCK_SIZE, num_warps = calculate_settings(n_cols)
+ table = _DW_NUM_WARPS if dw else _NUM_WARPS
+ return BLOCK_SIZE, norm_num_warps(table, n_cols, num_warps, device)
+
+
+_cached_arch_settings = functools.lru_cache(maxsize = None)(_arch_settings)
+
+
+def _settings(
+ n_cols,
+ device = None,
+ dw = False,
+):
+ # Cached per (width, device) for eager calls (host bound at small shapes); tracing calls it directly.
if torch.compiler.is_compiling():
- return calculate_settings(n_cols)
- return _cached_settings(n_cols)
+ return _arch_settings(n_cols, device, dw)
+ return _cached_arch_settings(n_cols, device, dw)
def _launch(wrap, kernel, grid, args, n_tensors, constexprs, device, **options):
@@ -708,7 +742,7 @@ def _rms_forward(
if _multirow_must_raise(error, wrap):
raise
_multirow_disable(f"launch failed: {error!r}")
- BLOCK_SIZE, num_warps = _settings(n_cols)
+ BLOCK_SIZE, num_warps = _settings(n_cols, device)
_launch(
wrap,
_gemma_rms_layernorm_forward if gemma else _rms_layernorm_forward,
@@ -763,7 +797,7 @@ def _dw_launch(units, device):
@functools.lru_cache(maxsize = None)
def _dw_row_config(device, n_cols):
# Cached (host bound). 64-warp SMs, <= 16 elems/lane: cap registers at 64 so all programs stay resident.
- BLOCK_SIZE, num_warps = _settings(n_cols)
+ BLOCK_SIZE, num_warps = _settings(n_cols, device, dw = True)
per_sm, options = _DW_PROGRAMS_PER_SM, {}
if (
device.type == "cuda"
@@ -837,7 +871,7 @@ def _rms_backward(
programs, per_program = _dw_split(n_rows, max_programs)
partials = torch.empty((programs, n_cols), dtype = torch.float32, device = device)
else:
- BLOCK_SIZE, num_warps = _settings(n_cols)
+ BLOCK_SIZE, num_warps = _settings(n_cols, device)
_launch(
wrap,
_rms_layernorm_backward,
diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.py
index 9f7612b6db3..190ad29dfa7 100644
--- a/unsloth/kernels/utils.py
+++ b/unsloth/kernels/utils.py
@@ -142,6 +142,32 @@ def calculate_settings(
return BLOCK_SIZE, num_warps
+# UNSLOTH_NORM_ARCH_WARPS=0 keeps calculate_settings' warps in the LayerNorm / RMSNorm kernels.
+_NORM_ARCH_WARPS = os.environ.get("UNSLOTH_NORM_ARCH_WARPS", "1").strip().lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+)
+
+
[email protected]_cache(maxsize = None)
+def _cuda_capability(index):
+ return tuple(torch.cuda.get_device_capability(index))
+
+
+def norm_num_warps(table, n_cols, num_warps, device):
+ """num_warps from table[(capability, n_cols)] for CUDA devices, else the default."""
+ if not _NORM_ARCH_WARPS or device is None or device.type != "cuda" or torch.version.hip:
+ return num_warps
+ index = device.index if device.index is not None else torch.cuda.current_device()
+ if torch.compiler.is_compiling():
+ capability = tuple(torch.cuda.get_device_capability(index))
+ else:
+ capability = _cuda_capability(index)
+ return table.get((capability, n_cols), num_warps)
+
+
HAS_CUDA_STREAM = False
try:
import bitsandbytes as bnb