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.

Kernels: keep sequence length out of Triton specialization in the RoPE kernels (#16690)

Daniel Han2a256a174651
diff --git a/tests/test_triton_runtime_size_args.py b/tests/test_triton_runtime_size_args.py
index f8124e40b29..8cfb5b327eb 100644
--- a/tests/test_triton_runtime_size_args.py
+++ b/tests/test_triton_runtime_size_args.py
@@ -1,8 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""Per-call sizes (token rows, split counts) stay runtime Triton arguments with do_not_specialize, so a
-kernel does not compile a new variant per prompt length, batch size or split count."""
+"""Per-call sizes stay do_not_specialize (no recompile per shape); every tl.constexpr says why it is static."""
import ast
import pathlib
@@ -17,39 +16,115 @@ CASES = {
"_layernorm_sum_partials": ("n_programs",),
},
"fp8.py": {"_w8a8_block_fp8_matmul": ("M",)},
+ "rope_embedding.py": {"_rope_embedding_QK": ("seqlen",)},
+ "qk_norm_rope.py": {
+ "_qk_norm_rope_forward": ("seqlen",),
+ "_qk_norm_rope_backward": ("seqlen",),
+ },
+}
+
+# Must stay specialized: % 16 hint on masked/vector loads; NF4 GEMV M == 1 folds the row split.
+KEEP_SPECIALIZED = {
+ "swiglu.py": {"_fg_kernel": ("n_elements",), "_DWf_DW_dfg_kernel": ("n_elements",)},
+ "geglu.py": {
+ "_exact_forward_kernel": ("n_elements",),
+ "_approx_forward_kernel": ("n_elements",),
+ },
+ "nf4.py": {"_nf4_dequant_kernel": ("n_elements", "n_bytes")},
+ "nf4_gemv.py": {
+ "_gemv_nf4_kernel": ("OUT_STRIDE", "K", "M"),
+ "_gemv_nf4_words_kernel": ("OUT_STRIDE", "K", "M"),
+ },
+ "fp8_lora.py": {"_fp8_tensorwise_cast_kernel": ("numel",)},
}
+COMMENTED = ("nf4.py", "nf4_gemv.py", "fp8_lora.py", "multi_lora.py")
-def _defs(path):
- tree = ast.parse(path.read_text(encoding = "utf-8"))
+
+def _tree(rel):
+ path = KERNELS / rel
+ return path.read_text(encoding = "utf-8"), ast.parse(path.read_text(encoding = "utf-8"))
+
+
+def _defs(tree):
return {n.name: n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)}
-def _do_not_specialize(fn):
- for dec in fn.decorator_list:
- if isinstance(dec, ast.Call) and ast.unparse(dec.func).endswith("jit"):
- for kw in dec.keywords:
+def _names(node):
+ return {e.value for e in node.elts} if isinstance(node, (ast.Tuple, ast.List)) else set()
+
+
+def _do_not_specialize(tree, fn):
+ calls = [d for d in fn.decorator_list if isinstance(d, ast.Call)]
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.Assign)
+ and isinstance(node.value, ast.Call)
+ and node.value.args
+ and isinstance(node.value.args[0], ast.Name)
+ and node.value.args[0].id == fn.name
+ ):
+ calls.append(node.value)
+ out = set()
+ for call in calls:
+ if ast.unparse(call.func).endswith("jit"):
+ for kw in call.keywords:
if kw.arg == "do_not_specialize":
- return {e.value for e in kw.value.elts}
- return set()
+ out |= _names(kw.value)
+ return out
+
+
+def _is_constexpr(arg):
+ return arg.annotation is not None and "constexpr" in ast.unparse(arg.annotation)
@pytest.mark.parametrize("rel", sorted(CASES))
def test_runtime_sizes_are_not_specialized(rel):
- defs = _defs(KERNELS / rel)
+ _, tree = _tree(rel)
+ defs = _defs(tree)
for name, args in CASES[rel].items():
fn = defs[name]
params = {a.arg: a for a in fn.args.args}
- dns = _do_not_specialize(fn)
+ dns = _do_not_specialize(tree, fn)
for arg in args:
assert arg in params, (name, arg)
- ann = params[arg].annotation
- assert ann is None or "constexpr" not in ast.unparse(ann), (name, arg)
- assert arg in dns, (name, arg, sorted(dns))
+ assert not _is_constexpr(params[arg]), (name, arg)
+ assert arg in dns, f"{rel}:{name}: {arg} varies per call, needs do_not_specialize"
+
+
[email protected]("rel", sorted(KEEP_SPECIALIZED))
+def test_vector_sizes_keep_specialization(rel):
+ _, tree = _tree(rel)
+ defs = _defs(tree)
+ for name, args in KEEP_SPECIALIZED[rel].items():
+ fn = defs[name]
+ params = {a.arg for a in fn.args.args}
+ dns = _do_not_specialize(tree, fn)
+ for arg in args:
+ assert arg in params, (name, arg)
+ assert arg not in dns, f"{rel}:{name}: {arg} needs its % 16 hint"
+
+
[email protected]("rel", COMMENTED)
+def test_every_constexpr_is_commented(rel):
+ src, tree = _tree(rel)
+ lines = src.splitlines()
+ missing = []
+ for fn in _defs(tree).values():
+ cx = [a for a in fn.args.args if _is_constexpr(a)]
+ if not cx:
+ continue
+ end = fn.body[0].lineno - 1
+ comments = " ".join(l.split("#", 1)[1] for l in lines[fn.lineno - 1 : end] if "#" in l)
+ for a in cx:
+ own = lines[a.lineno - 1]
+ if "#" not in own and a.arg not in comments:
+ missing.append(f"{fn.name}.{a.arg}")
+ assert not missing, f"{rel}: constexpr without a why-static comment: {missing}"
def test_nvfp4_split_sum_keeps_split_constexpr():
# The unrolled static_range over SPLIT (2, 4, 8 or 16) is 13-34% faster than a runtime loop.
- fn = _defs(KERNELS / "nvfp4.py")["_split_sum_kernel"]
+ fn = _defs(_tree("nvfp4.py")[1])["_split_sum_kernel"]
ann = {a.arg: a.annotation for a in fn.args.args}["SPLIT"]
assert ann is not None and "constexpr" in ast.unparse(ann)
diff --git a/unsloth/kernels/fp8_lora.py b/unsloth/kernels/fp8_lora.py
index 3f565965663..615044d6038 100644
--- a/unsloth/kernels/fp8_lora.py
+++ b/unsloth/kernels/fp8_lora.py
@@ -141,7 +141,7 @@ _MULTI_GPU = torch.cuda.is_available() and torch.cuda.device_count() > 1
if triton is not None:
@triton.jit
- def _cast_fp8_rn(x, IS_E5M2: tl.constexpr):
+ def _cast_fp8_rn(x, IS_E5M2: tl.constexpr): # fp8 format, per recipe
# Triton 3.8 rounds through fp16 on sm89; native f32 conversion avoids double rounding.
if IS_E5M2:
packed = tl.inline_asm_elementwise(
@@ -171,9 +171,9 @@ if triton is not None:
amax_ptr,
inv_ptr,
numel,
- FP8_MAX: tl.constexpr,
- IS_E5M2: tl.constexpr,
- BLOCK: tl.constexpr,
+ FP8_MAX: tl.constexpr, # fp8 format max, per recipe
+ IS_E5M2: tl.constexpr, # fp8 format, per recipe
+ BLOCK: tl.constexpr, # elements per program, fixed 2048
):
pid = tl.program_id(0).to(tl.int64)
offs = pid * BLOCK + tl.arange(0, BLOCK)
@@ -226,10 +226,10 @@ if triton is not None:
inv_ptr,
K,
stride_xm,
- FP8_MAX: tl.constexpr,
- IS_E5M2: tl.constexpr,
- BLOCK_K: tl.constexpr,
- ONE_BLOCK: tl.constexpr,
+ FP8_MAX: tl.constexpr, # fp8 format max, per recipe
+ IS_E5M2: tl.constexpr, # fp8 format, per recipe
+ BLOCK_K: tl.constexpr, # row tile, from in_features
+ ONE_BLOCK: tl.constexpr, # the row fits one tile, from in_features
):
row = tl.program_id(0).to(tl.int64)
x_row = x_ptr + row * stride_xm
@@ -303,7 +303,7 @@ def quantize_rowwise(x: torch.Tensor, fp8_dtype = E4M3):
if triton is not None:
@triton.jit
- def _transpose_u8_kernel(x_ptr, y_ptr, R, C, BLOCK: tl.constexpr):
+ def _transpose_u8_kernel(x_ptr, y_ptr, R, C, BLOCK: tl.constexpr): # square tile, fixed 64
# Square tiles on purpose: non-square 2D fp8 transposed stores write corrupt bytes on sm89 (L4, triton 3.x).
rows = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
cols = tl.program_id(1).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
@@ -474,8 +474,8 @@ if triton is not None:
raw_s1,
delta_s0,
delta_s1,
- ROW_SCALE: tl.constexpr,
- BLOCK: tl.constexpr,
+ ROW_SCALE: tl.constexpr, # rowwise weight scales, per recipe
+ BLOCK: tl.constexpr, # elements per program, fixed 1024
):
offset = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
row, col = offset // N, offset % N
diff --git a/unsloth/kernels/multi_lora.py b/unsloth/kernels/multi_lora.py
index 65ffae01afe..7046e50ef60 100644
--- a/unsloth/kernels/multi_lora.py
+++ b/unsloth/kernels/multi_lora.py
@@ -132,14 +132,14 @@ if HAS_TRITON:
stride_wu,
stride_wk,
stride_wn,
- IN_SORTED: tl.constexpr,
- OUT_SORTED: tl.constexpr,
- ADD: tl.constexpr,
- SCALE: tl.constexpr,
- IEEE: tl.constexpr,
- BLOCK_M: tl.constexpr,
- BLOCK_N: tl.constexpr,
- BLOCK_K: tl.constexpr,
+ IN_SORTED: tl.constexpr, # IN rows in adapter order, per call site
+ OUT_SORTED: tl.constexpr, # OUT rows in adapter order, per call site
+ ADD: tl.constexpr, # accumulate into OUT, per call site
+ SCALE: tl.constexpr, # per-adapter scales given
+ IEEE: tl.constexpr, # fp32 inputs: ieee dot
+ BLOCK_M: tl.constexpr, # token tile, fixed 64
+ BLOCK_N: tl.constexpr, # from N (rank or out_features)
+ BLOCK_K: tl.constexpr, # from K (in_features or rank)
):
# OUT[rows] (+)= scale_u * IN[rows] @ W_u, W_u read as (K, N) through strides. A row is either the
# token's position in the sorted order (H, dH live there) or its original row (X, Y, dY, dX).
@@ -210,13 +210,13 @@ if HAS_TRITON:
stride_ou,
stride_oi,
stride_oj,
- P_SORTED: tl.constexpr,
- Q_SORTED: tl.constexpr,
- SCALE: tl.constexpr,
- IEEE: tl.constexpr,
- BLOCK_T: tl.constexpr,
- BLOCK_I: tl.constexpr,
- BLOCK_J: tl.constexpr,
+ P_SORTED: tl.constexpr, # P rows in adapter order, per call site
+ Q_SORTED: tl.constexpr, # Q rows in adapter order, per call site
+ SCALE: tl.constexpr, # per-adapter scales given
+ IEEE: tl.constexpr, # fp32 inputs: ieee dot
+ BLOCK_T: tl.constexpr, # token tile, fixed 64
+ BLOCK_I: tl.constexpr, # from I (weight dim)
+ BLOCK_J: tl.constexpr, # from J (weight dim)
):
# OUT_u = scale_u * P[seg_u].T @ Q[seg_u]; an adapter with no tokens stores zeros.
pid = tl.program_id(0)
diff --git a/unsloth/kernels/nf4.py b/unsloth/kernels/nf4.py
index e1a0a91b9ed..ce8e87a8f3a 100644
--- a/unsloth/kernels/nf4.py
+++ b/unsloth/kernels/nf4.py
@@ -31,7 +31,7 @@ _HAS_MUL_RN = torch.version.hip is None and os.environ.get("TRITON_INTERPRET", "
@triton.jit
-def _mul(a, b, USE_MUL_RN: tl.constexpr):
+def _mul(a, b, USE_MUL_RN: tl.constexpr): # libdevice mul_rn available (CUDA)
if USE_MUL_RN:
return libdevice.mul_rn(a, b)
else:
@@ -56,7 +56,7 @@ else:
@triton.jit
-def _nf4_lut(lut_ptr, n, LUT_MODE: tl.constexpr):
+def _nf4_lut(lut_ptr, n, LUT_MODE: tl.constexpr): # lookup strategy, per GPU config
# n: int32 nibbles. Every mode returns the same fp32 table entry, so the choice is speed only.
if LUT_MODE == 0:
# A 64-byte table gather stays in L1.
@@ -100,10 +100,10 @@ def _nf4_dequant_kernel(
n_bytes,
n_blocks,
HALF: tl.constexpr, # packed bytes per absmax block (blocksize // 2)
- BLOCKSIZE2_SHIFT: tl.constexpr,
- NESTED: tl.constexpr,
- USE_MUL_RN: tl.constexpr,
- ROWS: tl.constexpr, # absmax blocks per program
+ BLOCKSIZE2_SHIFT: tl.constexpr, # log2 of the nested absmax block, per weight
+ NESTED: tl.constexpr, # double quantized state
+ USE_MUL_RN: tl.constexpr, # libdevice mul_rn available (CUDA)
+ ROWS: tl.constexpr, # absmax blocks per program, bucketed from the weight size
WORDS: tl.constexpr, # load the packed bytes as int32 words (needs n_bytes % 4 == 0)
EVICT: tl.constexpr, # "evict_first" streams the weight and the output past L2, else ""
LUT_MODE: tl.constexpr, # see _nf4_lut
diff --git a/unsloth/kernels/nf4_gemv.py b/unsloth/kernels/nf4_gemv.py
index a78e4e0fce9..f2d9d8cf269 100644
--- a/unsloth/kernels/nf4_gemv.py
+++ b/unsloth/kernels/nf4_gemv.py
@@ -27,6 +27,8 @@ __all__ = [
]
+# M stays specialized: M == 1 folds the row split (unspecialized 0.5-0.9% slower on T4), and M == 1
+# vs 2..4 are separate call sites, so no extra variants.
@triton.jit
def _gemv_nf4_kernel(
X,
@@ -39,16 +41,16 @@ def _gemv_nf4_kernel(
OUT,
N,
K,
- M,
+ M, # specialized on == 1 (see above)
OUT_STRIDE,
- BLOCKSIZE: tl.constexpr,
- BLOCKSIZE2: tl.constexpr,
- NESTED: tl.constexpr,
- USE_MUL_RN: tl.constexpr,
- BLOCK_N: tl.constexpr,
- BLOCK_K: tl.constexpr,
- EVEN_K: tl.constexpr,
- LUT_MODE: tl.constexpr,
+ BLOCKSIZE: tl.constexpr, # nf4 absmax block, per weight
+ BLOCKSIZE2: tl.constexpr, # nested absmax block, per weight
+ NESTED: tl.constexpr, # double quantized state
+ USE_MUL_RN: tl.constexpr, # libdevice mul_rn available (CUDA)
+ BLOCK_N: tl.constexpr, # output rows per program, from N
+ BLOCK_K: tl.constexpr, # K tile, from K and blocksize
+ EVEN_K: tl.constexpr, # K % BLOCK_K == 0, per weight
+ LUT_MODE: tl.constexpr, # codebook lookup, from BLOCK_K
):
# FSDP-QLoRA packs the 4bit weight into float storage; it is bytes either way.
W = W.to(tl.pointer_type(tl.uint8))
@@ -108,14 +110,14 @@ def _gemv_nf4_words_kernel(
OUT,
N,
K,
- M,
+ M, # specialized on == 1 (see above)
OUT_STRIDE,
- BLOCKSIZE: tl.constexpr,
- BLOCKSIZE2: tl.constexpr,
- NESTED: tl.constexpr,
- USE_MUL_RN: tl.constexpr,
- BLOCK_N: tl.constexpr,
- BLOCK_K: tl.constexpr,
+ BLOCKSIZE: tl.constexpr, # nf4 absmax block, per weight
+ BLOCKSIZE2: tl.constexpr, # nested absmax block, per weight
+ NESTED: tl.constexpr, # double quantized state
+ USE_MUL_RN: tl.constexpr, # libdevice mul_rn available (CUDA)
+ BLOCK_N: tl.constexpr, # output rows per program, 1 here
+ BLOCK_K: tl.constexpr, # K tile, from K and blocksize
):
# _gemv_nf4_kernel reading int32 words of 8 nibbles; faster before Triton 3.7, slower on 3.7.
W = W.to(tl.pointer_type(tl.int32))
diff --git a/unsloth/kernels/qk_norm_rope.py b/unsloth/kernels/qk_norm_rope.py
index 44ba7d92dc2..11fd2bfebc0 100644
--- a/unsloth/kernels/qk_norm_rope.py
+++ b/unsloth/kernels/qk_norm_rope.py
@@ -84,7 +84,7 @@ def _norm_rope_fwd_block(
tl.store(y_ptr + HALF, y1 * cos1[None, :] + y0 * sin1[None, :], mask = mask)
[email protected](do_not_specialize = ("seqlen",))
def _qk_norm_rope_forward(
Qo,
Q,
@@ -194,7 +194,7 @@ def _norm_rope_bwd_block(
tl.store(dx_ptr + HALF, scale * tl.fma(-n1, rowsum[:, None], HEAD_DIM * g1), mask = mask)
[email protected](do_not_specialize = ("seqlen",))
def _qk_norm_rope_backward(
dQ,
dQo,
diff --git a/unsloth/kernels/rope_embedding.py b/unsloth/kernels/rope_embedding.py
index 57eeb69babe..1b2fd377910 100644
--- a/unsloth/kernels/rope_embedding.py
+++ b/unsloth/kernels/rope_embedding.py
@@ -119,7 +119,7 @@ def _rope_embedding_QK(
sin,
sin_row_stride,
rope_embedding_indices,
- seqlen,
+ seqlen, # runtime, not specialized: varies per call
n_heads_Q: tl.constexpr, # 32
n_heads_K: tl.constexpr, # 8 (0 without K)
n_groups_Q: tl.constexpr, # 1
@@ -224,7 +224,7 @@ def _rope_embedding_QK(
# No triton.heuristics wrapper: the launcher passes real bools, and the wrapper's per-call cost
# showed up at small (decode / short-sequence) shapes.
-_rope_embedding_QK = triton.jit(_rope_embedding_QK)
+_rope_embedding_QK = triton.jit(_rope_embedding_QK, do_not_specialize = ("seqlen",))
# Elements of one half-head tile a program rotates: several heads per program instead of one
# program per (row, head) with half its lanes masked off.