From b54ea693a02ddab37039d3fc05ca7643998c5246 Mon Sep 17 00:00:00 2001 From: Zhongrui Sun Date: Mon, 23 Nov 2026 21:57:03 -0800 Subject: [PATCH] Fix LongCat n-gram history for right-padded batches In a right-padded batch, the n-gram cache kept the last n - 1 physical tokens of each row, so a short prompt next to a longer one saved padding as its history and its next tokens changed. Save each row's last real tokens using the cache lengths instead. AI helped write the code and run the experiments; I reviewed all of it in depth. --- mlx_lm/models/longcat_flash_ngram/layers.py | 19 +++++++++---- tests/test_models.py | 30 +++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/mlx_lm/models/longcat_flash_ngram/layers.py b/mlx_lm/models/longcat_flash_ngram/layers.py index 90e701254..40fe67db7 100644 --- a/mlx_lm/models/longcat_flash_ngram/layers.py +++ b/mlx_lm/models/longcat_flash_ngram/layers.py @@ -43,12 +43,21 @@ def __call__( input_ids = input_ids.astype(mx.int64) if cache is not None: - context = cache[0] - if context is None: - context = input_ids + n_keep = self.n - 1 + history = cache[0] + if history is None: + history = mx.zeros((input_ids.shape[0], n_keep), dtype=input_ids.dtype) + elif history.shape[-1] < n_keep: + history = mx.pad(history, [(0, 0), (n_keep - history.shape[-1], 0)]) + context = mx.concatenate([history, input_ids], axis=-1) + if cache.lengths is None: + cache[0] = context[:, seq_len:] else: - context = mx.concatenate([context, input_ids], axis=-1) - cache[0] = context[..., max(0, context.shape[-1] - self.n + 1) :] + # Skip right padding when saving each row's last real tokens. + ends = mx.clip(cache.lengths, 0, seq_len) + positions = ends[:, None] + mx.arange(n_keep) + cache[0] = mx.take_along_axis(context, positions, axis=1) + cache.advance(seq_len) else: context = input_ids diff --git a/tests/test_models.py b/tests/test_models.py index 036245a8d..b11b407e9 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -4035,6 +4035,36 @@ def test_granitemoehybrid_rope_parameters(self): sanitized = model.sanitize(weights) self.assertNotIn("lm_head.weight", sanitized) + def test_longcat_ngram_padded_history(self): + from types import SimpleNamespace + + from mlx_lm.models.cache import ArraysCache + from mlx_lm.models.longcat_flash_ngram.layers import NgramEmbedding + + args = SimpleNamespace( + vocab_size=64, + hidden_size=24, + ngram_vocab_size_ratio=2, + emb_split_num=2, + emb_neighbor_num=4, + ) + embedding = NgramEmbedding(args) + cache = ArraysCache(1) + cache.prepare(lengths=[2, 5]) + embedding(mx.array([[4, 0, 0], [5, 6, 7]]), cache) + embedding(mx.array([[0, 0], [8, 9]]), cache) + self.assertEqual(cache[0].tolist(), [[0, 4, 0], [7, 8, 9]]) + cache.finalize() + batch = embedding(mx.array([[12], [10]]), cache) + alone = embedding(mx.array([[4, 0, 12]])) + self.assertTrue(mx.allclose(batch[0, 0], alone[0, -1], atol=1e-6)) + + # Older caches saved fewer than n - 1 tokens for a short prompt. + saved = ArraysCache(1) + saved[0] = mx.array([[4]]) + restored = embedding(mx.array([[0, 12]]), saved) + self.assertTrue(mx.allclose(restored[0, -1], alone[0, -1], atol=1e-6)) + def test_granitemoehybrid_padded_batch(self): from mlx_lm.generate import BatchGenerator, generate_step from mlx_lm.models import granitemoehybrid