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.

Fused Qwen3 q_norm / k_norm RMSNorm + RoPE Triton kernel (opt-in) (#13890)

Daniel Han701a3453caf3
diff --git a/tests/test_qk_norm_rope.py b/tests/test_qk_norm_rope.py
new file mode 100644
index 00000000000..2e78e63199e
--- /dev/null
+++ b/tests/test_qk_norm_rope.py
@@ -0,0 +1,187 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""fast_qk_norm_rope (per-head RMSNorm + RoPE, one launch each way) vs the unfused
+fast_rms_layernorm + fast_rope_embedding path and an fp64 reference."""
+
+import pytest
+import torch
+
+if not torch.cuda.is_available():
+ pytest.skip("needs a CUDA device", allow_module_level = True)
+
+pytest.importorskip("triton")
+
+import unsloth # noqa: F401
+import torch._dynamo.utils as dynamo_utils
+from unsloth.kernels import rms_layernorm
+from unsloth.kernels.qk_norm_rope import _unfused, fast_qk_norm_rope
+
+TRACEABLE = hasattr(torch.library, "triton_op") and hasattr(torch.library, "wrap_triton")
+BF16 = pytest.param(
+ torch.bfloat16,
+ marks = pytest.mark.skipif(
+ not rms_layernorm._BF16_TRACEABLE, reason = "no native bf16: bf16 stays untraced"
+ ),
+)
+CDTYPE = torch.bfloat16 if rms_layernorm._BF16_TRACEABLE else torch.float16
+EPS = 1e-6
+
+
+class _Norm(torch.nn.Module):
+ def __init__(
+ self,
+ dim,
+ dtype,
+ seed,
+ trainable = False,
+ ):
+ super().__init__()
+ g = torch.Generator(device = "cuda").manual_seed(seed)
+ w = torch.randn(dim, device = "cuda", generator = g) * 0.3 + 1
+ self.weight = torch.nn.Parameter(w.to(dtype), requires_grad = trainable)
+ self.variance_epsilon = EPS
+
+
+def _case(
+ bsz,
+ seq,
+ n_heads,
+ n_kv,
+ head_dim,
+ dtype,
+ packed,
+ trainable = False,
+):
+ g = torch.Generator(device = "cuda").manual_seed(0)
+ q_lin = (torch.randn(bsz, seq, n_heads * head_dim, device = "cuda", generator = g) * 2 + 0.3).to(
+ dtype
+ )
+ k_lin = (torch.randn(bsz, seq, n_kv * head_dim, device = "cuda", generator = g) * 0.5).to(dtype)
+ inv = 1.0 / (1e6 ** (torch.arange(0, head_dim, 2, device = "cuda").float() / head_dim))
+ emb = torch.outer(torch.arange(seq + 16, device = "cuda").float(), inv)
+ emb = torch.cat((emb, emb), -1)
+ cos, sin = emb.cos().to(dtype), emb.sin().to(dtype)
+ if packed:
+ lens = [seq // 3, seq // 3, seq - 2 * (seq // 3)]
+ pos = torch.cat([torch.arange(n) for n in lens]).repeat(bsz, 1).cuda()
+ else:
+ pos = None
+ grads = (
+ torch.randn(bsz, n_heads, seq, head_dim, device = "cuda", generator = g).to(dtype),
+ torch.randn(bsz, n_kv, seq, head_dim, device = "cuda", generator = g).to(dtype),
+ )
+ norms = _Norm(head_dim, dtype, 1, trainable), _Norm(head_dim, dtype, 2, trainable)
+ return q_lin, k_lin, cos, sin, pos, grads, norms
+
+
+def _run(fn, q_lin, k_lin, cos, sin, pos, grads, norms, head_dim):
+ bsz, seq = q_lin.shape[:2]
+ a = q_lin.detach().clone().requires_grad_(True)
+ b = k_lin.detach().clone().requires_grad_(True)
+ Q = a.view(bsz, seq, -1, head_dim)
+ K = b.view(bsz, seq, -1, head_dim)
+ q, k = fn(norms[0], norms[1], Q, K, cos, sin, pos)
+ torch.autograd.backward((q, k), grads)
+ return q.detach(), k.detach(), a.grad, b.grad
+
+
+def _ref64(q_lin, k_lin, cos, sin, pos, grads, norms, head_dim):
+ bsz, seq = q_lin.shape[:2]
+ a = q_lin.double().requires_grad_(True)
+ b = k_lin.double().requires_grad_(True)
+ if pos is None:
+ pos = torch.arange(seq, device = "cuda").repeat(bsz, 1)
+ c, s = cos[pos].double()[:, None], sin[pos].double()[:, None]
+
+ def f(x, w):
+ y = x * torch.rsqrt(x.pow(2).mean(-1, keepdim = True) + EPS) * w.double()
+ y = y.transpose(1, 2)
+ half = head_dim // 2
+ return y * c + torch.cat((-y[..., half:], y[..., :half]), -1) * s
+
+ q = f(a.view(bsz, seq, -1, head_dim), norms[0].weight)
+ k = f(b.view(bsz, seq, -1, head_dim), norms[1].weight)
+ torch.autograd.backward((q, k), [x.double() for x in grads])
+ return q.detach(), k.detach(), a.grad, b.grad
+
+
+def _err(x, ref):
+ return (x.double() - ref).abs().max().item()
+
+
[email protected]("dtype", [BF16, torch.float16, torch.float32])
[email protected]("packed", [False, True])
+ "shape",
+ [
+ (2, 130, 32, 8, 128),
+ (1, 77, 12, 4, 64),
+ (2, 64, 8, 1, 256),
+ (1, 33, 16, 16, 128),
+ (1, 50, 20, 5, 128),
+ ],
+)
+def test_matches_unfused_within_rounding(shape, packed, dtype):
+ bsz, seq, n_heads, n_kv, head_dim = shape
+ case = _case(bsz, seq, n_heads, n_kv, head_dim, dtype, packed)
+ fused = _run(fast_qk_norm_rope, *case, head_dim)
+ main = _run(_unfused, *case, head_dim)
+ ref = _ref64(*case, head_dim)
+ ulp = torch.finfo(dtype).eps
+ for f, m, r in zip(fused, main, ref):
+ scale = r.abs().max().item()
+ assert _err(f, r) <= 1.5 * _err(m, r) + 2 * ulp * scale
+
+
+def test_fused_inputs_and_grads_untouched():
+ case = _case(2, 64, 16, 4, 128, CDTYPE, True)
+ q_lin, k_lin, cos, sin, pos, grads, norms = case
+ a = q_lin.clone().requires_grad_(True)
+ b = k_lin.clone().requires_grad_(True)
+ g0, g1 = grads[0].clone(), grads[1].clone()
+ q, k = fast_qk_norm_rope(
+ norms[0], norms[1], a.view(2, 64, 16, 128), b.view(2, 64, 4, 128), cos, sin, pos
+ )
+ torch.autograd.backward((q, k), grads)
+ assert torch.equal(a.detach(), q_lin) and torch.equal(b.detach(), k_lin)
+ assert torch.equal(grads[0], g0) and torch.equal(grads[1], g1)
+ assert q.data_ptr() != a.data_ptr() and k.data_ptr() != b.data_ptr()
+
+
+def test_trainable_norm_weights_fall_back_to_unfused():
+ case = _case(1, 40, 8, 2, 64, torch.float32, False, trainable = True)
+ q_lin, k_lin, cos, sin, pos, grads, norms = case
+ q, k = fast_qk_norm_rope(
+ norms[0], norms[1], q_lin.view(1, 40, 8, 64), k_lin.view(1, 40, 2, 64), cos, sin, pos
+ )
+ torch.autograd.backward((q, k), grads)
+ assert norms[0].weight.grad is not None and norms[1].weight.grad is not None
+
+
+def test_broadcast_position_ids():
+ bsz, seq = 3, 50
+ case = _case(bsz, seq, 8, 2, 128, CDTYPE, False)
+ q_lin, k_lin, cos, sin, _, grads, norms = case
+ one_row = torch.arange(seq, device = "cuda")[None]
+ full = one_row.expand(bsz, seq)
+ a = _run(fast_qk_norm_rope, q_lin, k_lin, cos, sin, one_row, grads, norms, 128)
+ b = _run(fast_qk_norm_rope, q_lin, k_lin, cos, sin, full, grads, norms, 128)
+ c = _run(fast_qk_norm_rope, q_lin, k_lin, cos, sin, None, grads, norms, 128)
+ for x, y, z in zip(a, b, c):
+ assert torch.equal(x, y) and torch.equal(x, z)
+
+
[email protected](not TRACEABLE, reason = "needs torch.library.triton_op")
[email protected]("dtype", [BF16, torch.float16, torch.float32])
[email protected]("packed", [False, True])
+def test_compiled_no_graph_breaks_same_bytes(dtype, packed):
+ torch._dynamo.reset()
+ dynamo_utils.counters.clear()
+ case = _case(2, 96, 16, 4, 128, dtype, packed)
+ eager = _run(fast_qk_norm_rope, *case, 128)
+ compiled = _run(torch.compile(fast_qk_norm_rope, fullgraph = True), *case, 128)
+ assert sum(dynamo_utils.counters["graph_break"].values()) == 0
+ for x, y in zip(eager, compiled):
+ assert torch.equal(x, y)
+ torch._dynamo.reset()
diff --git a/unsloth/kernels/qk_norm_rope.py b/unsloth/kernels/qk_norm_rope.py
new file mode 100644
index 00000000000..16c6f17c2be
--- /dev/null
+++ b/unsloth/kernels/qk_norm_rope.py
@@ -0,0 +1,450 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+# Per-head RMSNorm (Qwen3 q_norm / k_norm) followed by RoPE, as one forward and one backward
+# launch for Q and K together. Outputs are always fresh tensors.
+
+import os
+import triton
+import triton.language as tl
+import torch
+from typing import Tuple
+from .utils import torch_gpu_device
+from .rms_layernorm import (
+ _BF16_TRACEABLE,
+ _TRACEABLE,
+ _eager_kernel,
+ _tag_compile_cache,
+ _traced_kernel,
+ fast_rms_layernorm,
+)
+from .rope_embedding import fast_rope_embedding, _sync_if_split
+
+__all__ = [
+ "fast_qk_norm_rope",
+ "QK_NORM_ROPE_ENABLED",
+]
+
+QK_NORM_ROPE_ENABLED = os.environ.get("UNSLOTH_FUSED_QKNORM_ROPE", "0") == "1"
+
+
+def _norm_rope_fwd_block(
+ Y,
+ X,
+ X_row_stride,
+ X_head_stride,
+ W,
+ r,
+ row,
+ heads,
+ n_heads,
+ cos1,
+ sin1,
+ cols,
+ eps,
+ HEAD_DIM: tl.constexpr,
+):
+ HALF = HEAD_DIM // 2
+ hmask = heads < n_heads
+ mask = hmask[:, None]
+ x_ptr = X + row * X_row_stride + heads[:, None].to(tl.int64) * X_head_stride + cols[None, :]
+ x0 = tl.load(x_ptr, mask = mask, other = 0).to(tl.float32)
+ x1 = tl.load(x_ptr + HALF, mask = mask, other = 0).to(tl.float32)
+ var = (tl.sum(x0 * x0, axis = 1) + tl.sum(x1 * x1, axis = 1)) / HEAD_DIM
+ inv = tl.math.rsqrt(var + tl.full((), eps, tl.float32))
+ tl.store(r + row * n_heads + heads, inv, mask = hmask)
+ w0 = tl.load(W + cols)
+ w1 = tl.load(W + HALF + cols)
+ # Same roundings as fast_rms_layernorm then the RoPE kernel: normed in W's dtype, the norm output
+ # in Y's dtype, the rotation in cos's dtype.
+ y0 = ((x0 * inv[:, None]).to(w0.dtype) * w0[None, :]).to(Y.dtype.element_ty).to(cos1.dtype)
+ y1 = ((x1 * inv[:, None]).to(w1.dtype) * w1[None, :]).to(Y.dtype.element_ty).to(cos1.dtype)
+ y_ptr = Y + (row * n_heads + heads[:, None].to(tl.int64)) * HEAD_DIM + cols[None, :]
+ tl.store(y_ptr, y0 * cos1[None, :] - y1 * sin1[None, :], mask = mask)
+ tl.store(y_ptr + HALF, y1 * cos1[None, :] + y0 * sin1[None, :], mask = mask)
+
+
+def _qk_norm_rope_forward(
+ Qo,
+ Q,
+ Q_row_stride,
+ Q_head_stride,
+ Wq,
+ rq,
+ n_heads_Q,
+ eps_Q,
+ Ko,
+ K,
+ K_row_stride,
+ K_head_stride,
+ Wk,
+ rk,
+ n_heads_K,
+ eps_K,
+ cos,
+ cos_row_stride,
+ sin,
+ sin_row_stride,
+ rope_indices,
+ seqlen,
+ HEAD_DIM: tl.constexpr,
+ BLOCK_H: tl.constexpr,
+ HAS_ROPE_INDICES: tl.constexpr,
+):
+ row = tl.program_id(0).to(tl.int64)
+ hblock = tl.program_id(1)
+ n_blocks_Q = (n_heads_Q + BLOCK_H - 1) // BLOCK_H
+ cols = tl.arange(0, HEAD_DIM // 2)
+ if HAS_ROPE_INDICES:
+ pos = tl.load(rope_indices + row).to(tl.int64)
+ else:
+ pos = row % seqlen
+ cos1 = tl.load(cos + pos * cos_row_stride + cols)
+ sin1 = tl.load(sin + pos * sin_row_stride + cols)
+ if hblock < n_blocks_Q:
+ heads = hblock * BLOCK_H + tl.arange(0, BLOCK_H)
+ _norm_rope_fwd_block(
+ Qo, Q, Q_row_stride, Q_head_stride, Wq, rq, row, heads, n_heads_Q,
+ cos1, sin1, cols, eps_Q, HEAD_DIM,
+ ) # fmt: skip
+ else:
+ heads = (hblock - n_blocks_Q) * BLOCK_H + tl.arange(0, BLOCK_H)
+ _norm_rope_fwd_block(
+ Ko, K, K_row_stride, K_head_stride, Wk, rk, row, heads, n_heads_K,
+ cos1, sin1, cols, eps_K, HEAD_DIM,
+ ) # fmt: skip
+
+
+def _norm_rope_bwd_block(
+ dX,
+ dY,
+ dY_batch_stride,
+ dY_seq_stride,
+ dY_head_stride,
+ X,
+ X_row_stride,
+ X_head_stride,
+ W,
+ r,
+ row,
+ batch_id,
+ seq_index,
+ heads,
+ n_heads,
+ cos1,
+ sin1,
+ cols,
+ HEAD_DIM: tl.constexpr,
+):
+ HALF = HEAD_DIM // 2
+ hmask = heads < n_heads
+ mask = hmask[:, None]
+ hoff = heads[:, None].to(tl.int64)
+ dy_ptr = (
+ dY
+ + batch_id * dY_batch_stride
+ + seq_index * dY_seq_stride
+ + hoff * dY_head_stride
+ + cols[None, :]
+ )
+ dy0 = tl.load(dy_ptr, mask = mask, other = 0)
+ dy1 = tl.load(dy_ptr + HALF, mask = mask, other = 0)
+ # Inverse rotation (sin negated), rounded to dY's dtype as the RoPE backward stores it.
+ dn0 = (dy0 * cos1[None, :] + dy1 * sin1[None, :]).to(dY.dtype.element_ty).to(tl.float32)
+ dn1 = (dy1 * cos1[None, :] - dy0 * sin1[None, :]).to(dY.dtype.element_ty).to(tl.float32)
+
+ x_ptr = X + row * X_row_stride + hoff * X_head_stride + cols[None, :]
+ x0 = tl.load(x_ptr, mask = mask, other = 0).to(tl.float32)
+ x1 = tl.load(x_ptr + HALF, mask = mask, other = 0).to(tl.float32)
+ inv = tl.load(r + row * n_heads + heads, mask = hmask, other = 0)
+ w0 = tl.load(W + cols).to(tl.float32)
+ w1 = tl.load(W + HALF + cols).to(tl.float32)
+ n0 = x0 * inv[:, None]
+ n1 = x1 * inv[:, None]
+ g0 = dn0 * w0[None, :]
+ g1 = dn1 * w1[None, :]
+ rowsum = tl.sum(g0 * n0, axis = 1) + tl.sum(g1 * n1, axis = 1)
+ scale = (inv / HEAD_DIM)[:, None]
+ dx_ptr = dX + (row * n_heads + hoff) * HEAD_DIM + cols[None, :]
+ tl.store(dx_ptr, scale * (HEAD_DIM * g0 - n0 * rowsum[:, None]), mask = mask)
+ tl.store(dx_ptr + HALF, scale * (HEAD_DIM * g1 - n1 * rowsum[:, None]), mask = mask)
+
+
+def _qk_norm_rope_backward(
+ dQ,
+ dQo,
+ dQo_batch_stride,
+ dQo_seq_stride,
+ dQo_head_stride,
+ Q,
+ Q_row_stride,
+ Q_head_stride,
+ Wq,
+ rq,
+ n_heads_Q,
+ dK,
+ dKo,
+ dKo_batch_stride,
+ dKo_seq_stride,
+ dKo_head_stride,
+ K,
+ K_row_stride,
+ K_head_stride,
+ Wk,
+ rk,
+ n_heads_K,
+ cos,
+ cos_row_stride,
+ sin,
+ sin_row_stride,
+ rope_indices,
+ seqlen,
+ HEAD_DIM: tl.constexpr,
+ BLOCK_H: tl.constexpr,
+ HAS_ROPE_INDICES: tl.constexpr,
+):
+ row = tl.program_id(0).to(tl.int64)
+ hblock = tl.program_id(1)
+ n_blocks_Q = (n_heads_Q + BLOCK_H - 1) // BLOCK_H
+ cols = tl.arange(0, HEAD_DIM // 2)
+ batch_id = row // seqlen
+ seq_index = row - batch_id * seqlen
+ if HAS_ROPE_INDICES:
+ pos = tl.load(rope_indices + row).to(tl.int64)
+ else:
+ pos = seq_index
+ cos1 = tl.load(cos + pos * cos_row_stride + cols)
+ sin1 = tl.load(sin + pos * sin_row_stride + cols)
+ if hblock < n_blocks_Q:
+ heads = hblock * BLOCK_H + tl.arange(0, BLOCK_H)
+ _norm_rope_bwd_block(
+ dQ, dQo, dQo_batch_stride, dQo_seq_stride, dQo_head_stride, Q, Q_row_stride,
+ Q_head_stride, Wq, rq, row, batch_id, seq_index, heads, n_heads_Q, cos1, sin1, cols,
+ HEAD_DIM,
+ ) # fmt: skip
+ else:
+ heads = (hblock - n_blocks_Q) * BLOCK_H + tl.arange(0, BLOCK_H)
+ _norm_rope_bwd_block(
+ dK, dKo, dKo_batch_stride, dKo_seq_stride, dKo_head_stride, K, K_row_stride,
+ K_head_stride, Wk, rk, row, batch_id, seq_index, heads, n_heads_K, cos1, sin1, cols,
+ HEAD_DIM,
+ ) # fmt: skip
+
+
+def _block_h(n_heads_Q, n_heads_K, head_dim):
+ block = 1
+ while block < min(n_heads_Q, n_heads_K) and block * 2 * head_dim <= 2048:
+ block *= 2
+ return block
+
+
+def _num_warps(block_h, head_dim):
+ return 8 if block_h * head_dim >= 4096 else 4
+
+
+def _launch_forward(Q, K, Wq, Wk, cos, sin, rope_indices, eps_Q, eps_K, has_indices, wrap):
+ # Q [batch, seq_len, n_heads_Q, head_dim], K [..., n_heads_K, head_dim]; rows = batch * seq_len.
+ batch, seq_len, n_heads_Q, head_dim = Q.shape
+ n_heads_K = K.shape[2]
+ rows = batch * seq_len
+ Q = Q.reshape(rows, n_heads_Q, head_dim)
+ K = K.reshape(rows, n_heads_K, head_dim)
+ Qo = torch.empty((batch, seq_len, n_heads_Q, head_dim), dtype = Q.dtype, device = Q.device)
+ Ko = torch.empty((batch, seq_len, n_heads_K, head_dim), dtype = K.dtype, device = K.device)
+ rq = torch.empty((rows, n_heads_Q), dtype = torch.float32, device = Q.device)
+ rk = torch.empty((rows, n_heads_K), dtype = torch.float32, device = Q.device)
+ BLOCK_H = _block_h(n_heads_Q, n_heads_K, head_dim)
+ n_blocks = (n_heads_Q + BLOCK_H - 1) // BLOCK_H + (n_heads_K + BLOCK_H - 1) // BLOCK_H
+ wrap(_qk_norm_rope_forward)[(rows, n_blocks)](
+ Qo, Q, Q.stride(0), Q.stride(1), Wq, rq, n_heads_Q, eps_Q,
+ Ko, K, K.stride(0), K.stride(1), Wk, rk, n_heads_K, eps_K,
+ cos, cos.stride(0), sin, sin.stride(0), rope_indices, seq_len,
+ HEAD_DIM = head_dim, BLOCK_H = BLOCK_H, HAS_ROPE_INDICES = has_indices,
+ num_warps = _num_warps(BLOCK_H, head_dim), enable_fp_fusion = True,
+ ) # fmt: skip
+ return Qo, Ko, rq, rk
+
+
+def _launch_backward(dQo, dKo, Q, K, Wq, Wk, rq, rk, cos, sin, rope_indices, has_indices, wrap):
+ batch, seq_len, n_heads_Q, head_dim = Q.shape
+ n_heads_K = K.shape[2]
+ rows = batch * seq_len
+ Q = Q.reshape(rows, n_heads_Q, head_dim)
+ K = K.reshape(rows, n_heads_K, head_dim)
+ if dQo.stride(-1) != 1:
+ dQo = dQo.contiguous()
+ if dKo.stride(-1) != 1:
+ dKo = dKo.contiguous()
+ dQ = torch.empty((batch, seq_len, n_heads_Q, head_dim), dtype = dQo.dtype, device = Q.device)
+ dK = torch.empty((batch, seq_len, n_heads_K, head_dim), dtype = dKo.dtype, device = Q.device)
+ BLOCK_H = _block_h(n_heads_Q, n_heads_K, head_dim)
+ n_blocks = (n_heads_Q + BLOCK_H - 1) // BLOCK_H + (n_heads_K + BLOCK_H - 1) // BLOCK_H
+ wrap(_qk_norm_rope_backward)[(rows, n_blocks)](
+ dQ, dQo, dQo.stride(0), dQo.stride(1), dQo.stride(2), Q, Q.stride(0), Q.stride(1), Wq, rq, n_heads_Q,
+ dK, dKo, dKo.stride(0), dKo.stride(1), dKo.stride(2), K, K.stride(0), K.stride(1), Wk, rk, n_heads_K,
+ cos, cos.stride(0), sin, sin.stride(0), rope_indices, seq_len,
+ HEAD_DIM = head_dim, BLOCK_H = BLOCK_H, HAS_ROPE_INDICES = has_indices,
+ num_warps = _num_warps(BLOCK_H, head_dim), enable_fp_fusion = True,
+ ) # fmt: skip
+ return dQ, dK
+
+
+class Fast_QK_Norm_RoPE(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, Q, K, Wq, Wk, cos, sin, rope_indices, eps_Q, eps_K, has_indices):
+ with torch_gpu_device(Q.device):
+ Qo, Ko, rq, rk = _launch_forward(
+ Q, K, Wq, Wk, cos, sin, rope_indices, eps_Q, eps_K, has_indices, _eager_kernel
+ )
+ ctx.has_indices = has_indices
+ ctx.save_for_backward(Q, K, Wq, Wk, rq, rk, cos, sin, rope_indices)
+ return Qo, Ko
+
+ @staticmethod
+ def backward(ctx, dQo, dKo):
+ Q, K, Wq, Wk, rq, rk, cos, sin, rope_indices = ctx.saved_tensors
+ with torch_gpu_device(dQo.device):
+ dQ, dK = _launch_backward(
+ dQo, dKo, Q, K, Wq, Wk, rq, rk, cos, sin, rope_indices, ctx.has_indices,
+ _eager_kernel,
+ ) # fmt: skip
+ return dQ, dK, None, None, None, None, None, None, None, None
+
+
+if _TRACEABLE:
+
+ @torch.library.triton_op("unsloth::qk_norm_rope", mutates_args = ())
+ def _qk_norm_rope_op(
+ Q: torch.Tensor,
+ K: torch.Tensor,
+ Wq: torch.Tensor,
+ Wk: torch.Tensor,
+ cos: torch.Tensor,
+ sin: torch.Tensor,
+ rope_indices: torch.Tensor,
+ eps_Q: float,
+ eps_K: float,
+ has_indices: bool,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ with torch_gpu_device(Q.device):
+ return _launch_forward(
+ Q, K, Wq, Wk, cos, sin, rope_indices, eps_Q, eps_K, has_indices, _traced_kernel
+ )
+
+ @torch.library.triton_op("unsloth::qk_norm_rope_backward", mutates_args = ())
+ def _qk_norm_rope_backward_op(
+ dQo: torch.Tensor,
+ dKo: torch.Tensor,
+ Q: torch.Tensor,
+ K: torch.Tensor,
+ Wq: torch.Tensor,
+ Wk: torch.Tensor,
+ rq: torch.Tensor,
+ rk: torch.Tensor,
+ cos: torch.Tensor,
+ sin: torch.Tensor,
+ rope_indices: torch.Tensor,
+ has_indices: bool,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ with torch_gpu_device(dQo.device):
+ return _launch_backward(
+ dQo, dKo, Q, K, Wq, Wk, rq, rk, cos, sin, rope_indices, has_indices,
+ _traced_kernel,
+ ) # fmt: skip
+
+ def _qk_norm_rope_setup_context(ctx, inputs, output):
+ Q, K, Wq, Wk, cos, sin, rope_indices, _, _, has_indices = inputs
+ ctx.has_indices = has_indices
+ ctx.save_for_backward(Q, K, Wq, Wk, output[2], output[3], cos, sin, rope_indices)
+
+ def _qk_norm_rope_op_backward(ctx, dQo, dKo, drq, drk):
+ Q, K, Wq, Wk, rq, rk, cos, sin, rope_indices = ctx.saved_tensors
+ if dQo is None:
+ dQo = torch.zeros(Q.shape, dtype = Q.dtype, device = Q.device)
+ if dKo is None:
+ dKo = torch.zeros(K.shape, dtype = K.dtype, device = K.device)
+ dQ, dK = torch.ops.unsloth.qk_norm_rope_backward(
+ dQo, dKo, Q, K, Wq, Wk, rq, rk, cos, sin, rope_indices, ctx.has_indices
+ )
+ return dQ, dK, None, None, None, None, None, None, None, None
+
+ _qk_norm_rope_op.register_autograd(
+ _qk_norm_rope_op_backward, setup_context = _qk_norm_rope_setup_context
+ )
+ _tag_compile_cache(__file__)
+
+
+def _eps(norm):
+ return norm.variance_epsilon if hasattr(norm, "variance_epsilon") else norm.eps
+
+
+def _unfused(q_norm, k_norm, Q, K, cos, sin, position_ids):
+ Q = fast_rms_layernorm(q_norm, Q).transpose(1, 2)
+ K = fast_rms_layernorm(k_norm, K).transpose(1, 2)
+ return fast_rope_embedding(Q, K, cos, sin, position_ids)
+
+
+def _fused_untraced(*args):
+ return Fast_QK_Norm_RoPE.apply(*args)
+
+
+def fast_qk_norm_rope(
+ q_norm,
+ k_norm,
+ Q,
+ K,
+ cos,
+ sin,
+ position_ids = None,
+):
+ """RMSNorm each head of Q [batch, seq_len, n_heads, head_dim] and K with q_norm / k_norm, then
+ rotate both. Returns Q, K as [batch, n_heads, seq_len, head_dim] like fast_rope_embedding.
+ Falls back to fast_rms_layernorm + fast_rope_embedding where the fused kernel does not apply
+ (trainable norm weights, non-CUDA, odd head_dim, cos / sin not a [positions, head_dim] table)."""
+ Wq, Wk = q_norm.weight, k_norm.weight
+ batch, seq_len, _, head_dim = Q.shape
+ cos2, sin2 = cos.squeeze(), sin.squeeze()
+ if (
+ Wq.requires_grad
+ or Wk.requires_grad
+ or Q.device.type != "cuda"
+ or head_dim % 2 != 0
+ or head_dim & (head_dim - 1) != 0
+ or head_dim < 16
+ or head_dim > 1024
+ or cos2.dim() != 2
+ or cos2.shape[-1] != head_dim
+ or sin2.shape != cos2.shape
+ or cos2.stride(-1) != 1
+ or sin2.stride(-1) != 1
+ or Q.stride(-1) != 1
+ or K.stride(-1) != 1
+ or Wq.shape[-1] != head_dim
+ or Wk.shape[-1] != head_dim
+ ):
+ return _unfused(q_norm, k_norm, Q, K, cos, sin, position_ids)
+ has_indices = position_ids is not None
+ if has_indices:
+ if position_ids.numel() == seq_len and batch != 1:
+ position_ids = position_ids.reshape(1, seq_len).expand(batch, seq_len)
+ if position_ids.numel() != batch * seq_len:
+ return _unfused(q_norm, k_norm, Q, K, cos, sin, position_ids)
+ rope_indices = position_ids.reshape(-1).to(dtype = torch.int32, device = Q.device)
+ else:
+ if seq_len > cos2.shape[0]:
+ return _unfused(q_norm, k_norm, Q, K, cos, sin, position_ids)
+ rope_indices = cos2.new_empty(1, dtype = torch.int32)
+ args = (Q, K, Wq.contiguous(), Wk.contiguous(), cos2, sin2, rope_indices, float(_eps(q_norm)), float(_eps(k_norm)), has_indices) # fmt: skip
+ if not torch.compiler.is_compiling():
+ Qo, Ko = Fast_QK_Norm_RoPE.apply(*args)
+ _sync_if_split(Q)
+ elif not _TRACEABLE or (Q.dtype == torch.bfloat16 and not _BF16_TRACEABLE):
+ Qo, Ko = _fused_untraced(*args)
+ else:
+ Qo, Ko, _, _ = torch.ops.unsloth.qk_norm_rope(*args)
+ return Qo.transpose(1, 2), Ko.transpose(1, 2)
diff --git a/unsloth/models/qwen3.py b/unsloth/models/qwen3.py
index 7bcb519b1d1..55f3e70c408 100644
--- a/unsloth/models/qwen3.py
+++ b/unsloth/models/qwen3.py
@@ -15,6 +15,8 @@ import os
from ._utils import __version__
from unsloth_zoo.utils import Version, _get_dtype
from ..utils.packing import get_packed_info_from_kwargs
+from ..kernels import qk_norm_rope as _qk_norm_rope
+from ..kernels.qk_norm_rope import fast_qk_norm_rope
from ..utils.attention_dispatch import (
AttentionConfig,
AttentionContext,
@@ -101,15 +103,7 @@ def Qwen3Attention_fast_forward(
V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)
seq_info = get_packed_info_from_kwargs(kwargs, hidden_states.device)
- # Qwen3 adds QKNorm, the only difference from Qwen2. A compiled norm mismatches Transformers'
- # numbers, so use fast_rms_layernorm.
- Q = fast_rms_layernorm(self.q_norm, Q)
- K = fast_rms_layernorm(self.k_norm, K)
-
- Q = Q.transpose(1, 2)
- K = K.transpose(1, 2)
-
- kv_seq_len = K.shape[-2]
+ kv_seq_len = q_len
if past_key_value is not None:
kv_seq_len += past_key_value[0].shape[-2]
@@ -122,7 +116,16 @@ def Qwen3Attention_fast_forward(
cos, sin = rotary_emb.get_cached(kv_seq_len, Q.device.index)
rope_position_ids = position_ids if position_ids is not None else kwargs.get("position_ids")
- Q, K = fast_rope_embedding(Q, K, cos, sin, rope_position_ids)
+ if _qk_norm_rope.QK_NORM_ROPE_ENABLED:
+ Q, K = fast_qk_norm_rope(self.q_norm, self.k_norm, Q, K, cos, sin, rope_position_ids)
+ else:
+ # Qwen3 adds QKNorm, the only difference from Qwen2. A compiled norm mismatches Transformers'
+ # numbers, so use fast_rms_layernorm.
+ Q = fast_rms_layernorm(self.q_norm, Q)
+ K = fast_rms_layernorm(self.k_norm, K)
+ Q = Q.transpose(1, 2)
+ K = K.transpose(1, 2)
+ Q, K = fast_rope_embedding(Q, K, cos, sin, rope_position_ids)
if past_key_value is not None:
K = torch.cat([past_key_value[0], K], dim = 2)