`mx.fast.rope` returns wrong values for batch rows > 0 when seq_len == 1 and batch > 1
Note on provenance. This was surfaced by Claude (Anthropic's Fable model) while working with me on an experimental entropy-sampler repo, and the subject matter is honestly out of my personal depth. I've verified it as far as I'm able with agent assistance before filing: the repro below is model-free, seeded, and runs in seconds; I've reproduced it across head dims 64/128/256 and both rope conventions, confirmed the downstream effect on two unrelated model families (including an unquantized bf16 model, ruling out quantization), and traced it to a specific line in
rope.cpp(see Root cause). Please correct anything I've mischaracterized.
Repo: ml-explore/mlx
Summary
mx.fast.rope on a contiguous 4D input of shape [B, H, 1, D] with
B > 1 returns corrupted values for every batch row after the first.
Row 0 is exact; rows ≥ 1 are wrong, and not by a position shift — no
single offset reproduces them, so the kernel appears to be mis-indexing
data across rows. [B, H, 1, D] is the standard batched single-token
decode shape, so any batched decode whose rope input materializes
contiguous is affected (see impact below).
Verified properties:
- Fires only at seq_len == 1 with batch > 1; seq_len ≥ 2 is exact for every batch size tested.
- Row 0 is always exact; rows ≥ 1 are corrupted.
- At
offset=0the correct output is provably the input (position 0 ⇒ rotation angle 0 ⇒ identity), yet corrupted rows come back as zeros — a value the identity map cannot produce. This removes any "expected numerics" reading: the kernel is not miscomputing a rotation, it is emitting data that isn't a rotation of the input at all. - Some shapes read uninitialized memory, not merely wrong values:
e.g. contiguous
[4, 8, 1, 128]bf16 has produced ~3.5e37in a corrupted row, and the set of affected(B, H)combinations is not stable — the signature of out-of-bounds / uninitialized reads. - Dtype-independent: bf16, fp16, and fp32 all affected (fp32 worst row deviation 6.08 below), so this is an indexing bug, not precision.
- The result depends on input strides: a transposed view holding the same values produces the correct result; the contiguous copy is the wrong one.
- Reproduces identically through
nn.RoPE(which callsmx.fast.rope).
Environment
- mlx 0.31.2 (via pip; mlx-metal 0.31.2)
- macOS 26.5.1, Apple M4 Max, 128 GB
- Python 3.12
Repro
import mlx.core as mx
mx.random.seed(0)
def rope(x, offset=32):
return mx.fast.rope(x, 256, traditional=False, base=10000.0,
scale=1.0, offset=offset)
# 1) Wrong values, only at T==1 with B>1 (contiguous input)
print("worst batch-row deviation vs the same row processed alone:")
for B in (2, 8):
for T in (1, 2, 8):
x = mx.contiguous(mx.random.normal((1, 16, B, T, 256))
.astype(mx.bfloat16)[0].transpose(1, 0, 2, 3))
out = rope(x) # x: contiguous [B, 16, T, 256]
worst = max(mx.abs(out[i:i+1] - rope(mx.contiguous(x[i:i+1])))
.max().item() for i in range(B))
print(f" B={B} T={T}: {worst:.4f}")
# 2) Row 0 is correct; rows >= 1 are corrupted, and not by a position
# shift -- no single offset reproduces them
x = mx.contiguous(mx.random.normal((8, 16, 1, 256)).astype(mx.bfloat16))
out = rope(x)
for i in (0, 1, 4):
best = min((mx.abs(out[i:i+1] - rope(mx.contiguous(x[i:i+1]), off))
.max().item(), off) for off in range(24, 48))
print(f"row {i}: best-fit offset {best[1]} (requested 32), dev {best[0]:.4f}")
# 3) Result depends on strides: a transposed VIEW of the same values is
# CORRECT, the contiguous copy is wrong
xv = mx.random.normal((1, 16, 8, 256)).astype(mx.bfloat16).transpose(2, 1, 0, 3)
a, b = rope(xv), rope(mx.contiguous(xv))
ref = mx.concatenate([rope(mx.contiguous(xv[i:i+1])) for i in range(8)])
print("view vs per-row reference: ", mx.abs(a - ref).max().item())
print("contiguous vs per-row reference:", mx.abs(b - ref).max().item())
# 4) dtype-independent (also fp32)
x32 = mx.contiguous(mx.random.normal((8, 16, 1, 256)))
out32 = rope(x32)
worst = max(mx.abs(out32[i:i+1] - rope(mx.contiguous(x32[i:i+1])))
.max().item() for i in range(8))
print("fp32 worst row dev:", round(worst, 4))
# 5) offset=0 is the identity (angle 0), so out MUST equal the input.
# Row 0 does; row 1 comes back as zeros -- not a rotation of anything.
x0 = mx.array([[[[1., 2., 3., 4.]]], [[[5., 6., 7., 8.]]]]) # [2,1,1,4]
o0 = mx.fast.rope(x0, 4, traditional=False, base=10000.0, scale=1.0, offset=0)
print("offset=0 row0 (want [1,2,3,4]):", o0[0].tolist())
print("offset=0 row1 (want [5,6,7,8]):", o0[1].tolist())
Observed output (mlx 0.31.2, M4 Max)
worst batch-row deviation vs the same row processed alone:
B=2 T=1: 4.2188
B=2 T=2: 0.0000
B=2 T=8: 0.0000
B=8 T=1: 4.2812
B=8 T=2: 0.0000
B=8 T=8: 0.0000
row 0: best-fit offset 32 (requested 32), dev 0.0000
row 1: best-fit offset 39 (requested 32), dev 3.2656
row 4: best-fit offset 30 (requested 32), dev 3.6094
view vs per-row reference: 0.0
contiguous vs per-row reference: 6.875
fp32 worst row dev: 6.0794
offset=0 row0 (want [1,2,3,4]): [[[1.0, 2.0, 3.0, 4.0]]]
offset=0 row1 (want [5,6,7,8]): [[[0.0, 0.0, 0.0, 0.0]]]
Root cause (host-side dispatch in rope.cpp)
The bug is in kernel dispatch, not the shader math. The single-time-step fast-path is selected by:
// mlx/backend/metal/rope.cpp
bool single = in.flags().row_contiguous && T == 1 && offset.size() == 1;
When single is true it launches rope_single with grid:
grid_dims = MTL::Size(dims_ / 2, N, 1); // (D/2, n_heads, 1)
N here is the product of the middle dims (n_heads); the batch
dimension B is not in the grid at all. rope_single therefore only
addresses the first batch matrix, and rows ≥ 1 of the freshly
malloc-ed output are never written — they contain uninitialized
memory (hence zeros / 3.5e37 above). This path predates batched
decode and assumes "single time step" ⇒ batch 1.
Consistent with this: anything that avoids the single predicate is
correct. A non-contiguous view (fails row_contiguous) and a per-row
offset array of length B (makes offset.size() != 1) both fall
through to the general rope kernel, whose grid includes batch
(dim2 = B * ceil(N/4)), and both return exact results:
scalar offset (single path) worst dev: 4.0625
array offset (general path) worst dev: 0.0
Suggested fix: require batch 1 for the fast-path, e.g.
single = in.flags().row_contiguous && T == 1 && B == 1 && offset.size() == 1;
so batched decode uses the general kernel (which is already correct).
Expected
All batch rows equal to the same row processed alone, independent of input strides and of the other rows in the batch.
Impact
[B, H, 1, D] is exactly the shape attention layers feed to rope
during batched single-token decode, so this is architecture-
independent: the repro above reproduces across head dims 64/128/256 and
both traditional conventions. In mlx-lm (0.31.3), batch>1 decode
shows the matching signature — row 0 exact, rows ≥ 1 corrupted — on
multiple model families: Gemma-4 (logits off by up to ~27, top-1 flips
on 7 of 8 rows; word salad on a quantized MoE) and Qwen3-4B in
unquantized bf16 (rows 1–7 off by 6–15, ruling out quantization as
the cause). Filed separately against mlx-lm with repros; the two issues
are very likely the same root cause.
The failure is silent — no error, plausible-looking output — which is what makes it dangerous: downstream it looks like "quantization artifacts" or "sampler weirdness" rather than a kernel bug.
The mlx-lm-level symptom (batched decode logit corruption, reproduced on Gemma-4 and unquantized bf16 Qwen3) is filed at ml-explore/mlx-lm#1457.
Apologies — this duplicates #3494, which was fixed by #3498 (merged 2026-05-11, with a regression test). I reproduced it on 0.31.2, which predates that fix; it's resolved on main. Closing as a duplicate. Thanks for the already-landed fix.