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.

Triton kernels: GPU guard against mid-generate recompiles, comment every tl.constexpr (#16575)

Daniel Han2c94592bd592
diff --git a/tests/test_triton_constexpr_comments.py b/tests/test_triton_constexpr_comments.py
new file mode 100644
index 00000000000..2659fd446ef
--- /dev/null
+++ b/tests/test_triton_constexpr_comments.py
@@ -0,0 +1,136 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Every tl.constexpr parameter of an Unsloth Triton kernel says what it is on its own line, and no
+kernel takes a per-call size (rows, tokens, sequence length, batch) as a constexpr: each distinct
+constexpr value compiles a new kernel, so a size that changes per call recompiles per call."""
+
+import ast
+import io
+import pathlib
+import tokenize
+
+ROOT = pathlib.Path(__file__).resolve().parents[1] / "unsloth"
+SKIP_DIRS = {"_vendor", "__pycache__"}
+KERNEL_DECORATORS = {"jit", "autotune", "heuristics"}
+PER_CALL_NAMES = {
+ "M",
+ "T",
+ "n_rows",
+ "num_rows",
+ "seq_len",
+ "seqlen",
+ "q_len",
+ "kv_len",
+ "batch",
+ "bsz",
+ "num_tokens",
+ "n_tokens",
+}
+
+
+def _dotted(node):
+ parts = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+
+
+def _is_kernel_decorator(node):
+ name = _dotted(node.func if isinstance(node, ast.Call) else node)
+ last = name.split(".")[-1]
+ return last in KERNEL_DECORATORS and (name.startswith("triton") or name == last)
+
+
+def _kernels(tree):
+ """FunctionDefs decorated as Triton kernels, or wrapped as `k = triton.jit(f)`."""
+ # Keyed by node: two factories may each define a kernel with the same name.
+ defs = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
+ found = {id(n): n for n in defs if any(_is_kernel_decorator(d) for d in n.decorator_list)}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Call) and node.args and isinstance(node.args[0], ast.Name):
+ outer = node.func.func if isinstance(node.func, ast.Call) else node.func
+ if _is_kernel_decorator(outer):
+ found.update({id(n): n for n in defs if n.name == node.args[0].id})
+ return found.values()
+
+
+def _constexpr_params(path):
+ source = path.read_text(encoding = "utf-8")
+ tree = ast.parse(source)
+ comments = {
+ tok.start[0]
+ for tok in tokenize.generate_tokens(io.StringIO(source).readline)
+ if tok.type == tokenize.COMMENT
+ }
+ for fn in _kernels(tree):
+ for arg in fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs:
+ if arg.annotation is not None and _dotted(arg.annotation).endswith("constexpr"):
+ yield fn.name, arg.arg, arg.lineno, arg.lineno in comments
+
+
+def _files():
+ for path in sorted(ROOT.rglob("*.py")):
+ if SKIP_DIRS.isdisjoint(path.relative_to(ROOT).parts):
+ text = path.read_text(encoding = "utf-8")
+ if "constexpr" in text:
+ yield path
+
+
+def test_finds_kernels():
+ # Guards the walk itself: a refactor that hides every kernel would pass the checks below vacuously.
+ params = [p for path in _files() for p in _constexpr_params(path)]
+ assert len(params) > 300
+ assert {path.name for path in _files()} >= {
+ "nf4_gemv.py",
+ "rms_layernorm.py",
+ "cross_entropy_loss.py",
+ }
+
+
+def test_every_constexpr_line_has_a_comment():
+ missing = [
+ f"{path.relative_to(ROOT.parent)}:{line} {kernel}.{name}"
+ for path in _files()
+ for kernel, name, line, commented in _constexpr_params(path)
+ if not commented
+ ]
+ assert not missing, "tl.constexpr parameters without a comment:\n" + "\n".join(missing)
+
+
+def test_no_per_call_size_is_constexpr():
+ bad = [
+ f"{path.relative_to(ROOT.parent)}:{line} {kernel}.{name}"
+ for path in _files()
+ for kernel, name, line, _ in _constexpr_params(path)
+ if name in PER_CALL_NAMES
+ ]
+ assert not bad, "per-call sizes must be runtime arguments:\n" + "\n".join(bad)
+
+
+def test_scanner_sees_same_name_and_positional_only_kernels(tmp_path):
+ src = tmp_path / "k.py"
+ src.write_text(
+ "import triton\nimport triton.language as tl\n\n"
+ "def make_a():\n"
+ " @triton.jit\n"
+ " def kernel(x, BLOCK: tl.constexpr):\n"
+ " pass\n\n"
+ "def make_b():\n"
+ " @triton.jit\n"
+ " def kernel(x, BLOCK: tl.constexpr): # elements per program\n"
+ " pass\n\n"
+ "@triton.jit\n"
+ "def pos(n_rows: tl.constexpr, /, x): # rows\n"
+ " pass\n",
+ encoding = "utf-8",
+ )
+ found = sorted((k, n, line, c) for k, n, line, c in _constexpr_params(src))
+ assert found == [
+ ("kernel", "BLOCK", 6, False),
+ ("kernel", "BLOCK", 11, True),
+ ("pos", "n_rows", 15, True),
+ ]
diff --git a/tests/test_triton_kernel_binaries.py b/tests/test_triton_kernel_binaries.py
new file mode 100644
index 00000000000..b9fdaaa07ab
--- /dev/null
+++ b/tests/test_triton_kernel_binaries.py
@@ -0,0 +1,120 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Mid-generate recompiles, counted on real Triton binaries: once the first decode / prefill shapes are
+built, other batch sizes (GEMV rows up to the default cap of 4) and prompt lengths, multiples of 16
+included, build nothing new; outputs still match a reference."""
+
+import pytest
+import torch
+from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py
+
+if not has_real_cuda():
+ pytest.skip(reason = "needs a CUDA device", allow_module_level = True)
+pytest.importorskip("triton")
+
+import unsloth # noqa: F401
+
+
+def _binaries(*kernels):
+ total = 0
+ for k in kernels:
+ caches = getattr(k, "device_caches", None)
+ if caches is None:
+ pytest.skip(reason = "this Triton keeps no device_caches to count binaries in")
+ total += sum(len(c[0]) for c in caches.values())
+ return total
+
+
+def test_gemv_rows_no_new_binary_per_batch_size():
+ F = pytest.importorskip("bitsandbytes.functional")
+ from unsloth.kernels import nf4_gemv as G
+
+ g = torch.Generator(device = "cuda").manual_seed(0)
+ W = torch.randn(1024, 4096, dtype = torch.float16, device = "cuda", generator = g)
+ q, s = F.quantize_4bit(W, quant_type = "nf4", compress_statistics = True)
+ W_dq = F.dequantize_4bit(q, s).float()
+
+ def run(m):
+ X = torch.randn(m, 1, 4096, dtype = torch.float16, device = "cuda", generator = g)
+ out = torch.empty(m, 1, 1024, dtype = torch.float16, device = "cuda")
+ G.gemv_nf4_rows(X, q, s.absmax, s.state2.code, s.state2.absmax, s.offset, s.code, s.blocksize, s.state2.blocksize, s.shape, out) # fmt: skip
+ ref = X.float().view(m, -1) @ W_dq.t()
+ err = (out.float().view(m, -1) - ref).abs().max() / ref.abs().max()
+ assert err < 1e-2, (m, err.item())
+
+ run(1)
+ run(2)
+ built = _binaries(*G._KERNELS)
+ for m in (3, 4):
+ run(m)
+ assert _binaries(*G._KERNELS) == built
+
+
+def _rope_ref(x, cos, sin):
+ half = x.shape[-1] // 2
+ seq = x.shape[2]
+ c, s = cos[:seq].float(), sin[:seq].float()
+ xf = x.float()
+ return xf * c + torch.cat((-xf[..., half:], xf[..., :half]), -1) * s
+
+
+def test_rope_no_new_binary_per_seqlen():
+ from unsloth.kernels import rope_embedding as RE
+
+ H, KV, D = 8, 4, 64
+ emb = torch.outer(torch.arange(512.0, device = "cuda"), torch.rand(D // 2, device = "cuda"))
+ emb = torch.cat((emb, emb), -1)
+ cos, sin = emb.cos().half(), emb.sin().half()
+
+ def run(seq):
+ qkv = torch.randn(3, seq, (H + 2 * KV) * D, device = "cuda", dtype = torch.float16)
+ qkv.requires_grad_(True)
+ Q = qkv[..., : H * D].view(3, seq, H, D).transpose(1, 2)
+ K = qkv[..., H * D : (H + KV) * D].view(3, seq, KV, D).transpose(1, 2)
+ q_ref, k_ref = _rope_ref(Q.detach(), cos, sin), _rope_ref(K.detach(), cos, sin)
+ q, k = RE.fast_rope_embedding(Q, K, cos, sin)
+ torch.testing.assert_close(q.float(), q_ref, rtol = 2e-3, atol = 2e-3)
+ torch.testing.assert_close(k.float(), k_ref, rtol = 2e-3, atol = 2e-3)
+ (q.float().sum() + k.float().sum()).backward()
+
+ run(1)
+ run(7)
+ built = _binaries(RE._rope_embedding_QK)
+ for seq in (16, 32, 48, 300):
+ run(seq)
+ assert _binaries(RE._rope_embedding_QK) == built
+
+
+def test_qk_norm_rope_no_new_binary_per_seqlen():
+ from unsloth.kernels import qk_norm_rope as QN
+
+ H, KV, D = 8, 4, 128
+ norms = [torch.nn.RMSNorm(D, eps = 1e-6, device = "cuda", dtype = torch.float16) for _ in "qk"]
+ for n in norms:
+ n.weight.requires_grad_(False)
+ n.variance_epsilon = 1e-6
+ emb = torch.outer(torch.arange(512.0, device = "cuda"), torch.rand(D // 2, device = "cuda"))
+ emb = torch.cat((emb, emb), -1)
+ cos, sin = emb.cos().half(), emb.sin().half()
+
+ def run(seq):
+ Q = torch.randn(2, seq, H, D, device = "cuda", dtype = torch.float16, requires_grad = True)
+ K = torch.randn(2, seq, KV, D, device = "cuda", dtype = torch.float16, requires_grad = True)
+ q, k = QN.fast_qk_norm_rope(norms[0], norms[1], Q, K, cos, sin)
+ x = Q.detach().float()
+ x = x * torch.rsqrt(x.square().mean(-1, keepdim = True) + 1e-6) * norms[0].weight.float()
+ q_ref = _rope_ref(x.transpose(1, 2), cos, sin)
+ torch.testing.assert_close(q.float(), q_ref, rtol = 1e-2, atol = 1e-2)
+ (q.float().sum() + k.float().sum()).backward()
+
+ run(1)
+ run(7)
+ kernels = QN._qk_norm_rope_forward, QN._qk_norm_rope_backward
+ built = _binaries(*kernels)
+ for seq in (16, 32, 48, 300):
+ run(seq)
+ assert _binaries(*kernels) == built
diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.py
index 6efc964e6b9..25d3ed245a1 100644
--- a/unsloth/kernels/fp8.py
+++ b/unsloth/kernels/fp8.py
@@ -1294,8 +1294,8 @@ def _fp8_rowwise_gemv_rows_reduce(
y_ptr,
M,
N,
- SPLIT_K: tl.constexpr,
- BLOCK: tl.constexpr, # SPLIT_K split-K factor, BLOCK block size
+ SPLIT_K: tl.constexpr, # split-K factor
+ BLOCK: tl.constexpr, # block size
):
offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
mask = offs < M * N
diff --git a/unsloth/kernels/geglu.py b/unsloth/kernels/geglu.py
index 992ec705b30..2974a6d3442 100644
--- a/unsloth/kernels/geglu.py
+++ b/unsloth/kernels/geglu.py
@@ -31,8 +31,8 @@ def _exact_forward_kernel(
g,
h,
n_elements,
- BLOCK_SIZE: tl.constexpr,
- LONG_INDEXING: tl.constexpr, # BLOCK_SIZE elements per program, LONG_INDEXING int64 offsets past 2**31
+ BLOCK_SIZE: tl.constexpr, # elements per program
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
):
block_idx = tl.program_id(0)
if LONG_INDEXING:
@@ -78,8 +78,8 @@ def _exact_backward_kernel(
e,
g,
n_elements,
- BLOCK_SIZE: tl.constexpr,
- LONG_INDEXING: tl.constexpr, # BLOCK_SIZE elements per program, LONG_INDEXING int64 offsets past 2**31
+ BLOCK_SIZE: tl.constexpr, # elements per program
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
):
"""
f = 1/2 * e * (1 + erf(1/sqrt(2) * e))
@@ -150,8 +150,8 @@ def _approx_forward_kernel(
g,
h,
n_elements,
- BLOCK_SIZE: tl.constexpr,
- LONG_INDEXING: tl.constexpr, # BLOCK_SIZE elements per program, LONG_INDEXING int64 offsets past 2**31
+ BLOCK_SIZE: tl.constexpr, # elements per program
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
):
block_idx = tl.program_id(0)
if LONG_INDEXING:
@@ -199,8 +199,8 @@ def _approx_backward_kernel(
e,
g,
n_elements,
- BLOCK_SIZE: tl.constexpr,
- LONG_INDEXING: tl.constexpr, # BLOCK_SIZE elements per program, LONG_INDEXING int64 offsets past 2**31
+ BLOCK_SIZE: tl.constexpr, # elements per program
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
):
"""
f = 1/2 * e * (1 + tanh( sqrt(2/pi) * x * (1 + 0.044715 * x^2 ) ))
diff --git a/unsloth/kernels/layernorm.py b/unsloth/kernels/layernorm.py
index 1536df0aecd..3b0dcbab851 100644
--- a/unsloth/kernels/layernorm.py
+++ b/unsloth/kernels/layernorm.py
@@ -194,8 +194,8 @@ def _layernorm_sum_partials(
out1,
n_programs,
n_cols,
- BLOCK_ROWS: tl.constexpr,
- BLOCK_COLS: tl.constexpr, # BLOCK_ROWS partial rows per program, BLOCK_COLS columns per program
+ BLOCK_ROWS: tl.constexpr, # partial rows per program
+ BLOCK_COLS: tl.constexpr, # columns per program
):
# Not torch.sum: Inductor reorders it, so eager and compiled bytes would differ.
which = tl.program_id(1)
diff --git a/unsloth/kernels/nvfp4.py b/unsloth/kernels/nvfp4.py
index 2d3016bdb2b..9ed77d6678d 100644
--- a/unsloth/kernels/nvfp4.py
+++ b/unsloth/kernels/nvfp4.py
@@ -556,8 +556,12 @@ def _fused_config(
@triton.jit
def _split_sum_kernel(
- partial_ptr, out_ptr, numel, SPLIT: tl.constexpr, BLOCK: tl.constexpr
-): # SPLIT split-K partials, BLOCK block size
+ partial_ptr,
+ out_ptr,
+ numel,
+ SPLIT: tl.constexpr, # split-K partials (2, 4, 8 or 16)
+ BLOCK: tl.constexpr, # block size
+):
# Fixed-order sum of the split partials (determinism), one cast. SPLIT stays constexpr: the unrolled
# static_range is 13-34% faster than a runtime loop, and SPLIT is only ever 2, 4, 8 or 16.
offs = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
diff --git a/unsloth/kernels/rms_layernorm.py b/unsloth/kernels/rms_layernorm.py
index 823af45423a..4d9581eef12 100644
--- a/unsloth/kernels/rms_layernorm.py
+++ b/unsloth/kernels/rms_layernorm.py
@@ -253,8 +253,11 @@ def _gemma_rms_layernorm_forward(
@triton.jit
def _fold_lanes(
- x, ROWS: tl.constexpr, WARPS: tl.constexpr, HALF: tl.constexpr
-): # ROWS rows per program, WARPS num_warps of the launch, HALF half of a lane pair
+ x,
+ ROWS: tl.constexpr, # rows per program
+ WARPS: tl.constexpr, # num_warps of the launch
+ HALF: tl.constexpr, # half of a lane pair
+):
return tl.sum(tl.reshape(x, (ROWS, WARPS, 2, HALF)), axis = 2)
@@ -265,8 +268,11 @@ _HIP_ROW_ORDER = tl.constexpr(bool(torch.version.hip))
@triton.jit
def _row_dot_in_hip_row_order(
- a, b, ROWS: tl.constexpr, WARPS: tl.constexpr
-): # ROWS rows per program, WARPS num_warps of the launch
+ a,
+ b,
+ ROWS: tl.constexpr, # rows per program
+ WARPS: tl.constexpr, # num_warps of the launch
+):
# Bit-exact replay of the one-row kernels' tl.sum on AMD (WARPS = BLOCK_SIZE // wavefront):
# fma(a_l, b_l, a_(l-8) * b_(l-8)), row_shr 4, 2, 1, 16-lane rows by lane bit 4 then 5, warps.
LANES: tl.constexpr = a.shape[1] // WARPS
@@ -289,8 +295,11 @@ def _row_dot_in_hip_row_order(
@triton.jit
def _row_dot_in_cuda_row_order(
- a, b, ROWS: tl.constexpr, WARPS: tl.constexpr
-): # ROWS rows per program, WARPS num_warps of the launch
+ a,
+ b,
+ ROWS: tl.constexpr, # rows per program
+ WARPS: tl.constexpr, # num_warps of the launch
+):
# Bit-exact replay of the one-row kernels' tl.sum (4 warps, 64 <= BLOCK_SIZE <= 128):
# fma(a_l, b_l, a_(l+16) * b_(l+16)), lane xor 8, 4, 2, 1, warp xor 2, 1; explicit steps only.
a = tl.permute(tl.reshape(a, (ROWS, WARPS, 2, 16)), (0, 1, 3, 2))
@@ -310,8 +319,11 @@ def _row_dot_in_cuda_row_order(
@triton.jit
def _row_dot_in_row_kernel_order(
- a, b, ROWS: tl.constexpr, WARPS: tl.constexpr
-): # ROWS rows per program, WARPS num_warps of the launch
+ a,
+ b,
+ ROWS: tl.constexpr, # rows per program
+ WARPS: tl.constexpr, # num_warps of the launch
+):
if _HIP_ROW_ORDER:
total = _row_dot_in_hip_row_order(a, b, ROWS, WARPS)
else:
@@ -499,8 +511,8 @@ def _rms_sum_dw_partials(
dW,
n_programs,
n_cols,
- BLOCK_ROWS: tl.constexpr,
- BLOCK_COLS: tl.constexpr, # BLOCK_ROWS partial rows per step, BLOCK_COLS columns per program
+ BLOCK_ROWS: tl.constexpr, # partial rows per step
+ BLOCK_COLS: tl.constexpr, # columns per program
):
# Fixed tile order, so eager and torch.compile give the same bytes.
cols = tl.program_id(0) * BLOCK_COLS + tl.arange(0, BLOCK_COLS)
diff --git a/unsloth/kernels/rope_embedding.py b/unsloth/kernels/rope_embedding.py
index 702ac37e100..e15323337a6 100644
--- a/unsloth/kernels/rope_embedding.py
+++ b/unsloth/kernels/rope_embedding.py
@@ -227,39 +227,39 @@ def _rope_embedding_QK(
K,
K_out,
q_batch_stride,
- q_seq_stride: tl.constexpr,
+ q_seq_stride: tl.constexpr, # fixed per model layout
q_head_stride,
- q_dim_stride: tl.constexpr,
+ q_dim_stride: tl.constexpr, # 1
qo_batch_stride,
- qo_seq_stride: tl.constexpr,
+ qo_seq_stride: tl.constexpr, # fixed per model layout
qo_head_stride,
- qo_dim_stride: tl.constexpr,
+ qo_dim_stride: tl.constexpr, # 1
k_batch_stride,
- k_seq_stride: tl.constexpr,
+ k_seq_stride: tl.constexpr, # fixed per model layout
k_head_stride,
- k_dim_stride: tl.constexpr,
+ k_dim_stride: tl.constexpr, # 1
ko_batch_stride,
- ko_seq_stride: tl.constexpr,
+ ko_seq_stride: tl.constexpr, # fixed per model layout
ko_head_stride,
- ko_dim_stride: tl.constexpr,
+ ko_dim_stride: tl.constexpr, # 1
cos,
cos_row_stride,
sin,
sin_row_stride,
rope_embedding_indices,
seqlen,
- n_heads_Q: tl.constexpr,
- n_heads_K: tl.constexpr,
- n_groups_Q: tl.constexpr,
- half_head_dim: tl.constexpr,
- BACKWARD_PASS: tl.constexpr,
- HAS_ROPE_INDICES: tl.constexpr,
- LONG_INDEXING: tl.constexpr,
- CAST_TO_SIN: tl.constexpr,
- HEADS_Q: tl.constexpr,
- HEADS_K: tl.constexpr,
- BLOCK_SIZE: tl.constexpr,
- EVICT_INDICES: tl.constexpr,
+ n_heads_Q: tl.constexpr, # query heads
+ n_heads_K: tl.constexpr, # key heads (0 without K)
+ n_groups_Q: tl.constexpr, # query heads per K head
+ half_head_dim: tl.constexpr, # head_dim // 2
+ BACKWARD_PASS: tl.constexpr, # negated sin
+ HAS_ROPE_INDICES: tl.constexpr, # explicit position ids
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
+ CAST_TO_SIN: tl.constexpr, # compute in sin's dtype
+ HEADS_Q: tl.constexpr, # query heads per program
+ HEADS_K: tl.constexpr, # key heads per program
+ BLOCK_SIZE: tl.constexpr, # next pow2 of head_dim // 2
+ EVICT_INDICES: tl.constexpr, # evict-first hint on position ids
):
"""Layout strides as constexprs (fixed per model)."""
_rope_qk_program(
@@ -331,18 +331,18 @@ def _rope_embedding_QK_strided(
sin_row_stride,
rope_embedding_indices,
seqlen,
- n_heads_Q: tl.constexpr,
- n_heads_K: tl.constexpr,
- n_groups_Q: tl.constexpr,
- half_head_dim: tl.constexpr,
- BACKWARD_PASS: tl.constexpr,
- HAS_ROPE_INDICES: tl.constexpr,
- LONG_INDEXING: tl.constexpr,
- CAST_TO_SIN: tl.constexpr,
- HEADS_Q: tl.constexpr,
- HEADS_K: tl.constexpr,
- BLOCK_SIZE: tl.constexpr,
- EVICT_INDICES: tl.constexpr,
+ n_heads_Q: tl.constexpr, # query heads
+ n_heads_K: tl.constexpr, # key heads (0 without K)
+ n_groups_Q: tl.constexpr, # query heads per K head
+ half_head_dim: tl.constexpr, # head_dim // 2
+ BACKWARD_PASS: tl.constexpr, # negated sin
+ HAS_ROPE_INDICES: tl.constexpr, # explicit position ids
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
+ CAST_TO_SIN: tl.constexpr, # compute in sin's dtype
+ HEADS_Q: tl.constexpr, # query heads per program
+ HEADS_K: tl.constexpr, # key heads per program
+ BLOCK_SIZE: tl.constexpr, # next pow2 of head_dim // 2
+ EVICT_INDICES: tl.constexpr, # evict-first hint on position ids
):
"""Runtime layout strides, for strides that depend on seq_len (dK as [b, h, d, s])."""
_rope_qk_program(
diff --git a/unsloth/kernels/swiglu.py b/unsloth/kernels/swiglu.py
index b82c396c2bf..c5ef49cde4f 100644
--- a/unsloth/kernels/swiglu.py
+++ b/unsloth/kernels/swiglu.py
@@ -23,8 +23,13 @@ INT32_SAFETY_BUFFER = NUM_INT32_ELEMENTS - BLOCK_SIZE * SAFE_INT32_BUFFER_MULTIP
@triton.jit
def _fg_kernel(
- e, g, h, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr
-): # BLOCK_SIZE elements per program, LONG_INDEXING int64 offsets past 2**31
+ e,
+ g,
+ h,
+ n_elements,
+ BLOCK_SIZE: tl.constexpr, # elements per program
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
+):
block_idx = tl.program_id(0)
if LONG_INDEXING:
offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to(tl.int64)
@@ -65,8 +70,13 @@ def swiglu_fg_kernel(e, g):
@triton.jit
def _DWf_DW_dfg_kernel(
- DW, e, g, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr
-): # BLOCK_SIZE elements per program, LONG_INDEXING int64 offsets past 2**31
+ DW,
+ e,
+ g,
+ n_elements,
+ BLOCK_SIZE: tl.constexpr, # elements per program
+ LONG_INDEXING: tl.constexpr, # int64 offsets past 2**31
+):
"""
e = e.float()
se = 1.0 / (1.0 + torch.exp(-e))
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index ff0ecc46928..271979626dd 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -597,7 +597,7 @@ def _triton_probe(index):
import triton.language as tl
@triton.jit
- def _add_one(X, N, BLOCK: tl.constexpr):
+ def _add_one(X, N, BLOCK: tl.constexpr): # BLOCK: 16, a fixed probe size
offsets = tl.arange(0, BLOCK)
tl.store(X + offsets, tl.load(X + offsets, offsets < N) + 1, offsets < N)
diff --git a/unsloth/optimizers/bf16_adamw.py b/unsloth/optimizers/bf16_adamw.py
index 17f7fe24307..a26988bf475 100644
--- a/unsloth/optimizers/bf16_adamw.py
+++ b/unsloth/optimizers/bf16_adamw.py
@@ -25,11 +25,11 @@ if triton is not None:
N,
SEED,
TILE,
- B1: tl.constexpr,
- B2: tl.constexpr,
- EPS: tl.constexpr,
- WD: tl.constexpr,
- BLOCK: tl.constexpr,
+ B1: tl.constexpr, # beta1
+ B2: tl.constexpr, # beta2
+ EPS: tl.constexpr, # Adam eps
+ WD: tl.constexpr, # weight decay
+ BLOCK: tl.constexpr, # elements per program
):
i = TILE.to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
valid = i < N
@@ -68,11 +68,11 @@ if triton is not None:
SEED,
LR,
sizes,
- B1: tl.constexpr,
- B2: tl.constexpr,
- EPS: tl.constexpr,
- WD: tl.constexpr,
- BLOCK: tl.constexpr,
+ B1: tl.constexpr, # beta1
+ B2: tl.constexpr, # beta2
+ EPS: tl.constexpr, # Adam eps
+ WD: tl.constexpr, # weight decay
+ BLOCK: tl.constexpr, # elements per program
):
pid = tl.program_id(0).to(tl.int64)
start = tl.full((), 0, tl.int64)
@@ -108,11 +108,11 @@ if triton is not None:
LR,
N,
SEED,
- B1: tl.constexpr,
- B2: tl.constexpr,
- EPS: tl.constexpr,
- WD: tl.constexpr,
- BLOCK: tl.constexpr,
+ B1: tl.constexpr, # beta1
+ B2: tl.constexpr, # beta2
+ EPS: tl.constexpr, # Adam eps
+ WD: tl.constexpr, # weight decay
+ BLOCK: tl.constexpr, # elements per program
):
_adamw_tile(P, G, M, V, STEP, LR, N, SEED, tl.program_id(0), B1, B2, EPS, WD, BLOCK)
diff --git a/unsloth/optimizers/flash_adamw.py b/unsloth/optimizers/flash_adamw.py
index ac731610975..ff72ecd6a49 100644
--- a/unsloth/optimizers/flash_adamw.py
+++ b/unsloth/optimizers/flash_adamw.py
@@ -260,8 +260,13 @@ def _variance_update(var, grad, beta2):
@triton.jit
def kernel(
- var_ptr, grad_ptr, out_ptr, n, beta2, BLOCK: tl.constexpr
- ): # elements per program
+ var_ptr,
+ grad_ptr,
+ out_ptr,
+ n,
+ beta2,
+ BLOCK: tl.constexpr, # elements per program
+ ):
offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
mask = offsets < n
v = tl.load(var_ptr + offsets, mask = mask)