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 QKNorm + RoPE: keep type promotion for mixed dtype tables, reuse grad in the trainable norm fallback (#14200)

Daniel Han1fe718b4636f
diff --git a/tests/test_qk_norm_rope.py b/tests/test_qk_norm_rope.py
index 2e78e63199e..629cff3b5cb 100644
--- a/tests/test_qk_norm_rope.py
+++ b/tests/test_qk_norm_rope.py
@@ -185,3 +185,47 @@ def test_compiled_no_graph_breaks_same_bytes(dtype, packed):
for x, y in zip(eager, compiled):
assert torch.equal(x, y)
torch._dynamo.reset()
+
+
[email protected]("dtype", [torch.float32, torch.float16])
[email protected]("packed", [False, True])
+def test_mixed_dtype_tables_match_unfused(dtype, packed):
+ # bf16 cos / sin with fp32 or fp16 activations: the indexed RoPE kernel the fused path replaces
+ # multiplies with type promotion, so the fused output must not be rounded to the table dtype.
+ case = list(_case(2, 66, 8, 2, 128, dtype, packed))
+ case[2], case[3] = case[2].to(torch.bfloat16), case[3].to(torch.bfloat16)
+ fused = _run(fast_qk_norm_rope, *case, 128)
+ main = _run(_unfused, *case, 128)
+ ref = _ref64(*case, 128)
+ 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_trainable_norm_fallback_reuses_grad_buffer():
+ # The trainable-norm fallback must keep the flag-off path's reuse_grad, so its backward peak
+ # matches the flag-off fast_rms_layernorm + fast_rope_embedding sequence.
+ from unsloth.kernels import fast_rms_layernorm, fast_rope_embedding
+
+ def flag_off(q_norm, k_norm, Q, K, cos, sin, pos):
+ Q = fast_rms_layernorm(q_norm, Q, reuse_grad = True).transpose(1, 2)
+ K = fast_rms_layernorm(k_norm, K, reuse_grad = True).transpose(1, 2)
+ return fast_rope_embedding(Q, K, cos, sin, pos)
+
+ case = _case(1, 1024, 16, 4, 128, CDTYPE, True, trainable = True)
+ peaks = []
+ outs = []
+ for fn in (flag_off, fast_qk_norm_rope, flag_off):
+ for n in case[-1]:
+ n.weight.grad = None
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ start = torch.cuda.memory_allocated()
+ outs.append(_run(fn, *case, 128) + tuple(n.weight.grad.clone() for n in case[-1]))
+ torch.cuda.synchronize()
+ peaks.append(torch.cuda.max_memory_allocated() - start)
+ assert peaks[0] == peaks[2]
+ assert peaks[1] <= peaks[0], peaks
+ for x, y in zip(outs[0], outs[1]):
+ assert torch.equal(x, y)
diff --git a/unsloth/kernels/qk_norm_rope.py b/unsloth/kernels/qk_norm_rope.py
index 16c6f17c2be..e481f119e2f 100644
--- a/unsloth/kernels/qk_norm_rope.py
+++ b/unsloth/kernels/qk_norm_rope.py
@@ -44,6 +44,7 @@ def _norm_rope_fwd_block(
cols,
eps,
HEAD_DIM: tl.constexpr,
+ HAS_ROPE_INDICES: tl.constexpr,
):
HALF = HEAD_DIM // 2
hmask = heads < n_heads
@@ -57,9 +58,14 @@ def _norm_rope_fwd_block(
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)
+ # in Y's dtype. The rotation matches the RoPE kernel it replaces: the indexed one multiplies the
+ # norm output by cos / sin with type promotion (fp32 activations stay fp32 for bf16 tables), the
+ # plain one casts to cos's dtype first. A no-op when the dtypes already match.
+ y0 = ((x0 * inv[:, None]).to(w0.dtype) * w0[None, :]).to(Y.dtype.element_ty)
+ y1 = ((x1 * inv[:, None]).to(w1.dtype) * w1[None, :]).to(Y.dtype.element_ty)
+ if not HAS_ROPE_INDICES:
+ y0 = y0.to(cos1.dtype)
+ y1 = y1.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)
@@ -107,13 +113,13 @@ def _qk_norm_rope_forward(
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,
+ cos1, sin1, cols, eps_Q, HEAD_DIM, HAS_ROPE_INDICES,
) # 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,
+ cos1, sin1, cols, eps_K, HEAD_DIM, HAS_ROPE_INDICES,
) # fmt: skip
@@ -383,8 +389,9 @@ def _eps(norm):
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)
+ # reuse_grad as in the flag-off Qwen3 path: the norm output only feeds the RoPE kernel.
+ Q = fast_rms_layernorm(q_norm, Q, reuse_grad = True).transpose(1, 2)
+ K = fast_rms_layernorm(k_norm, K, reuse_grad = True).transpose(1, 2)
return fast_rope_embedding(Q, K, cos, sin, position_ids)