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.

Fix int32 offset overflow past 2^31 elements in RoPE and norm kernels (#13121)

Srijan Keshri850bd28a390d
diff --git a/tests/test_rope_zero_stride_grad.py b/tests/test_rope_zero_stride_grad.py
index 41164cbc392..54ce63757db 100644
--- a/tests/test_rope_zero_stride_grad.py
+++ b/tests/test_rope_zero_stride_grad.py
@@ -80,3 +80,46 @@ def test_rope_backward_preserves_shared_dense_gradient(implementation):
grad_before = grad.clone()
(q + k).backward(grad)
assert torch.equal(grad, grad_before)
+
+
[email protected]("implementation", ["single", "indexed_qk"])
+def test_rope_rows_past_2_pow_31_elements(implementation):
+ from unsloth.kernels.rope_embedding import Fast_RoPE_Embedding, Fast_RoPE_Embedding_QK
+
+ b, h, s, d = 513, 8, 4096, 128 # b * h * s * d > 2^31
+ need = b * (h + 1) * s * d * 2 + (1 << 30)
+ torch.cuda.empty_cache()
+ if torch.cuda.mem_get_info()[0] < need:
+ pytest.skip(reason = f"needs {need / 2**30:.1f} GiB free GPU memory")
+ torch.manual_seed(0)
+ inv = 1.0 / (10000 ** (torch.arange(0, d, 2, device = "cuda").float() / d))
+ freqs = torch.outer(torch.arange(s, device = "cuda").float(), inv)
+ emb = torch.cat((freqs, freqs), -1)
+ cos, sin = emb.cos(), emb.sin()
+
+ with torch.no_grad():
+ if implementation == "single":
+ Q = torch.randn(b, s, h, d, device = "cuda", dtype = torch.float16)
+ ref = _reference(Q[-1, -4:].transpose(0, 1).float(), cos[-4:], sin[-4:], None)
+ Fast_RoPE_Embedding.apply(Q, cos, sin)
+ out = Q[-1, -4:].transpose(0, 1)
+ else:
+ Q = torch.randn(b, h, s, d, device = "cuda", dtype = torch.float16)
+ K = torch.zeros(b, 1, s, d, device = "cuda", dtype = torch.float16)
+ idx = torch.arange(s, device = "cuda", dtype = torch.int32).expand(b, s)
+ ref = _reference(Q[-1, :, -4:].float(), cos[-4:], sin[-4:], None)
+ Fast_RoPE_Embedding_QK.apply(Q, K, cos, sin, idx)
+ out = Q[-1, :, -4:]
+ torch.testing.assert_close(out, ref.half())
+
+
+def test_long_indexing_bounds_the_largest_offset():
+ from unsloth.kernels.utils import long_indexing
+
+ meta = dict(device = "meta")
+ assert not long_indexing(torch.empty(2**31, **meta))
+ assert long_indexing(torch.empty(2**31 + 1, **meta))
+ assert long_indexing(torch.empty(2**31 - 8, **meta), block = 16)
+ # 4 elements, but the last one sits 2^31 + 1 elements past the first.
+ assert long_indexing(torch.empty(2**31 + 2, **meta).as_strided((2, 2), (2**31, 1)))
+ assert not long_indexing(torch.empty(64, 128, **meta).t(), torch.empty(0, 4096, **meta))
diff --git a/unsloth/kernels/layernorm.py b/unsloth/kernels/layernorm.py
index 631b75e6ca1..2759b760579 100644
--- a/unsloth/kernels/layernorm.py
+++ b/unsloth/kernels/layernorm.py
@@ -13,7 +13,7 @@
import triton
import triton.language as tl
import torch
-from .utils import calculate_settings, torch_gpu_device
+from .utils import calculate_settings, long_indexing, torch_gpu_device
from unsloth_zoo.patching_utils import (
patch_layernorm,
)
@@ -31,9 +31,12 @@ def layernorm_forward(
mu,
n_cols: tl.constexpr,
eps: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
row_idx = tl.program_id(0)
+ if LONG_INDEXING:
+ row_idx = row_idx.to(tl.int64)
col_offsets = tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
@@ -72,10 +75,13 @@ def layernorm_backward(
mu,
n_cols: tl.constexpr,
eps: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
# Approximately follows karpathy/llm.c doc/layernorm/layernorm.md
row_idx = tl.program_id(0)
+ if LONG_INDEXING:
+ row_idx = row_idx.to(tl.int64)
col_offsets = tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
@@ -127,6 +133,7 @@ class Fast_Layernorm(torch.autograd.Function):
mu,
n_cols,
eps,
+ LONG_INDEXING = long_indexing(X, Y, block = BLOCK_SIZE),
BLOCK_SIZE = BLOCK_SIZE,
num_warps = num_warps,
)
@@ -156,6 +163,7 @@ class Fast_Layernorm(torch.autograd.Function):
mu,
n_cols,
ctx.eps,
+ LONG_INDEXING = long_indexing(dY, X, block = ctx.BLOCK_SIZE),
BLOCK_SIZE = ctx.BLOCK_SIZE,
num_warps = ctx.num_warps,
)
diff --git a/unsloth/kernels/rms_layernorm.py b/unsloth/kernels/rms_layernorm.py
index d9ea06a3cce..5497596d07f 100644
--- a/unsloth/kernels/rms_layernorm.py
+++ b/unsloth/kernels/rms_layernorm.py
@@ -16,7 +16,7 @@ import triton
import triton.language as tl
import torch
from typing import Tuple
-from .utils import calculate_settings, torch_gpu_device
+from .utils import calculate_settings, long_indexing, torch_gpu_device
@triton.jit
@@ -31,6 +31,7 @@ def _rms_layernorm_forward(
r_row_stride: tl.constexpr,
n_cols: tl.constexpr,
eps: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
"""
@@ -39,6 +40,8 @@ def _rms_layernorm_forward(
https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
"""
row_idx = tl.program_id(0)
+ if LONG_INDEXING:
+ row_idx = row_idx.to(tl.int64)
col_offsets = tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
@@ -74,6 +77,7 @@ def _rms_layernorm_backward(
n_cols: tl.constexpr,
eps: tl.constexpr,
GEMMA: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
"""
@@ -82,6 +86,8 @@ def _rms_layernorm_backward(
https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
"""
row_idx = tl.program_id(0)
+ if LONG_INDEXING:
+ row_idx = row_idx.to(tl.int64)
col_offsets = tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
@@ -116,6 +122,7 @@ _rms_layernorm_backward = triton.jit(_rms_layernorm_backward)
_rms_layernorm_backward = triton.heuristics(
{
"GEMMA": lambda args: bool(args["GEMMA"]),
+ "LONG_INDEXING": lambda args: bool(args["LONG_INDEXING"]),
}
)(_rms_layernorm_backward)
@@ -132,11 +139,14 @@ def _gemma_rms_layernorm_forward(
r_row_stride: tl.constexpr,
n_cols: tl.constexpr,
eps: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
# Copies google-deepmind/gemma layers.py#L31 and keras-nlp gemma/rms_normalization.py#L33 exactly:
# essentially all in float32.
row_idx = tl.program_id(0)
+ if LONG_INDEXING:
+ row_idx = row_idx.to(tl.int64)
col_offsets = tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
@@ -197,8 +207,12 @@ def _rms_layernorm_forward_rows(
BLOCK_SIZE: tl.constexpr,
ROWS: tl.constexpr,
WARPS: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
):
- rows = tl.program_id(0).to(tl.int64) * ROWS + tl.arange(0, ROWS)
+ pid = tl.program_id(0)
+ if LONG_INDEXING:
+ pid = pid.to(tl.int64)
+ rows = pid * ROWS + tl.arange(0, ROWS)
col_offsets = tl.arange(0, BLOCK_SIZE)
row_mask = rows < n_rows
col_mask = col_offsets < n_cols
@@ -242,8 +256,12 @@ def _rms_layernorm_backward_rows(
BLOCK_SIZE: tl.constexpr,
ROWS: tl.constexpr,
WARPS: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
):
- rows = tl.program_id(0).to(tl.int64) * ROWS + tl.arange(0, ROWS)
+ pid = tl.program_id(0)
+ if LONG_INDEXING:
+ pid = pid.to(tl.int64)
+ rows = pid * ROWS + tl.arange(0, ROWS)
col_offsets = tl.arange(0, BLOCK_SIZE)
row_mask = rows < n_rows
col_mask = col_offsets < n_cols
@@ -371,6 +389,10 @@ def _multirow_checked(X, W, eps, gemma):
return multirow if verdict and _MULTIROW else None
+# Covers masked lanes past the last row: a block of columns, or ROWS rows in the multirow kernels.
+_INDEX_MARGIN = 1 << 20
+
+
def _rms_forward(
X,
W,
@@ -385,6 +407,7 @@ def _rms_forward(
r = torch.empty(n_rows, dtype = torch.float32, device = X.device)
if multirow is None:
multirow = _multirow_checked(X, W, eps, gemma)
+ long = long_indexing(X, Y, block = _INDEX_MARGIN)
if multirow:
BLOCK_SIZE, ROWS, WARPS, num_warps = multirow
try:
@@ -402,6 +425,8 @@ def _rms_forward(
BLOCK_SIZE = BLOCK_SIZE,
ROWS = ROWS,
WARPS = WARPS,
+ # int32 rows measured slower only for the Gemma multi-row forward: keep main's int64.
+ LONG_INDEXING = long or gemma,
num_warps = num_warps,
)
return Y, r
@@ -422,6 +447,7 @@ def _rms_forward(
r.stride(0),
n_cols,
eps,
+ LONG_INDEXING = long,
BLOCK_SIZE = BLOCK_SIZE,
num_warps = num_warps,
)
@@ -443,6 +469,7 @@ def _rms_backward(
n_rows, n_cols = dY.shape
if multirow is None:
multirow = _multirow_checked(X, W, eps, gemma)
+ long = long_indexing(dY, dX, X, block = _INDEX_MARGIN)
if multirow:
BLOCK_SIZE, ROWS, WARPS, num_warps = multirow
try:
@@ -462,6 +489,7 @@ def _rms_backward(
BLOCK_SIZE = BLOCK_SIZE,
ROWS = ROWS,
WARPS = WARPS,
+ LONG_INDEXING = long,
num_warps = num_warps,
)
return
@@ -484,6 +512,7 @@ def _rms_backward(
n_cols,
eps,
GEMMA = gemma,
+ LONG_INDEXING = long,
BLOCK_SIZE = BLOCK_SIZE,
num_warps = num_warps,
)
diff --git a/unsloth/kernels/rope_embedding.py b/unsloth/kernels/rope_embedding.py
index 1bdb3b139fc..7a42fab70c9 100644
--- a/unsloth/kernels/rope_embedding.py
+++ b/unsloth/kernels/rope_embedding.py
@@ -15,7 +15,7 @@ import triton.language as tl
import torch
from ..device_type import DEVICE_COUNT
from typing import Tuple
-from .utils import calculate_settings, torch_gpu_device, torch_device_stream
+from .utils import calculate_settings, long_indexing, torch_gpu_device, torch_device_stream
from .rms_layernorm import (
_BF16_TRACEABLE,
_TRACEABLE,
@@ -44,6 +44,7 @@ def _rope_embedding_QK(
n_heads_K: tl.constexpr,
BACKWARD_PASS: tl.constexpr,
HAS_ROPE_INDICES: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
row_position = tl.program_id(0)
@@ -77,6 +78,11 @@ def _rope_embedding_QK(
batch_id = row_position // seqlen
seq_index = row_position - batch_id * seqlen
+ if LONG_INDEXING:
+ # Widen after the int32 div/mod: 64-bit div/mod is slow at normal sizes.
+ batch_id = batch_id.to(tl.int64)
+ seq_index = seq_index.to(tl.int64)
+ head_position = head_position.to(tl.int64)
q_ptr = Q + batch_id * Q_batch_stride + head_position * Q_head_stride + seq_index * Q_seq_stride
q0 = tl.load(q_ptr + col_offsets, mask = mask, other = 0)
@@ -99,6 +105,7 @@ _rope_embedding_QK = triton.heuristics(
{
"BACKWARD_PASS": lambda args: bool(args["BACKWARD_PASS"]),
"HAS_ROPE_INDICES": lambda args: bool(args["HAS_ROPE_INDICES"]),
+ "LONG_INDEXING": lambda args: bool(args["LONG_INDEXING"]),
}
)(_rope_embedding_QK)
@@ -117,6 +124,7 @@ def _rope_embedding(
head_dim: tl.constexpr,
n_heads: tl.constexpr,
BACKWARD_PASS: tl.constexpr,
+ LONG_INDEXING: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
"""
@@ -151,9 +159,13 @@ def _rope_embedding(
head_end = min((head_start + ROPE_GROUP_SIZE), n_heads)
# 10% faster kernel from HuyNguyen-hust, unslothai/unsloth#238.
+ if LONG_INDEXING:
+ Q += row_position.to(tl.int64) * Q_row_stride
+ else:
+ Q += row_position * Q_row_stride
for k in range(head_start, head_end):
- offs_q1 = row_position * Q_row_stride + k * head_dim + col_offsets
- offs_q2 = row_position * Q_row_stride + k * head_dim + col_offsets + half_head_dim
+ offs_q1 = k * head_dim + col_offsets
+ offs_q2 = k * head_dim + col_offsets + half_head_dim
# Gemma sometimes needs RoPE done in float32 rather than bfloat16.
Q1 = tl.load(Q + offs_q1, mask = mask, other = 0).to(sin1.dtype)
@@ -167,6 +179,7 @@ _rope_embedding = triton.jit(_rope_embedding)
_rope_embedding = triton.heuristics(
{
"BACKWARD_PASS": lambda args: bool(args["BACKWARD_PASS"]),
+ "LONG_INDEXING": lambda args: bool(args["LONG_INDEXING"]),
}
)(_rope_embedding)
@@ -193,6 +206,7 @@ def _rope_rows(Q, cos, sin, seq_len, n_heads, head_dim, backward, wrap):
head_dim,
n_heads,
BACKWARD_PASS = backward,
+ LONG_INDEXING = long_indexing(Q, block = BLOCK_SIZE),
BLOCK_SIZE = BLOCK_SIZE,
num_warps = num_warps,
)
@@ -260,6 +274,7 @@ def _rope_qk(Q, K, cos, sin, rope_ptr, has_indices, backward, wrap):
n_heads_K = n_heads_K,
BACKWARD_PASS = backward,
HAS_ROPE_INDICES = has_indices,
+ LONG_INDEXING = long_indexing(Q, K, block = BLOCK_SIZE),
BLOCK_SIZE = BLOCK_SIZE,
num_warps = num_warps,
)
diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.py
index dbf8fb29d80..fcfe4ad736d 100644
--- a/unsloth/kernels/utils.py
+++ b/unsloth/kernels/utils.py
@@ -119,6 +119,27 @@ def is_rdna():
)
+try:
+ from math import sumprod as _sumprod
+except ImportError: # Python < 3.12
+
+ def _sumprod(a, b):
+ return sum(x * y for x, y in zip(a, b))
+
+
+def long_indexing(*tensors, block = 0):
+ # numel() is not enough for strided views (transposed Q / K): their offsets reach past it.
+ for t in tensors:
+ if t.is_contiguous():
+ extent = t.numel()
+ else:
+ stride = t.stride()
+ extent = _sumprod(t.shape, stride) - sum(stride) + 1
+ if extent + block > 2**31:
+ return True
+ return False
+
+
def calculate_settings(
n: int,
) -> (