Skip to content
Open
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
19 changes: 14 additions & 5 deletions mlx_lm/models/longcat_flash_ngram/layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
30 changes: 30 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down