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.

RoPE: no recompile per sequence length when a compiled backward hands over a seq-major gradient (#17212)

Daniel Han56a96ad8845c
diff --git a/tests/test_rope_constexpr_recompiles.py b/tests/test_rope_constexpr_recompiles.py
index 10e52f0d421..a38d6d8f19e 100644
--- a/tests/test_rope_constexpr_recompiles.py
+++ b/tests/test_rope_constexpr_recompiles.py
@@ -60,3 +60,33 @@ def test_compiled_rope_keeps_one_graph_across_batch_and_seq(with_indices):
rope(Q, K, idx).backward()
torch.testing.assert_close(grad, qkv.grad, rtol = 1e-3, atol = 1e-3)
assert counters["stats"]["unique_graphs"] == 1
+
+
+def test_compiled_rope_seq_major_grad_keeps_one_graph():
+ # dK as [b, h, d, s] (fp16 LoRA compiled block) must not specialize seq_len.
+ if not RE._TRACEABLE:
+ pytest.skip(reason = "RoPE ops are not traceable on this torch / Triton")
+ from torch._dynamo.utils import counters
+
+ freqs = torch.outer(
+ torch.arange(4096.0, device = "cuda"), torch.rand(HEAD_DIM // 2, device = "cuda")
+ )
+ emb = torch.cat((freqs, freqs), -1)
+ cos, sin = emb.cos().half(), emb.sin().half()
+
+ def rope(Q, K):
+ q, k = RE.fast_rope_embedding(Q, K, cos, sin, None)
+ return q.float().square().sum() + k.transpose(2, 3).contiguous().float().square().sum()
+
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(rope, dynamic = True, fullgraph = True)
+ for batch, seq in [(3, 37), (5, 96), (6, 129), (7, 13), (3, 300)]:
+ qkv, Q, K = _qk(batch, seq)
+ compiled(Q, K).backward()
+ grad = qkv.grad
+ qkv, Q, K = _qk(batch, seq)
+ rope(Q, K).backward()
+ torch.testing.assert_close(grad, qkv.grad, rtol = 1e-2, atol = 1e-2)
+ assert counters["stats"]["unique_graphs"] == 1
diff --git a/tests/test_rope_symbolic_layout_strides.py b/tests/test_rope_symbolic_layout_strides.py
new file mode 100644
index 00000000000..dbe16ce7dee
--- /dev/null
+++ b/tests/test_rope_symbolic_layout_strides.py
@@ -0,0 +1,116 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A traced RoPE launch never passes a seq_len-dependent stride (dK as [b, h, d, s]) as a constexpr.
+
+CPU only: fake tensors with a symbolic seq dim and a recording launcher."""
+
+import pytest
+import torch
+
+pytest.importorskip("triton")
+
+from torch._subclasses.fake_tensor import FakeTensorMode # noqa: E402
+from torch.fx.experimental.symbolic_shapes import ( # noqa: E402
+ DimDynamic,
+ ShapeEnv,
+ StatelessSymbolicContext,
+ is_concrete_int,
+)
+
+from unsloth.kernels import rope_embedding as RE # noqa: E402
+
+B, H, S, D = 2, 4, 13, 16
+
+
+class _Recorder:
+ def __init__(self):
+ self.launches = []
+
+ def __call__(self, kernel):
+ def grid(_grid):
+ def launch(*args, **kwargs):
+ self.launches.append((kernel, args, kwargs))
+
+ return launch
+
+ return type("_Grid", (), {"__getitem__": lambda _self, g: grid(g)})()
+
+
+def _bound(kernel, args, kwargs):
+ names = [p.name for p in kernel.params]
+ values = dict(zip(names, args))
+ values.update(kwargs)
+ return {p.name: values[p.name] for p in kernel.params if p.is_constexpr}
+
+
+def _fake_seq_dynamic(mode, t, seq_dim):
+ sizes = [DimDynamic.STATIC] * t.dim()
+ sizes[seq_dim] = DimDynamic.DYNAMIC
+ return mode.from_tensor(t, symbolic_context = StatelessSymbolicContext(dynamic_sizes = sizes))
+
+
+def _launch(layout_of_k, backward):
+ mode = FakeTensorMode(shape_env = ShapeEnv())
+ Q = _fake_seq_dynamic(mode, torch.empty(B, S, H, D), 1).transpose(1, 2)
+ if layout_of_k == "bhds":
+ # [b, h, d, s] storage seen as [b, h, s, d]: dim stride = seq_len.
+ K = _fake_seq_dynamic(mode, torch.empty(B, H, D, S), 3).transpose(2, 3)
+ else:
+ K = _fake_seq_dynamic(mode, torch.empty(B, S, H, D), 1).transpose(1, 2)
+ with mode:
+ Q_out = torch.empty(Q.transpose(1, 2).shape).transpose(1, 2)
+ K_out = torch.empty(K.transpose(1, 2).shape).transpose(1, 2)
+ cos = torch.empty(64, D)
+ rec = _Recorder()
+ RE._rope_launch(Q, Q_out, K, K_out, cos, cos, None, False, backward, False, rec)
+ assert len(rec.launches) == 1
+ return rec.launches[0], K
+
+
[email protected](autouse = True)
+def _no_device_queries(monkeypatch):
+ monkeypatch.setattr(RE, "_rope_num_warps", lambda device: 4)
+
+
[email protected]("backward", [False, True])
+def test_seq_major_dK_never_reaches_a_constexpr(backward):
+ (kernel, args, kwargs), K = _launch("bhds", backward)
+ assert not is_concrete_int(K.stride(3)), "the setup must give K a symbolic dim stride"
+ symbolic = {
+ name: value
+ for name, value in _bound(kernel, args, kwargs).items()
+ if isinstance(value, torch.SymInt) and not is_concrete_int(value)
+ }
+ assert not symbolic, f"{kernel.fn.__name__}: symbolic constexpr args {symbolic}"
+ assert kernel is RE._rope_embedding_QK_strided
+
+
[email protected]("backward", [False, True])
+def test_projection_layouts_keep_the_constexpr_kernel(backward):
+ (kernel, args, kwargs), _ = _launch("bshd", backward)
+ assert kernel is RE._rope_embedding_QK
+ constexprs = _bound(kernel, args, kwargs)
+ for name in RE._LAYOUT_STRIDES:
+ assert type(constexprs[name]) is int, (name, constexprs[name])
+
+
+def test_strided_kernel_has_runtime_layout_strides():
+ fixed = {p.name: p.is_constexpr for p in RE._rope_embedding_QK.params}
+ strided = {p.name: p.is_constexpr for p in RE._rope_embedding_QK_strided.params}
+ assert fixed.keys() == strided.keys()
+ for name in fixed:
+ if name in RE._LAYOUT_STRIDES:
+ assert fixed[name] and not strided[name], name
+ assert name in RE._rope_embedding_QK_strided.do_not_specialize
+ else:
+ assert fixed[name] == strided[name], name
+
+
+def test_eager_seq_major_layout_takes_the_strided_kernel():
+ X = torch.empty(B, H, D, S).transpose(2, 3)
+ assert not RE._fixed_layout(X)
+ assert RE._fixed_layout(torch.empty(B, S, H, D).transpose(1, 2))
+ assert RE._fixed_layout(torch.empty(B, H, S, D))
+ assert RE._fixed_layout(torch.empty(1, 1, 1, 1))
+ assert RE._fixed_layout(torch.empty(1, 1, 1, D).expand(B, H, S, D))
diff --git a/unsloth/kernels/rope_embedding.py b/unsloth/kernels/rope_embedding.py
index 83418fbed1a..0994aae3856 100644
--- a/unsloth/kernels/rope_embedding.py
+++ b/unsloth/kernels/rope_embedding.py
@@ -18,6 +18,7 @@ import triton.language as tl
import torch
from ..device_type import DEVICE_COUNT, DEVICE_TYPE_TORCH
from typing import Tuple
+from torch.fx.experimental.symbolic_shapes import is_concrete_int as _is_concrete_int
from .utils import long_indexing, next_power_of_2, torch_gpu_device, torch_device_stream
from .rms_layernorm import (
_BF16_TRACEABLE,
@@ -93,27 +94,28 @@ def _rope_heads_tile(
tl.store(out_ptr + half_head_dim * out_dim_stride, out1, mask = mask)
-def _rope_embedding_QK(
+def _rope_qk_program(
Q,
Q_out,
K,
K_out,
q_batch_stride,
- q_seq_stride: tl.constexpr, # 4096 n_heads * head_dim (6144 fused QKV, 128 contiguous)
+ q_seq_stride,
q_head_stride,
- q_dim_stride: tl.constexpr, # 1
+ q_dim_stride,
qo_batch_stride,
- qo_seq_stride: tl.constexpr, # 4096 or 128
+ qo_seq_stride,
qo_head_stride,
- qo_dim_stride: tl.constexpr, # 1
+ qo_dim_stride,
k_batch_stride,
- k_seq_stride: tl.constexpr, # 1024 n_kv_heads * head_dim
+ k_seq_stride,
k_head_stride,
- k_dim_stride: tl.constexpr, # 1
+ k_dim_stride,
ko_batch_stride,
- ko_seq_stride: tl.constexpr, # 1024 or 128
+ ko_seq_stride,
ko_head_stride,
- ko_dim_stride: tl.constexpr, # 1
+ ko_dim_stride,
cos,
cos_row_stride, # runtime: a SymInt in compiled graphs
sin,
@@ -222,9 +224,190 @@ def _rope_embedding_QK(
)
+def _rope_embedding_QK(
+ Q,
+ Q_out,
+ K,
+ K_out,
+ q_batch_stride,
+ q_seq_stride: tl.constexpr,
+ q_head_stride,
+ q_dim_stride: tl.constexpr,
+ qo_batch_stride,
+ qo_seq_stride: tl.constexpr,
+ qo_head_stride,
+ qo_dim_stride: tl.constexpr,
+ k_batch_stride,
+ k_seq_stride: tl.constexpr,
+ k_head_stride,
+ k_dim_stride: tl.constexpr,
+ ko_batch_stride,
+ ko_seq_stride: tl.constexpr,
+ ko_head_stride,
+ ko_dim_stride: tl.constexpr,
+ 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,
+):
+ """Layout strides as constexprs (fixed per model)."""
+ _rope_qk_program(
+ Q,
+ Q_out,
+ K,
+ K_out,
+ q_batch_stride,
+ q_seq_stride,
+ q_head_stride,
+ q_dim_stride,
+ qo_batch_stride,
+ qo_seq_stride,
+ qo_head_stride,
+ qo_dim_stride,
+ k_batch_stride,
+ k_seq_stride,
+ k_head_stride,
+ k_dim_stride,
+ ko_batch_stride,
+ ko_seq_stride,
+ ko_head_stride,
+ ko_dim_stride,
+ cos,
+ cos_row_stride,
+ sin,
+ sin_row_stride,
+ rope_embedding_indices,
+ seqlen,
+ n_heads_Q,
+ n_heads_K,
+ n_groups_Q,
+ half_head_dim,
+ BACKWARD_PASS,
+ HAS_ROPE_INDICES,
+ LONG_INDEXING,
+ CAST_TO_SIN,
+ HEADS_Q,
+ HEADS_K,
+ BLOCK_SIZE,
+ EVICT_INDICES,
+ )
+
+
+def _rope_embedding_QK_strided(
+ Q,
+ Q_out,
+ K,
+ K_out,
+ q_batch_stride,
+ q_seq_stride,
+ q_head_stride,
+ q_dim_stride,
+ qo_batch_stride,
+ qo_seq_stride,
+ qo_head_stride,
+ qo_dim_stride,
+ k_batch_stride,
+ k_seq_stride,
+ k_head_stride,
+ k_dim_stride,
+ ko_batch_stride,
+ ko_seq_stride,
+ ko_head_stride,
+ ko_dim_stride,
+ 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,
+):
+ """Runtime layout strides, for strides that depend on seq_len (dK as [b, h, d, s])."""
+ _rope_qk_program(
+ Q,
+ Q_out,
+ K,
+ K_out,
+ q_batch_stride,
+ q_seq_stride,
+ q_head_stride,
+ q_dim_stride,
+ qo_batch_stride,
+ qo_seq_stride,
+ qo_head_stride,
+ qo_dim_stride,
+ k_batch_stride,
+ k_seq_stride,
+ k_head_stride,
+ k_dim_stride,
+ ko_batch_stride,
+ ko_seq_stride,
+ ko_head_stride,
+ ko_dim_stride,
+ cos,
+ cos_row_stride,
+ sin,
+ sin_row_stride,
+ rope_embedding_indices,
+ seqlen,
+ n_heads_Q,
+ n_heads_K,
+ n_groups_Q,
+ half_head_dim,
+ BACKWARD_PASS,
+ HAS_ROPE_INDICES,
+ LONG_INDEXING,
+ CAST_TO_SIN,
+ HEADS_Q,
+ HEADS_K,
+ BLOCK_SIZE,
+ EVICT_INDICES,
+ )
+
+
+_LAYOUT_STRIDES = (
+ "q_seq_stride",
+ "q_dim_stride",
+ "qo_seq_stride",
+ "qo_dim_stride",
+ "k_seq_stride",
+ "k_dim_stride",
+ "ko_seq_stride",
+ "ko_dim_stride",
+)
+
+
# 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, do_not_specialize = ("seqlen",))
+_rope_embedding_QK_strided = triton.jit(
+ _rope_embedding_QK_strided, do_not_specialize = ("seqlen",) + _LAYOUT_STRIDES
+)
# 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.
@@ -255,6 +438,19 @@ def _heads_per_program(n_heads, block_size):
return max(1, min(next_power_of_2(n_heads), ROPE_TILE_ELEMENTS // block_size))
+def _fixed_layout(X):
+ # Seq-dependent strides as constexprs recompile per length (a guard traced, a binary eager).
+ _, _, seq_stride, dim_stride = X.stride()
+ # Plain ints (eager) skip the symbolic check: hot on every decode step.
+ if type(seq_stride) is not int or type(dim_stride) is not int:
+ if not (_is_concrete_int(seq_stride) and _is_concrete_int(dim_stride)):
+ return False
+ # Dense, the dim stride grows with seq_len only when the seq dim is the inner one.
+ if dim_stride <= seq_stride or seq_stride == 0:
+ return True
+ return X.shape[2] <= 1 or X.shape[3] <= 1
+
+
def _rope_launch(Q, Q_out, K, K_out, cos, sin, rope_ptr, has_indices, backward, cast_to_sin, wrap):
# Q, K, Q_out, K_out: [batch, n_heads, seq_len, head_dim] at any strides (K may be None).
# Q_out may be Q itself (in place).
@@ -275,7 +471,15 @@ def _rope_launch(Q, Q_out, K, K_out, cos, sin, rope_ptr, has_indices, backward,
if rope_ptr is None:
rope_ptr = cos # never read without HAS_ROPE_INDICES
tensors = (Q, Q_out, K, K_out, cos, sin)
- wrap(_rope_embedding_QK)[(batch * seq_len, n_groups_Q + n_groups_K)](
+ kernel = (
+ _rope_embedding_QK
+ if _fixed_layout(Q)
+ and _fixed_layout(K)
+ and (Q_out is Q or _fixed_layout(Q_out))
+ and (K_out is K or _fixed_layout(K_out))
+ else _rope_embedding_QK_strided
+ )
+ wrap(kernel)[(batch * seq_len, n_groups_Q + n_groups_K)](
Q,
Q_out,
K,