Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

feat(studio): reuse MLX VLM prompt snapshots in the resident vision batch (#12263)

Long Yixing9bafddb90db7
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index ea705c4de5e..341de5b5ae2 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -591,6 +591,10 @@ class VLMPromptSnapshotStore:
for other in [other for other in self._entries if other not in keep]:
self.discard(other)
+ def retain_key(self, key):
+ for other in [other for other in self._entries if other[0] != key]:
+ self.discard(other)
+
def clear(self):
self._entries.clear()
self._bases.clear()
@@ -766,6 +770,72 @@ class VLMPromptCacheSession:
return self._store.store(self._key, self._token_ids[:held], snapshot)
+class VLMBatchRowCache:
+ """The ``prompt_cache_state`` one batched row hands to unsloth-zoo, on the single path's grid
+ and store: ``open`` resumes the longest snapshot ending by the row's boundary and names the
+ chunk ends to bank, the boundary and the replay; ``checkpoint`` stores each. With no
+ ``store`` the row prefills cold on the same cache layout; ``releases_unserved`` frees what
+ does not serve it, as the single path does."""
+
+ def __init__(
+ self,
+ store,
+ key,
+ make_cache,
+ media_token_ids = (),
+ releases_unserved = False,
+ step = VLM_PREFILL_STEP,
+ ):
+ self._store = store
+ self._key = key
+ self._make_cache = make_cache
+ self._media_token_ids = tuple(media_token_ids)
+ self._releases_unserved = releases_unserved
+ self._step = step
+ self._token_ids = []
+ self._replay = None
+
+ def open(self, token_ids):
+ self._token_ids = token_ids = list(token_ids)
+ boundary = shape_stable_prefix(len(token_ids), 0, self._step)
+ media_end = media_prefix_end(token_ids, self._media_token_ids)
+ if self._store is None:
+ return self._make_cache(), ()
+ if boundary < media_end:
+ self._keep(None)
+ return self._make_cache(), ()
+ cache = None
+ entries, prefix = self._store.lookup(self._key, token_ids, boundary)
+ if entries is not None and prefix >= media_end:
+ try:
+ # The row advances its cache in place; the store keeps its own.
+ cache = copy_cache_entries(entries)
+ except Exception as exc:
+ logger.info("MLX VLM prompt cache: snapshot not copied for a batched row (%s)", exc)
+ if cache is None:
+ cache, prefix = self._make_cache(), 0
+ self._keep((self._key, tuple(token_ids[:prefix])) if prefix else None)
+ replay = len(token_ids) - 1
+ self._replay = replay if replay != boundary else None
+ return cache, [length for length in (boundary, replay) if length > prefix]
+
+ def _keep(self, item):
+ if self._releases_unserved:
+ self._store.retain(item)
+
+ def checkpoint(self, token_count, cache):
+ # Runs inside the batch's prefill: a failure costs a later turn its reuse, never this row.
+ try:
+ self._store.store(
+ self._key,
+ self._token_ids[:token_count],
+ copy_cache_entries(cache),
+ replay = token_count == self._replay,
+ )
+ except Exception as exc:
+ logger.info("MLX VLM prompt cache: batched row snapshot not stored (%s)", exc)
+
+
def _mlx_adapter_modules(model):
"""Return bypassable adapter entries and unsupported wrapper paths."""
adapters = []
@@ -3592,6 +3662,7 @@ class _VisionBatchRow:
"generated",
"reason",
"prompt_tokens",
+ "cached_tokens",
"admitted_at",
"ready_at",
"cancelled",
@@ -3604,11 +3675,20 @@ class _VisionBatchRow:
self.generated = 0
self.reason = None
self.prompt_tokens = 0
+ self.cached_tokens = 0
self.admitted_at = time.perf_counter()
self.ready_at = None
self.cancelled = False
+def _row_prompt_cache_gap():
+ try:
+ from unsloth_zoo.mlx.generate import row_prompt_cache_unavailable_reason
+ except ImportError:
+ return "the installed unsloth-zoo cannot resume a batched row"
+ return row_prompt_cache_unavailable_reason()
+
+
class _VisionBatchSession:
def __init__(
self,
@@ -3622,6 +3702,7 @@ class _VisionBatchSession:
self.backend = backend
self._adapter_state = adapter_state
+ self._resumes_rows = _row_prompt_cache_gap() is None
self._rows = {}
self._by_row = {}
self._settled = {}
@@ -3668,8 +3749,14 @@ class _VisionBatchSession:
backend = self.backend
plan = backend._plan_vlm_request(request)
- if plan.images:
+ state = (
+ backend._vlm_batch_row_cache(self._adapter_state, plan.images)
+ if self._resumes_rows
+ else None
+ )
+ if state is None and plan.images:
backend._release_vlm_snapshots()
+ resume = {} if state is None else {"prompt_cache_state": state}
try:
row_number = self.stream.add(
GenerationRequest(
@@ -3678,6 +3765,7 @@ class _VisionBatchSession:
max_tokens = plan.max_tokens,
sampling = SamplingParams(**plan.sampling),
logits_processors = plan.processors,
+ **resume,
)
)
except BatchRowRefused as refusal:
@@ -3716,6 +3804,7 @@ class _VisionBatchSession:
if not row.cancelled:
row.reason = result.finish_reason
row.prompt_tokens = result.prompt_token_count
+ row.cached_tokens = getattr(result, "cached_token_count", 0)
row.generated = len(result.token_ids) + (result.finish_reason == "stop")
yield from self._retire(row, cancelled = row.cancelled)
elif row.cancelled:
@@ -3734,6 +3823,7 @@ class _VisionBatchSession:
managed = self.stream.withdraw(row.row)
if managed is not None:
row.prompt_tokens = managed.prompt_token_count
+ row.cached_tokens = getattr(managed, "cached_token_count", 0)
row.generated = len(managed.token_ids)
yield from self._retire(row, cancelled = True)
@@ -3746,11 +3836,13 @@ class _VisionBatchSession:
ready_at = row.ready_at or time.perf_counter()
decoded = time.perf_counter() - ready_at
prefill_s = ready_at - row.admitted_at
+ prefilled = row.prompt_tokens - row.cached_tokens
self._settled[row.handle] = _build_generation_stats(
- row.prompt_tokens,
- (row.prompt_tokens / prefill_s) if prefill_s > 0 else 0.0,
+ prefilled,
+ (prefilled / prefill_s) if prefill_s > 0 else 0.0,
row.generated,
row.generated / max(decoded, 1e-9),
+ cached_n = row.cached_tokens,
finish_reason = row.reason or "stop",
)
yield row.handle, None
@@ -3915,17 +4007,7 @@ class MLXInferenceBackend:
# Neither side can tell where the image's rows end without them.
return None
try:
- from mlx_vlm.models.cache import make_prompt_cache
-
- language_model = getattr(self._model, "language_model", self._model)
- window = self._kv_cache_window
- # Base-vs-LoRA compare must not serve one side's KV to the other.
- key = f"{self.active_model_name}|{adapter_state!r}"
- if images:
- key += f"|{self._vlm_image_digest(images)}"
- make_cache = lambda: self._prepare_kv_entries(
- make_prompt_cache(language_model, max_kv_size = window)
- )
+ language_model, key, make_cache = self._vlm_snapshot_scope(adapter_state, images)
block = self._vlm_media_block(prompt, images, make_cache)
return VLMPromptCacheSession(
store,
@@ -3945,6 +4027,53 @@ class MLXInferenceBackend:
logger.info("MLX VLM prompt cache unavailable (%s); prefilling every request", exc)
return None
+ def _vlm_snapshot_scope(self, adapter_state, images):
+ """The language model, store key and cache factory every path resumes and banks under."""
+ from mlx_vlm.models.cache import make_prompt_cache
+
+ language_model = getattr(self._model, "language_model", self._model)
+ window = self._kv_cache_window
+ # Base-vs-LoRA compare must not serve one side's KV to the other.
+ key = f"{self.active_model_name}|{adapter_state!r}"
+ if images:
+ key += f"|{self._vlm_image_digest(images)}"
+ make_cache = lambda: self._prepare_kv_entries(
+ make_prompt_cache(language_model, max_kv_size = window)
+ )
+ return language_model, key, make_cache
+
+ def _vlm_batch_row_cache(
+ self,
+ adapter_state,
+ images = None,
+ ):
+ """A batched row's ``prompt_cache_state``, or None while the store is off. Once it is on,
+ every row gets one, so all rows' caches share the factory's layout."""
+ store = self._vlm_prompt_cache_store()
+ if store is None or self._vlm_is_diffusion_model(self._model):
+ return None
+ media_ids = self._vlm_media_token_ids(getattr(self._model, "config", None))
+ try:
+ _language_model, key, make_cache = self._vlm_snapshot_scope(adapter_state, images)
+ except Exception as exc:
+ logger.info("MLX VLM prompt cache unavailable for a batched row (%s)", exc)
+ return None
+ if images and (not media_ids or self._vlm_bidirectional_vision(self._model)):
+ # Unplaceable, or prefilled by the single path as a media block: nothing serves it.
+ store.clear()
+ store = None
+ elif images:
+ # Before the vision pass, which zoo runs before the row can look anything up.
+ store.retain_key(key)
+ return VLMBatchRowCache(
+ store,
+ key,
+ make_cache,
+ media_ids,
+ releases_unserved = bool(images),
+ step = vlm_prefill_step(),
+ )
+
@staticmethod
def _vlm_media_block_available():
try:
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 1bb682c95c6..5fa4f779f8f 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -5884,6 +5884,70 @@ def test_a_vision_row_cut_by_its_stop_sequence_leaves_the_batch(monkeypatch, sto
), "a row the engine has already retired is not handed back again"
+def test_a_resident_vision_row_resumes_from_the_snapshot_store_and_reports_it(monkeypatch):
+ from core.inference import mlx_inference
+
+ engine = _batch_engine(monkeypatch)
+ monkeypatch.setattr(engine, "GenerationRequest", SimpleNamespace, raising = False)
+ monkeypatch.setattr(engine, "SamplingParams", dict, raising = False)
+ monkeypatch.setattr(engine, "BatchRowRefused", RuntimeError, raising = False)
+ monkeypatch.setattr(engine, "row_prompt_cache_unavailable_reason", lambda: None, raising = False)
+ backend = _vlm_backend(monkeypatch, markers = None)
+ store = mlx_inference.VLMPromptSnapshotStore(max_bytes = 10**9)
+ for key in ("m", "m|img"):
+ store._entries[(key, (1,))] = ([], 0)
+ backend._vlm_snapshot_store = store
+ backend._vlm_prompt_cache_store = lambda: store
+ backend._vlm_is_diffusion_model = lambda model: False
+ backend._vlm_snapshot_scope = lambda state, images: (None, "m|img" if images else "m", list)
+
+ backend._plan_vlm_request = lambda request: SimpleNamespace(
+ prompt = "p",
+ images = request.get("images"),
+ max_tokens = 4,
+ sampling = {},
+ processors = None,
+ think_prefix = "",
+ stream = _vlm_row(backend),
+ )
+ session = _open_vision_session([])
+ session.backend, session._adapter_state = backend, None
+ session._resumes_rows = mlx_inference._row_prompt_cache_gap() is None
+ added = []
+ session.stream = SimpleNamespace(add = lambda request: added.append(request) or len(added) - 1)
+
+ session.admit({}, "text")
+ assert added[0].prompt_cache_state._store is store and len(store) == 2
+ # An image row keeps only its image's snapshots through its vision pass.
+ backend._model = SimpleNamespace(config = SimpleNamespace(image_token_id = 9))
+ session.admit({"images": [object()]}, "image")
+ assert list(store._entries) == [("m|img", (1,))]
+ assert added[1].prompt_cache_state._store is store
+ # One the single path prefills as a media block resumes nothing and frees everything.
+ backend._model.config.use_bidirectional_attention = "vision"
+ session.admit({"images": [object()]}, "block")
+ assert added[2].prompt_cache_state._store is None and len(store) == 0
+
+ result = SimpleNamespace(
+ finish_reason = "length", prompt_token_count = 10, cached_token_count = 6, token_ids = [1]
+ )
+ session.stream.step = lambda: iter([SimpleNamespace(index = 0, delta = "", result = result)])
+ list(session.step())
+ stats = session.take_stats("text")
+ assert stats["usage"]["prompt_tokens"] == 10 and stats["timings"]["prompt_n"] == 4
+ assert stats["usage"]["prompt_tokens_details"]["cached_tokens"] == 6
+ session.stream.withdraw = lambda row: result
+ list(session.withdraw(["image"]))
+ assert session.take_stats("image")["usage"]["prompt_tokens_details"]["cached_tokens"] == 6
+
+ # A zoo that cannot resume rows gets no state, and image rows clear the store as before.
+ store._entries[("m|img", (1,))] = ([], 0)
+ monkeypatch.setattr(engine, "row_prompt_cache_unavailable_reason", lambda: "old zoo")
+ session._resumes_rows = mlx_inference._row_prompt_cache_gap() is None
+ session.admit({"images": [object()]}, "old")
+ assert not hasattr(added[3], "prompt_cache_state") and len(store) == 0
+
+
def _batch_engine(monkeypatch):
"""The zoo batch engine, or a stand-in where the backend CI installs no unsloth-zoo."""
try:
diff --git a/studio/backend/tests/test_mlx_vlm_prompt_cache.py b/studio/backend/tests/test_mlx_vlm_prompt_cache.py
index 6b1836f5cf6..85fd5c5c961 100644
--- a/studio/backend/tests/test_mlx_vlm_prompt_cache.py
+++ b/studio/backend/tests/test_mlx_vlm_prompt_cache.py
@@ -11,6 +11,7 @@ from core.inference import mlx_inference as snapshots
from core.inference.mlx_inference import (
VLM_PREFILL_STEP,
RecordingForward,
+ VLMBatchRowCache,
VLMPromptCacheSession,
VLMPromptSnapshotStore,
cache_entries_nbytes,
@@ -566,6 +567,45 @@ def test_session_serves_and_stores_only_prefixes_past_the_last_media_token(fake_
assert len(store) == 0 and store.nbytes == 0
+def _prefill_row(state, token_ids):
+ """unsloth-zoo's batched row: resume the opened cache, checkpoint where a grid chunk ends."""
+ cache, lengths = state.open(token_ids)
+ done = prefix = cache_entries_offset(cache)
+ while len(token_ids) - done > 1:
+ take = min(STEP, len(token_ids) - done - 1)
+ for entry in cache:
+ entry.advance(token_ids[done : done + take])
+ done += take
+ if done in lengths:
+ state.checkpoint(done, cache)
+ return prefix, cache
+
+
[email protected]("media", (False, True))
+def test_a_batched_row_resumes_and_banks_what_the_single_path_does(fake_mx, media):
+ single, batched = (VLMPromptSnapshotStore(max_bytes = 10**9) for _ in range(2))
+ media_ids = (9,) if media else ()
+ prompts = [_media_prompt(n) if media else list(range(n)) for n in (700, 700, 900, 1000)]
+ prompts.append(prompts[-1] + [1])
+ for prompt in prompts:
+ # A media row keeps only what serves it, on both paths.
+ for store in (single, batched):
+ store.store("m", [-1], _snapshot([-1]))
+ session, _cache, _stored = _generate(
+ single, FakeLanguageModel(), prompt, media_token_ids = media_ids, releases_unserved = media
+ )
+ row = VLMBatchRowCache(batched, "m", make_cache, media_ids, media, step = STEP)
+ prefix, cache = _prefill_row(row, prompt)
+ assert prefix == session.reused_tokens and cache[0].keys.rows == prompt[:-1]
+ assert set(batched._entries) == set(single._entries)
+ assert batched._replays == single._replays
+ # The row advanced a copy: what it resumed from stays as banked.
+ entries, prefix = batched.lookup("m", prompts[-1] + [0], limit = 768)
+ assert prefix == 768 and entries[0].keys.rows == prompts[-1][:768]
+ cache, lengths = VLMBatchRowCache(None, "m", make_cache).open(prompts[-1])
+ assert cache_entries_offset(cache) == 0 and not lengths
+
+
class FakeMediaBlock:
"""A prompt's first ``rows`` rows are its image; prefilled outside the count."""