Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix(mtp): mask a multi-token update of a wrapped batch window by its …
…real length

BatchRotatingKVCache.make_mask (mlx-lm and mlx-vlm) trims the left padding
by _idx - max_size + 1 for a multi-token update. After the window wraps in
place, _idx is the ring cursor, but the update first puts the ring in
temporal order (_idx becomes the window length) and then drops that many
oldest columns. The stock mask keeps the old padding count, so a left-padded
row loses its oldest valid key in every batched verify forward after its
sliding window wraps (batched speculative verify over sliding-window
layers, such as the Gemma 4 caches cache_rollback already undo-logs).

The patch runs the stock mask with _idx set to the buffer length for that
case. CPU regression test: a left-padded row of a wrapped batch window
attends like the same row alone (fails before the fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
avifenesh and claude committed Nov 13, 2026
commit 011d82d1722ef3935dc398ab6bc8357680ba644c
33 changes: 33 additions & 0 deletions omlx/patches/mlx_lm_mtp/cache_rollback.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,37 @@ def trim(self, n):
cls._omlx_mtp_undo_attached = True


def _fix_batch_rotating_mask(cls) -> None:
"""Mask a multi-token update of a wrapped batch window by its real length.

``make_mask`` trims the left padding by ``_idx - max_size + 1`` for a
multi-token update. After the window wraps, ``_idx`` is the ring cursor,
but the update first puts the ring in temporal order (``_idx`` becomes
the window length) and then drops that many oldest columns. The stock
mask therefore keeps the old padding count, and a left-padded row loses
its oldest valid key in every verify forward after its window wraps.
"""
if getattr(cls, "_omlx_wrapped_mask_fixed", False):
return
original = cls.make_mask

def make_mask(self, N, window_size=None, return_array=False):
keys = getattr(self, "keys", None)
if N > 1 and self.rotated and keys is not None and self._idx < keys.shape[2]:
cursor = self._idx
self._idx = keys.shape[2]
try:
return original(
self, N, window_size=window_size, return_array=return_array
)
finally:
self._idx = cursor
return original(self, N, window_size=window_size, return_array=return_array)

cls.make_mask = make_mask
cls._omlx_wrapped_mask_fixed = True


def _attach_rotating_undo() -> bool:
try:
from mlx_lm.models.cache import BatchRotatingKVCache, RotatingKVCache
Expand All @@ -186,6 +217,7 @@ def _attach_rotating_undo() -> bool:
BatchRotatingKVCache,
("keys", "values", "offset", "_offset", "_idx", "rotated", "left_padding"),
)
_fix_batch_rotating_mask(BatchRotatingKVCache)
if vlm_cache is None:
return True
# mlx-vlm's own rotating caches (Gemma 4 sliding layers) share the
Expand All @@ -195,6 +227,7 @@ def _attach_rotating_undo() -> bool:
vlm_cache.BatchRotatingKVCache,
("keys", "values", "offset", "_offset", "_idx", "rotated", "left_padding"),
)
_fix_batch_rotating_mask(vlm_cache.BatchRotatingKVCache)
return True


Expand Down
55 changes: 55 additions & 0 deletions tests/test_mlx_lm_mtp_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -2735,6 +2735,61 @@ def test_vlm_batch_rotating_kv_cache_undo(self, num_drafts):
lambda: vlm_cache.BatchRotatingKVCache(8, [0]), num_drafts=num_drafts
)

@pytest.mark.parametrize("package", ["mlx_lm", "mlx_vlm"])
def test_wrapped_batch_window_masks_multi_token_update_like_one_row(self, package):
"""After a left-padded row's sliding window wraps in place, a
verify-sized update attends to the same keys as that row's own cache
(the stock mask dropped the row's oldest valid key)."""
import importlib

import mlx.core as mx

from omlx.patches.mlx_lm_mtp import cache_rollback

cache_mod = pytest.importorskip(f"{package}.models.cache")
create_attention_mask = importlib.import_module(
f"{package}.models.base"
).create_attention_mask

def kv(rows, length, seed):
mx.random.seed(seed)
shape = (rows, 2, length, 16)
return (
mx.random.normal(shape).astype(mx.float16),
mx.random.normal(shape).astype(mx.float16),
)

def attend(cache, queries, keys, values):
mask = create_attention_mask(queries.transpose(0, 2, 1, 3), cache)
k, v = cache.update_and_fetch(keys, values)
return mx.fast.scaled_dot_product_attention(
queries, k, v, scale=0.25, mask=mask
)

cache_rollback.apply()
singles, references = [], []
for row, length in enumerate([3, 9]):
keys, values = kv(1, length, seed=row)
for target in (singles, references):
cache = cache_mod.RotatingKVCache(max_size=6, keep=0)
cache.update_and_fetch(keys, values)
target.append(cache)
batch = cache_mod.RotatingKVCache.merge(singles)

# Two one-token steps wrap the window in place; then a 3-token update.
for step, length in enumerate([1, 1, 3]):
queries = mx.random.normal((2, 2, length, 16))
keys, values = kv(2, length, seed=30 + step)
out = attend(batch, queries, keys, values)
for i, ref in enumerate(references):
expected = attend(
ref, queries[i : i + 1], keys[i : i + 1], values[i : i + 1]
)
assert mx.allclose(
out[i : i + 1], expected, atol=2e-3, rtol=2e-3
).item(), (step, i)
assert batch.rotated is False

def test_unarmed_update_keeps_stock_semantics(self):
import mlx.core as mx

Expand Down
Loading