From 011d82d1722ef3935dc398ab6bc8357680ba644c Mon Sep 17 00:00:00 2001 From: Avi Fenesh Date: Thu, 12 Nov 2026 22:41:19 +0200 Subject: [PATCH] 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 --- omlx/patches/mlx_lm_mtp/cache_rollback.py | 33 ++++++++++++++ tests/test_mlx_lm_mtp_patch.py | 55 +++++++++++++++++++++++ 2 files changed, 88 insertions(+) diff --git a/omlx/patches/mlx_lm_mtp/cache_rollback.py b/omlx/patches/mlx_lm_mtp/cache_rollback.py index 2b850aa079..5a8dd79200 100644 --- a/omlx/patches/mlx_lm_mtp/cache_rollback.py +++ b/omlx/patches/mlx_lm_mtp/cache_rollback.py @@ -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 @@ -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 @@ -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 diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py index c96c98c9fb..352dad7766 100644 --- a/tests/test_mlx_lm_mtp_patch.py +++ b/tests/test_mlx_lm_mtp_patch.py @@ -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