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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: reuse MLX vision-language prompt prefixes between turns (#10239)
Long Yixing975c61575e3e
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 51de37ad720..df56adf09a8 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -5,11 +5,15 @@ Drop-in replacement for InferenceBackend — same interface, uses mlx-lm/mlx-vlminstead of torch/transformers for model loading and generation."""+import copy+import hashlibimport osimport reimport sysimport threading-from contextlib import contextmanager+import time+from collections import OrderedDict+from contextlib import contextmanager, nullcontextfrom typing import Optional, Generatorfrom core.inference.message_content import content_to_textfrom core.inference.runtime_context import (@@ -37,6 +41,482 @@ from loggers import get_loggerlogger = get_logger(__name__)+# Prefix reuse for mlx-vlm generation, owned by Studio. A forward is not shape-invariant,+# so a reused turn answers as an unreused one only when both chunk the same rows: every+# request prefills on one grid and snapshots where a chunk of it ends, counting forwards.+# Driven through public kwargs only: prompt_cache, prompt_cache_state, prefill_step_size.++# The grid the boundary sits on: a prompt shorter than the step has no boundary at all.+VLM_PROMPT_CACHE_PREFILL_STEP = 256+VLM_PROMPT_CACHE_ENTRIES = 6+++def shape_stable_prefix(token_count, origin = 0):+ """Rows whole chunks produced from ``origin``; mlx-vlm holds the last token back."""+ step = VLM_PROMPT_CACHE_PREFILL_STEP+ rows = token_count - 1+ if rows < origin:+ return 0+ return origin + (rows - origin) // step * step+++def _is_cache(value):+ """Every mlx-vlm cache class carries ``state``; read off the type so no property runs."""+ return hasattr(value, "__dict__") and hasattr(type(value), "state")+++def _is_opaque_cache(value):+ """A cache whose fields this cannot reach: it carries ``state`` but keeps its+ attributes somewhere ``vars`` does not see, as a ``__slots__`` layout does. Every+ class mlx-vlm ships today is an ordinary one; a future one that is not must stop+ the copy rather than be handed back as itself, which would share it."""+ return not hasattr(value, "__dict__") and hasattr(type(value), "state")+++def _copy_value(value, mx):+ if isinstance(value, mx.array):+ return value + 0+ if isinstance(value, list):+ return [_copy_value(item, mx) for item in value]+ if isinstance(value, tuple):+ return tuple(_copy_value(item, mx) for item in value)+ if isinstance(value, dict):+ return {key: _copy_value(item, mx) for key, item in value.items()}+ if _is_cache(value):+ duplicate = copy.copy(value)+ for name, item in list(vars(duplicate).items()):+ setattr(duplicate, name, _copy_value(item, mx))+ return duplicate+ if _is_opaque_cache(value):+ raise TypeError(f"{type(value).__name__} cannot be copied")+ return value+++def _arrays(value, mx):+ if isinstance(value, mx.array):+ yield value+ elif isinstance(value, (list, tuple)):+ for item in value:+ yield from _arrays(item, mx)+ elif isinstance(value, dict):+ for item in value.values():+ yield from _arrays(item, mx)+ elif _is_cache(value):+ for item in vars(value).values():+ yield from _arrays(item, mx)+++def _release_value(value, mx):+ if isinstance(value, mx.array):+ return None+ if isinstance(value, list):+ value[:] = [_release_value(item, mx) for item in value]+ elif isinstance(value, tuple):+ return tuple(_release_value(item, mx) for item in value)+ elif isinstance(value, dict):+ for key, item in list(value.items()):+ value[key] = _release_value(item, mx)+ elif _is_cache(value):+ for name, item in list(vars(value).items()):+ setattr(value, name, _release_value(item, mx))+ return value+++def release_cache_entries(entries):+ import mlx.core as mx+ entries[:] = [_release_value(entry, mx) for entry in entries]+++def copy_cache_entries(entries):+ """Copies, object-shallow and array-deep, evaluated so they own their data."""+ import mlx.core as mx++ for entry in entries:+ if not (_is_cache(entry) or isinstance(entry, (list, tuple))):+ raise TypeError(f"{type(entry).__name__} cannot be copied")+ copies = [_copy_value(entry, mx) for entry in entries]+ mx.eval(list(_arrays(copies, mx)))+ return copies+++def cache_entries_nbytes(entries):+ import mlx.core as mx+ return sum(array.nbytes for array in _arrays(entries, mx))+++def cache_entries_offset(entries):+ """Tokens the entries hold, else None: only ``offset`` counts prompt rows."""+ for entry in entries:+ offset = getattr(entry, "offset", None)+ if isinstance(offset, int):+ return offset+ nested = vars(entry).values() if _is_cache(entry) else entry+ if isinstance(nested, (list, tuple)) or _is_cache(entry):+ found = cache_entries_offset(+ [item for item in nested if _is_cache(item) or isinstance(item, (list, tuple))]+ )+ if found is not None:+ return found+ return None+++def media_prefix_end(token_ids, media_token_ids):+ """Rows through the last media placeholder, 0 if none: what mlx-vlm resumes past."""+ media = {int(token) for token in media_token_ids}+ if not media:+ return 0+ for index in range(len(token_ids) - 1, -1, -1):+ if int(token_ids[index]) in media:+ return index + 1+ return 0+++def _chunk_rows(args, kwargs):+ for chunk in (kwargs.get("inputs_embeds"), kwargs.get("inputs"), args[0] if args else None):+ shape = getattr(chunk, "shape", None)+ if shape and len(shape) > 1:+ return shape[1]+ return 0+++def _place_per_layer_inputs(kwargs, rows, start):+ """Slice ``per_layer_inputs`` to this forward's own rows: mlx-vlm computes it for+ the whole uncached prompt and the model slices it at an offset a resume shifts. A+ single-token forward gets none and computes its own, as the reference model does."""+ inputs = kwargs.get("per_layer_inputs")+ shape = getattr(inputs, "shape", None)+ if not shape:+ return+ if rows == 1:+ kwargs.pop("per_layer_inputs")+ elif rows > 1 and shape[1] != rows and 0 <= start and start + rows <= shape[1]:+ kwargs["per_layer_inputs"] = inputs[:, start : start + rows]+++class _ForwardRecord:+ __slots__ = ("forwards", "capture_at", "snapshot", "resume_offset", "on_resume")++ def __init__(self):+ self.forwards = 0+ self.capture_at = 0+ self.snapshot = None+ self.resume_offset = None+ self.on_resume = None+++_RECORDING_CLASSES = {}+++def _prompt_wide_position_ids(args, kwargs):+ """Whether ``position_ids`` spans more than the chunk being fed: mlx-vlm primes+ mRoPE prompt-wide and not every family slices the kwarg (glm4v feeds it through+ as is), so a prompt-wide one is withheld for the model's own primed state."""+ shape = getattr(kwargs.get("position_ids"), "shape", None)+ if not shape:+ return False+ chunk = kwargs.get("inputs", args[0] if args else None)+ chunk_shape = getattr(chunk, "shape", None) or getattr(+ kwargs.get("inputs_embeds"), "shape", None+ )+ return bool(chunk_shape) and len(chunk_shape) > 1 and shape[-1] != chunk_shape[1]+++def _recording_class(base):+ """``base`` with a forward that counts itself and copies the cache on cue."""+ cls = _RECORDING_CLASSES.get(base)+ if cls is not None:+ return cls++ def __call__(self, *args, **kwargs):+ # A plain attribute: nn.Module stores dicts and lists in its module tree.+ record = self.__dict__.get("_studio_forward_record")+ cache = kwargs.get("cache")+ if record is not None:+ offset = cache_entries_offset(cache) if cache is not None else None+ if record.resume_offset is None:+ record.resume_offset = offset or 0+ if record.on_resume is not None:+ record.on_resume(record.resume_offset)+ if _prompt_wide_position_ids(args, kwargs):+ kwargs.pop("position_ids")+ _place_per_layer_inputs(+ kwargs, _chunk_rows(args, kwargs), (offset or 0) - record.resume_offset+ )+ # As the next forward begins, not as the boundary one returns: generate_step+ # converts the cache between the two (KV quantization).+ if (+ record is not None+ and record.capture_at+ and record.forwards == record.capture_at+ and cache is not None+ ):+ try:+ record.snapshot = copy_cache_entries(cache)+ except Exception as exc:+ logger.info("MLX VLM prompt cache: cache layout not copied (%s)", exc)+ output = base.__call__(self, *args, **kwargs)+ if record is not None:+ record.forwards += 1+ return output++ cls = type(f"Recording{base.__name__}", (base,), {"__call__": __call__, "_studio_base": base})+ _RECORDING_CLASSES[base] = cls+ return cls+++def _offset_aware_policy(host):+ """``chunked_prefill_policy`` of ``host`` fed only the token types past the+ cache: with the vision block already there, the suffix is text and may chunk."""+ base_policy = type(host).chunked_prefill_policy++ def policy(+ *,+ prompt_cache = None,+ prefill_kwargs = None,+ **rest,+ ):+ offset = cache_entries_offset(prompt_cache) if prompt_cache is not None else 0+ if offset and prefill_kwargs:+ prefill_kwargs = dict(prefill_kwargs)+ for key in ("mm_token_type_ids", "token_type_ids"):+ shape = getattr(prefill_kwargs.get(key), "shape", None)+ if shape and len(shape) > 1 and shape[1] > offset:+ prefill_kwargs[key] = prefill_kwargs[key][:, offset:]+ return base_policy(host, prompt_cache = prompt_cache, prefill_kwargs = prefill_kwargs, **rest)++ return policy+++class RecordingForward:+ def __init__(self, language_model):+ self._language_model = language_model+ self.record = _ForwardRecord()+ self._base = None++ def __enter__(self):+ model = self._language_model+ base = getattr(type(model), "_studio_base", type(model))+ self._base = base+ model.__class__ = _recording_class(base)+ model.__dict__["_studio_forward_record"] = self.record+ return self++ def __exit__(self, *_exc):+ model = self._language_model+ model.__dict__.pop("_studio_forward_record", None)+ model.__class__ = self._base+ return False++ def unrecorded(self, *args, **kwargs):+ """A forward the record does not count: rows prepared outside the generation."""+ return self._base.__call__(self._language_model, *args, **kwargs)+++class VLMPromptSnapshotStore:+ """Boundary snapshots, most recently used last, under a byte budget."""++ def __init__(+ self,+ max_bytes,+ max_entries = VLM_PROMPT_CACHE_ENTRIES,+ ):+ self._max_bytes = max_bytes+ self._max_entries = max_entries+ self._entries = OrderedDict()+ self.nbytes = 0++ def __len__(self):+ return len(self._entries)++ def lookup(self, key, token_ids, limit):+ """Longest stored prefix of ``token_ids`` under ``key`` ending by ``limit``."""+ best = None+ for (stored_key, prefix), (entries, _nbytes) in self._entries.items():+ n = len(prefix)+ if stored_key != key or n == 0 or n > limit:+ continue+ if best is not None and n <= len(best[0]):+ continue+ if tuple(token_ids[:n]) == prefix:+ best = (prefix, entries)+ if best is None:+ return None, 0+ self._entries.move_to_end((key, best[0]))+ return best[1], len(best[0])++ def store(self, key, prefix_ids, entries):+ nbytes = cache_entries_nbytes(entries)+ if nbytes > self._max_bytes:+ logger.debug(+ "MLX VLM prompt cache: skipping %.2f GB snapshot over the %.2f GB budget",+ nbytes / 1e9,+ self._max_bytes / 1e9,+ )+ return False+ item = (key, tuple(prefix_ids))+ self.discard(item)+ while self._entries and (+ self.nbytes + nbytes > self._max_bytes or len(self._entries) >= self._max_entries+ ):+ self.discard(next(iter(self._entries)))+ self._entries[item] = (entries, nbytes)+ self.nbytes += nbytes+ return True++ def discard(self, item):+ dropped = self._entries.pop(item, None)+ if dropped is not None:+ self.nbytes -= dropped[1]++ def retain(self, item):+ for other in [other for other in self._entries if other != item]:+ self.discard(other)++ def clear(self):+ self._entries.clear()+ self.nbytes = 0+++class VLMPromptCacheSession:+ """The ``prompt_cache_state`` one generation hands to mlx-vlm: ``find_prefix_length``+ picks the snapshot to resume from, swaps ``cache`` to it and arms the capture, and+ ``finish`` stores it. ``releases_unserved`` frees the rest, the headroom a media pass+ needs. A ``media_block`` prefills the rows through the last vision token for models+ that cannot chunk them, becoming the grid's origin, and ``policy_hosts`` are the+ models whose ``chunked_prefill_policy`` would then refuse to chunk the suffix."""++ def __init__(+ self,+ store,+ key,+ language_model,+ make_cache,+ media_token_ids = (),+ releases_unserved = False,+ media_block = None,+ policy_hosts = (),+ ):+ self._store = store+ self._key = key+ self._media_token_ids = tuple(media_token_ids)+ self._releases_unserved = releases_unserved+ self.media_block = media_block+ self._origin = 0+ # Produced for this request: prefill work rather than reuse, for the stats.+ self.produced_tokens = 0+ self.produced_seconds = 0.0+ self._policy_hosts = tuple(policy_hosts)+ self._forward = RecordingForward(language_model)+ self.cache = make_cache()+ self.reused_tokens = 0+ self._token_ids = None+ self._media_end = 0++ def __enter__(self):+ self._forward.__enter__()+ self._patched_hosts = [+ host for host in self._policy_hosts if hasattr(type(host), "chunked_prefill_policy")+ ]+ for host in self._patched_hosts:+ host.chunked_prefill_policy = _offset_aware_policy(host)+ return self++ def __exit__(self, *exc):+ try:+ for host in self._patched_hosts:+ # policy_hosts is (model, language_model), which name one object twice when+ # the wrapper exposes none, so unpatch idempotently rather than del twice.+ host.__dict__.pop("chunked_prefill_policy", None)+ finally:+ # The class goes back regardless: one left wrapped serves every later request.+ self._forward.__exit__(*exc)+ return False++ def find_prefix_length(self, token_ids):+ token_ids = list(token_ids)+ self._token_ids = token_ids+ origin = self.media_block.rows(token_ids) if self.media_block is not None else 0+ self._origin = origin+ boundary = shape_stable_prefix(len(token_ids), origin)+ self._media_end = media_prefix_end(token_ids, self._media_token_ids)+ record = self._forward.record+ if boundary < self._media_end:+ # Inside the media span: the prompt has to grow past it first.+ self._keep(None)+ return 0+ entries, prefix_len = self._store.lookup(self._key, token_ids, boundary)+ if entries is None and origin:+ # Produced here instead, in the one square forward the vision tokens need.+ self._keep(None)+ started = time.perf_counter()+ try:+ entries, prefix_len = self.media_block.prefill(self._forward, origin), origin+ self.produced_tokens = origin+ except Exception as exc:+ # Prefilled by mlx-vlm as before, off this grid: no capture.+ logger.info("MLX VLM prompt cache: media block not prefilled (%s)", exc)+ self._keep(None)+ return 0+ finally:+ # Spent either way, and outside mlx-vlm's prompt timer.+ self.produced_seconds = time.perf_counter() - started+ if entries is not None:+ # The copy is taken at the first forward, once mlx-vlm has resumed.+ self.cache = entries+ record.on_resume = self._detach_served+ self._keep((self._key, tuple(token_ids[:prefix_len])) if prefix_len else None)+ record.capture_at = (boundary - prefix_len) // VLM_PROMPT_CACHE_PREFILL_STEP+ self.reused_tokens = prefix_len+ return prefix_len++ def _keep(self, item):+ # At lookup, before the media pass a declined request starts.+ if self._releases_unserved:+ self._store.retain(item)++ def _detach_served(self, offset):+ prefix_ids = self._token_ids[: self.reused_tokens]+ if offset != self.reused_tokens:+ # Declined: freed now, before the fresh-cache request's media pass evaluates.+ self._store.discard((self._key, tuple(prefix_ids)))+ try:+ release_cache_entries(self.cache)+ except Exception as exc:+ logger.info("MLX VLM prompt cache: declined snapshot not released (%s)", exc)+ return+ # About to be advanced by this generation: the store keeps a copy.+ try:+ copy = copy_cache_entries(self.cache)+ except Exception as exc:+ # Costs the next turn its reuse, never this answer.+ logger.info("MLX VLM prompt cache: served snapshot not kept (%s)", exc)+ self._store.discard((self._key, tuple(prefix_ids)))+ return+ self._store.store(self._key, prefix_ids, copy)++ def update(self, _token_ids, _cache):+ """mlx-vlm's after-generation hook; ``finish`` stores, as it also runs on a+ consumer that stops reading early."""++ def finish(self):+ snapshot = self._forward.record.snapshot+ if snapshot is None or self._token_ids is None:+ return False+ # Read off the snapshot: a declined offer captures an earlier boundary.+ held = cache_entries_offset(snapshot)+ step = VLM_PROMPT_CACHE_PREFILL_STEP+ if (+ not held+ or held < self._origin+ or (held - self._origin) % step+ or held < self._media_end+ or held > shape_stable_prefix(len(self._token_ids), self._origin)+ ):+ logger.debug("MLX VLM prompt cache: snapshot holds %r rows, not stored", held)+ return False+ return self._store.store(self._key, self._token_ids[:held], snapshot)++def _mlx_adapter_modules(model):"""Return bypassable adapter entries and unsupported wrapper paths."""adapters = []@@ -1452,6 +1932,87 @@ def _mlx_sampling_processors(# current helper's list, which carries laguna -- only 0.6.9 stopped tokenizing laguna with# the markers, and 0.6.0-0.6.8 are what this stands in for._VLM_INLINE_SPECIAL_TOKEN_FAMILIES = ("gemma3", "gemma3n", "gemma4", "gemma4_unified")+# First mlx-vlm whose gemma-4 mask overlay skips a resumed suffix's non-square mask (#1445).+_VLM_MEDIA_BLOCK_MIN_VERSION = "0.6.4"+++def _vlm_add_special_tokens(model_type, processor):+ try:+ from mlx_vlm.utils import should_add_special_tokens+ return should_add_special_tokens(model_type, processor)+ except Exception:+ # The rule those releases inline, which Studio's runtime gate still accepts.+ return (+ getattr(processor, "chat_template", None) is None+ if model_type in _VLM_INLINE_SPECIAL_TOKEN_FAMILIES+ else True+ )+++class _VLMMediaBlock:+ """A prompt's rows through its last vision token, prefilled by Studio: models whose+ vision tokens attend to each other prefill in one forward that lands off the grid,+ and this is that forward cut where the grid can continue."""++ def __init__(self, model, processor, prompt, images, make_cache):+ from mlx_vlm.utils import prepare_inputs++ self._model = model+ self._make_cache = make_cache+ config = getattr(model, "config", None)+ read = config.get if isinstance(config, dict) else lambda attr: getattr(config, attr, None)+ self._inputs = prepare_inputs(+ processor,+ images = images,+ prompts = prompt,+ image_token_index = read("image_token_index"),+ add_special_tokens = _vlm_add_special_tokens(read("model_type"), processor),+ )++ def generate_kwargs(self):+ inputs = dict(self._inputs)+ return {+ "input_ids": inputs.pop("input_ids"),+ "pixel_values": inputs.pop("pixel_values", None),+ "mask": inputs.pop("attention_mask", None),+ **inputs,+ }++ def rows(self, token_ids):+ ids = self._inputs["input_ids"]+ if ids.shape[0] != 1 or ids[0].tolist() != list(token_ids):+ return 0+ types = self._inputs.get("mm_token_type_ids", self._inputs.get("token_type_ids"))+ if types is None:+ return 0+ visual = [index for index, kind in enumerate(types[0].tolist()) if kind in (1, 2)]+ return visual[-1] + 1 if visual else 0++ def prefill(self, forward, rows):+ import mlx.core as mx++ inputs = self._inputs+ extra = {+ key: value+ for key, value in inputs.items()+ if key not in ("input_ids", "pixel_values", "attention_mask")+ }+ features = self._model.get_input_embeddings(+ input_ids = inputs["input_ids"], pixel_values = inputs.get("pixel_values"), **extra+ )+ kwargs = {+ key: extra[key][:, :rows]+ for key in ("mm_token_type_ids", "token_type_ids")+ if key in extra+ }+ if features.per_layer_inputs is not None:+ kwargs["per_layer_inputs"] = features.per_layer_inputs[:, :rows]+ entries = self._make_cache()+ forward.unrecorded(+ inputs = None, inputs_embeds = features.inputs_embeds[:, :rows], cache = entries, **kwargs+ )+ mx.eval([entry.state for entry in entries])+ return entriesclass MLXInferenceBackend:@@ -1487,6 +2048,9 @@ class MLXInferenceBackend:self._prompt_cache_history = Noneself._prompt_cache_unavailable = False+ self._vlm_snapshot_store = None+ self._vlm_snapshot_store_unavailable = False+ self._vlm_is_diffusion_model = Nonedef _prompt_cache(self):if self._prompt_cache_history is not None or self._prompt_cache_unavailable:@@ -1516,6 +2080,127 @@ class MLXInferenceBackend:def _clear_prompt_cache(self):self._prompt_cache_history = Noneself._prompt_cache_unavailable = False+ self._vlm_snapshot_store = None+ self._vlm_snapshot_store_unavailable = False+ self._vlm_is_diffusion_model = None++ def _release_vlm_snapshots(self):+ store = getattr(self, "_vlm_snapshot_store", None)+ if store is not None:+ store.clear()++ def _vlm_prompt_cache_store(self):+ if self._vlm_snapshot_store is not None or self._vlm_snapshot_store_unavailable:+ return self._vlm_snapshot_store+ max_bytes = _prompt_cache_max_bytes(self._memory_limits_applied.get("recommended_gb"))+ if max_bytes <= 0:+ self._vlm_snapshot_store_unavailable = True+ logger.info("MLX VLM prompt cache disabled by budget")+ return None+ # Needs a dispatcher that primes mRoPE state, reports reuse and routes diffusion+ # itself: all three arrived with cached_tokens.+ try:+ from mlx_vlm.generate import GenerationResult+ from mlx_vlm.generate.diffusion import is_diffusion_model+ if not hasattr(GenerationResult, "cached_tokens"):+ raise ImportError("GenerationResult has no cached_tokens")+ except ImportError as exc:+ self._vlm_snapshot_store_unavailable = True+ logger.info(+ "MLX VLM prompt cache needs a newer mlx-vlm (%s); prefilling every request", exc+ )+ return None+ self._vlm_is_diffusion_model = is_diffusion_model+ self._vlm_snapshot_store = VLMPromptSnapshotStore(max_bytes)+ logger.info("MLX VLM prompt cache: %.2f GB budget", max_bytes / 1e9)+ return self._vlm_snapshot_store++ @staticmethod+ def _vlm_media_token_ids(config):+ ids = set()+ for attr in ("image_token_id", "image_token_index", "video_token_id", "video_token_index"):+ value = config.get(attr) if isinstance(config, dict) else getattr(config, attr, None)+ if value is not None:+ ids.add(int(value))+ return ids++ @staticmethod+ def _vlm_image_digest(images):+ digest = hashlib.sha256()+ for image in images:+ # What the tower sees: RGB, so palette indices and alpha decide nothing.+ rgb = image.convert("RGB")+ digest.update(f"{rgb.size}:{image.getexif().get(0x0112, 1)}:".encode())+ digest.update(rgb.tobytes())+ return digest.hexdigest()[:16]++ @staticmethod+ def _vlm_bidirectional_vision(model):+ config = getattr(getattr(model, "language_model", model), "config", None)+ return getattr(config, "use_bidirectional_attention", None) == "vision"++ def _vlm_prompt_cache_session(+ self,+ adapter_state,+ images = None,+ prompt = None,+ ):+ store = self._vlm_prompt_cache_store()+ if store is None or self._vlm_is_diffusion_model(self._model):+ # Diffusion generation never consults the prefix hook.+ return None+ media_ids = self._vlm_media_token_ids(getattr(self._model, "config", None))+ if images and not media_ids:+ # 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: make_prompt_cache(language_model, max_kv_size = window)+ block = self._vlm_media_block(prompt, images, make_cache)+ return VLMPromptCacheSession(+ store,+ key,+ language_model,+ make_cache,+ media_token_ids = media_ids,+ releases_unserved = bool(images),+ media_block = block,+ policy_hosts = (self._model, language_model) if block is not None else (),+ )+ except Exception as exc:+ # A layout that cannot be built once cannot be built later.+ self._vlm_snapshot_store = None+ self._vlm_snapshot_store_unavailable = True+ logger.info("MLX VLM prompt cache unavailable (%s); prefilling every request", exc)+ return None++ @staticmethod+ def _vlm_media_block_available():+ try:+ import mlx_vlm+ from packaging.version import Version+ return Version(mlx_vlm.__version__) >= Version(_VLM_MEDIA_BLOCK_MIN_VERSION)+ except Exception:+ return False++ def _vlm_media_block(self, prompt, images, make_cache):+ if not images or prompt is None or not self._vlm_bidirectional_vision(self._model):+ return None+ if not self._vlm_media_block_available():+ return None+ try:+ return _VLMMediaBlock(self._model, self._processor, prompt, images, make_cache)+ except Exception as exc:+ # This request prefills the image as before; the store stays.+ logger.info("MLX VLM prompt cache: media block not prepared (%s)", exc)+ return Nonedef _prepare_prompt_cache(self, prompt, adapter_state):history = self._prompt_cache()@@ -1759,6 +2444,8 @@ class MLXInferenceBackend:else:load_kwargs["tensor_group"] = distributed_group+ # Freed before the replacement weights are allocated, for headroom.+ self._clear_prompt_cache()model, tokenizer_or_processor = FastMLXModel.from_pretrained(model_name,**load_kwargs,@@ -2100,16 +2787,7 @@ class MLXInferenceBackend:# answer mlx_vlm makes for every generation; ask it rather than guess, or the# count is off by whatever the generation's own choice would have added._model_type = getattr(getattr(self._model, "config", None), "model_type", None)- try:- from mlx_vlm.utils import should_add_special_tokens- add_special = should_add_special_tokens(_model_type, self._processor)- except Exception:- # The rule those releases inline, which Studio's runtime gate still accepts.- add_special = (- getattr(self._processor, "chat_template", None) is None- if _model_type in _VLM_INLINE_SPECIAL_TOKEN_FAMILIES- else True- )+ add_special = _vlm_add_special_tokens(_model_type, self._processor)return len(self._tokenizer.encode(prompt, add_special_tokens = add_special))render_result = self._render_text_prompt(@@ -2644,6 +3322,16 @@ class MLXInferenceBackend:elif _rep_active:vlm_kwargs["repetition_penalty"] = float(repetition_penalty)+ session = self._vlm_prompt_cache_session(_adapter_state, images, prompt)+ if session is not None:+ vlm_kwargs["prompt_cache"] = session.cache+ vlm_kwargs["prompt_cache_state"] = session+ if session.media_block is not None:+ vlm_kwargs.update(session.media_block.generate_kwargs())+ # Reused and unreused turns must prefill on the same grid to match.+ vlm_kwargs["prefill_step_size"] = VLM_PROMPT_CACHE_PREFILL_STEP+ session_scope = session if session is not None else nullcontext()+def _stream_vlm_snapshots():nonlocal stoppedsampled = ""@@ -2651,7 +3339,14 @@ class MLXInferenceBackend:# Hold the generation lock AND the request-scoped adapter state for the# whole stream so Base-vs-LoRA compare mode honors use_adapter and the# wrapper tree is restored on completion, cancellation, or close.- with self._generation_lock, _temporary_mlx_adapter_state(self._model, _adapter_state):+ with (+ self._generation_lock,+ _temporary_mlx_adapter_state(self._model, _adapter_state),+ session_scope,+ ):+ if images and session is None:+ # The vision pass gets the headroom, under the lock so nothing refills it.+ self._release_vlm_snapshots()final_response = Nonetry:# Emit any prefilled <think> block before the first token so the@@ -2687,16 +3382,36 @@ class MLXInferenceBackend:if sequences and not stopped and released < len(sampled):yield prefill + sampledfinally:+ cached_n = produced_n = 0+ produced_s = 0.0+ if session is not None:+ # Not from mlx-vlm's hook, which a stop or cancel never reaches.+ try:+ session.finish()+ except Exception as exc:+ logger.debug("MLX VLM prompt cache: snapshot not stored (%s)", exc)+ # What mlx-vlm reused, less the rows produced here as prefill.+ cached_n = int(getattr(final_response, "cached_tokens", 0) or 0)+ produced_n, produced_s = session.produced_tokens, session.produced_seconds+ cached_n = max(cached_n - produced_n, 0)# mlx_vlm exposes the same stats fields as mlx_lm, minus a# finish reason, so that one is derived.if final_response is not None:tokenizer = getattr(self._processor, "tokenizer", self._processor)stop_ids = _mlx_stop_token_ids(tokenizer, self._model)+ # mlx-vlm rates the whole prompt against the prefill it ran, which+ # leaves out the rows the session produced first.+ prompt_n = int(getattr(final_response, "prompt_tokens", 0) or 0)+ prefilled_n = max(prompt_n - cached_n, 0)+ prompt_tps = float(getattr(final_response, "prompt_tps", 0.0) or 0.0)+ if prompt_tps and (cached_n or produced_s):+ prompt_tps = prefilled_n / (prompt_n / prompt_tps + produced_s)self.last_generation_stats = _build_generation_stats(- getattr(final_response, "prompt_tokens", 0),- getattr(final_response, "prompt_tps", 0.0),+ prefilled_n,+ prompt_tps,getattr(final_response, "generation_tokens", 0),getattr(final_response, "generation_tps", 0.0),+ cached_n,finish_reason = _mlx_finish_reason(final_response,stop_ids,@@ -2779,6 +3494,8 @@ class MLXInferenceBackend:# Hold the adapter state for the whole stream, as text and vision do,# so Base-vs-LoRA compare doesn't run the adapter on both sides.with self._generation_lock, _temporary_mlx_adapter_state(self._model, use_adapter):+ # As on the image path: the tower gets the headroom, under the lock.+ self._release_vlm_snapshots()final_response = Nonetry:for response in vlm_stream(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex d7eaa0f9806..3dcd77f0672 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -18748,6 +18748,26 @@ def _user_ordinal_supplying_the_image(messages: list) -> Optional[int]:return ordinal+def _mark_image_owner_turn(messages: list, ordinal: int) -> list:+ """Give the *ordinal*-th user turn a structured image part ahead of its text: the+ renderers attach it to the newest turn unless one already carries it."""+ marked = list(messages)+ seen = 0+ for index, message in enumerate(marked):+ if not isinstance(message, dict) or message.get("role") != "user":+ continue+ if seen == ordinal:+ body = message.get("content")+ if isinstance(body, str):+ marked[index] = {+ **message,+ "content": [{"type": "image"}, {"type": "text", "text": body}],+ }+ break+ seen += 1+ return marked++def _images_in_last_user_message(messages: list) -> int:"""Image parts on the newest user turn.@@ -23765,22 +23785,9 @@ async def produce_openai_chat_completions(if _sf_renders_image:_sf_image_ordinal = _user_ordinal_supplying_the_image(payload.messages)if _sf_image_ordinal is not None:- _sf_seen_users = 0- for _sf_idx, _sf_msg in enumerate(gen_kwargs["messages"]):- if not isinstance(_sf_msg, dict) or _sf_msg.get("role") != "user":- continue- if _sf_seen_users == _sf_image_ordinal:- _sf_body = _sf_msg.get("content")- if isinstance(_sf_body, str):- gen_kwargs["messages"][_sf_idx] = {- **_sf_msg,- "content": [- {"type": "image"},- {"type": "text", "text": _sf_body},- ],- }- break- _sf_seen_users += 1+ gen_kwargs["messages"] = _mark_image_owner_turn(+ gen_kwargs["messages"], _sf_image_ordinal+ )gen_kwargs["system_prompt"] = ""# tool_choice="none": keep history templating but advertise no tools# (heal_gate is off, markup would relay as prose). A forced function@@ -23802,6 +23809,13 @@ async def produce_openai_chat_completions(] or Noneelse:gen_kwargs["tools"] = payload.tools+ elif _sf_renders_image:+ # The plain route too: later turns then share the prefix that holds the image.+ _sf_image_ordinal = _user_ordinal_supplying_the_image(payload.messages)+ if _sf_image_ordinal is not None:+ gen_kwargs["messages"] = _mark_image_owner_turn(+ gen_kwargs["messages"], _sf_image_ordinal+ )# The potential tool context above is needed before server/client routing is# known. This standard path now has the exact schemas that will be rendered,diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 63fa16bc941..001a5411308 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -4094,3 +4094,45 @@ def test_the_mlx_mcp_snapshot_is_taken_under_the_same_guard_the_gguf_count_uses(guard = body.index("async with mcp_server_snapshot_guard():")snapshot = body.index("asyncio.to_thread(cached_mcp_tools)")assert guard < snapshot, "the guard must be held across the snapshot, not after it"+++# --- VLM prompt snapshots -------------------------------------------------------+++def _fake_image(+ pixels,+ raw = None,+ orientation = None,+):+ """A PIL-like image whose RGB conversion holds ``pixels``; a palette image's own+ bytes are indices (``raw``) saying nothing about its colors."""+ rgb = SimpleNamespace(mode = "RGB", size = (2, 2), tobytes = lambda: pixels)+ return SimpleNamespace(+ mode = "P" if raw else "RGB",+ size = (2, 2),+ tobytes = lambda: raw or pixels,+ convert = lambda _mode: rgb,+ getexif = lambda: {0x0112: orientation} if orientation else {},+ )+++def test_mlx_vlm_snapshots_are_keyed_by_what_the_vision_tower_sees():+ from core.inference.mlx_inference import MLXInferenceBackend as backend++ digest = backend._vlm_image_digest+ assert digest([_fake_image(b"aaaa")]) == digest([_fake_image(b"aaaa")])+ assert digest([_fake_image(b"aaaa")]) != digest([_fake_image(b"bbbb")])+ assert digest([_fake_image(b"red!", raw = b"idx")]) != digest([_fake_image(b"blue", raw = b"idx")])+ assert digest([_fake_image(b"aaaa")]) != digest([_fake_image(b"aaaa", orientation = 6)])+ assert digest([_fake_image(b"aaaa")]) != digest([_fake_image(b"aaaa"), _fake_image(b"bbbb")])+++def test_vlm_add_special_tokens_falls_back_to_the_inline_rule(monkeypatch):+ from core.inference.mlx_inference import _vlm_add_special_tokens as rule++ monkeypatch.setitem(sys.modules, "mlx_vlm.utils", types.ModuleType("mlx_vlm.utils"))+ template = SimpleNamespace(chat_template = "t")+ assert rule("gemma4", template) is False and rule("gemma4", SimpleNamespace()) is True+ assert rule("qwen2_vl", template) is True+ sys.modules["mlx_vlm.utils"].should_add_special_tokens = lambda *_: "mlx-vlm's answer"+ assert rule("gemma4", template) == "mlx-vlm's answer"diff --git a/studio/backend/tests/test_mlx_vlm_prompt_cache.py b/studio/backend/tests/test_mlx_vlm_prompt_cache.pynew file mode 100644index 00000000000..cc314e5163e--- /dev/null+++ b/studio/backend/tests/test_mlx_vlm_prompt_cache.py@@ -0,0 +1,716 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import logging+import sys+import types++import pytest++from core.inference import mlx_inference as snapshots+from core.inference.mlx_inference import (+ VLM_PROMPT_CACHE_PREFILL_STEP as STEP,+ RecordingForward,+ VLMPromptCacheSession,+ VLMPromptSnapshotStore,+ cache_entries_nbytes,+ cache_entries_offset,+ copy_cache_entries,+ release_cache_entries,+ media_prefix_end,+ shape_stable_prefix,+)++[email protected](autouse = True)+def _plain_logger(monkeypatch):+ """The backend logs through structlog, which caplog does not see."""+ monkeypatch.setattr(snapshots, "logger", logging.getLogger(snapshots.__name__))+++class FakeArray:+ def __init__(self, rows):+ self.rows = list(rows)++ def __add__(self, _other):+ return FakeArray(self.rows)++ @property+ def nbytes(self):+ return 4 * len(self.rows)+++def fake_mx(monkeypatch):+ evaluated = []+ mlx_core = types.ModuleType("mlx.core")+ mlx_core.array = FakeArray+ mlx_core.eval = lambda arrays: evaluated.append(list(arrays))+ mlx_pkg = types.ModuleType("mlx")+ mlx_pkg.core = mlx_core+ monkeypatch.setitem(sys.modules, "mlx", mlx_pkg)+ monkeypatch.setitem(sys.modules, "mlx.core", mlx_core)+ return evaluated+++class FakeKV:+ state = property(lambda self: self.keys)++ def __init__(self):+ self.keys = FakeArray([])+ self.offset = 0++ def advance(self, tokens):+ self.keys = FakeArray(self.keys.rows + list(tokens))+ self.offset += len(tokens)+++class FakeState:+ state = property(lambda self: self.cache)++ def __init__(self):+ self.cache = [None, None]++ def advance(self, tokens):+ self.cache[0] = FakeArray(tokens[-1:])+ self.cache[1] = FakeArray([sum(tokens)])+++class FakeCacheList:+ state = property(lambda self: [c.state for c in self.caches])++ def __init__(self, *caches):+ self.caches = caches++ def advance(self, tokens):+ for entry in self.caches:+ entry.advance(tokens)+++class FakeSimpleKV:+ """Encoder-decoder entry: rows counted in ``cache_length``, not ``offset``."""++ state = property(lambda self: self.keys)++ def __init__(self):+ self.keys = FakeArray([])+ self.cache_length = 0++ def advance(self, tokens):+ self.keys = FakeArray(self.keys.rows + list(tokens))+ self.cache_length += len(tokens)+++class FakeLanguageModel:+ def __init__(self):+ self.seen_kwargs = []+ self.outputs = []++ def __call__(+ self,+ inputs,+ cache = None,+ **kwargs,+ ):+ self.seen_kwargs.append(dict(kwargs))+ for entry in cache:+ entry.advance(inputs)+ self.outputs.append(object())+ return self.outputs[-1]+++def make_cache():+ return [FakeKV(), FakeState(), FakeKV()]+++def run_generation(+ language_model,+ token_ids,+ cache,+ start,+ between = None,+ **kwargs,+):+ """mlx-vlm's prefill loop: grid chunks over all but the last token, then it."""+ n = len(token_ids)+ pos = start+ while n - pos > 1:+ take = min(STEP, n - pos - 1)+ language_model(token_ids[pos : pos + take], cache = cache, **kwargs)+ if between is not None:+ between(cache)+ pos += take+ language_model(token_ids[n - 1 :], cache = cache, **kwargs)+++def _snapshot(rows):+ kv = FakeKV()+ kv.advance(rows)+ return [kv]+++def _generate(+ store,+ language_model,+ token_ids,+ *,+ honour_reuse = True,+ kwargs = None,+ media_token_ids = (),+ **session_kwargs,+):+ with VLMPromptCacheSession(+ store, "m", language_model, make_cache, media_token_ids = media_token_ids, **session_kwargs+ ) as session:+ prefix = session.find_prefix_length(token_ids)+ cache = session.cache+ if not honour_reuse:+ cache, prefix = make_cache(), 0+ run_generation(language_model, token_ids, cache, prefix, **(kwargs or {}))+ session.update(token_ids, cache)+ stored = session.finish()+ return session, cache, stored+++def test_shape_stable_prefix_is_the_last_whole_chunk_from_the_origin():+ grid = [(0, 0, 0), (1, 0, 0), (256, 0, 0), (257, 0, 256), (512, 0, 256), (513, 0, 512)]+ grid += [(2049, 0, 2048), (4018, 0, 3840), (600, 647, 0), (648, 647, 647), (903, 647, 647)]+ grid += [(904, 647, 903), (1160, 647, 1159)]+ for tokens, origin, prefix in grid:+ assert shape_stable_prefix(tokens, origin) == prefix, (tokens, origin)+++def test_copy_and_release_walk_every_array_of_a_composite_layout(fake_mx):+ kv, state = FakeKV(), FakeState()+ kv.advance([1, 2, 3])+ state.advance([1, 2, 3])+ state.extra = (FakeArray([9]), 7)+ nested = FakeCacheList(FakeKV(), FakeState())+ nested.advance([1, 2])+ pair = (FakeSimpleKV(), FakeSimpleKV())+ for entry in pair:+ entry.advance([5])+ entries = [kv, state, nested, pair]+ copies = copy_cache_entries(entries)++ assert copies[0].offset == 3 and copies[0].keys.rows == [1, 2, 3]+ assert copies[0].keys is not kv.keys+ assert copies[1].cache[1].rows == [6] and copies[1].cache is not state.cache+ assert copies[1].cache[0] is not state.cache[0] and copies[1].cache[1] is not state.cache[1]+ assert copies[1].extra[0] is not state.extra[0] and copies[1].extra[1] == 7+ assert copies[2].caches[0].keys is not nested.caches[0].keys+ assert copies[2].caches[1].cache is not nested.caches[1].cache+ assert isinstance(copies[3], tuple) and copies[3][1] is not pair[1]+ kv.advance([4])+ state.advance([4])+ nested.advance([3])+ assert copies[0].keys.rows == [1, 2, 3] and copies[1].cache[0].rows == [3]+ assert copies[2].caches[0].keys.rows == [1, 2] and copies[2].caches[0].offset == 2+ assert len(fake_mx) == 1 and len(fake_mx[0]) == 9++ assert cache_entries_nbytes([nested, pair]) == 4 * (3 + 1 + 1 + 1 + 1)+ assert cache_entries_offset([nested]) == 3 and cache_entries_offset([pair]) is None+ assert cache_entries_offset([state, kv]) == 4 and cache_entries_offset([state]) is None++ release_cache_entries(entries)+ assert not list(snapshots._arrays(entries, sys.modules["mlx.core"]))+ assert nested.caches[0].keys is None and nested.caches[0].offset == 3+ assert nested.caches[1].cache == [None, None] and pair[1].cache_length == 1+ assert len(fake_mx) == 1++ with pytest.raises(TypeError, match = "int cannot be copied"):+ copy_cache_entries([3])+ with pytest.raises(TypeError, match = "SimpleNamespace cannot be copied"):+ copy_cache_entries([types.SimpleNamespace(keys = FakeArray([1]))])++ ids = [1, 2, 9, 9, 9, 3, 4, 9, 5, 7, 6]+ assert media_prefix_end(ids, {9}) == 8+ assert media_prefix_end(ids, [9, 7]) == 10+ assert media_prefix_end(ids, ()) == 0+ assert media_prefix_end([1, 2, 3], {9}) == 0+ assert media_prefix_end([9], {9}) == 1+++def test_recording_forward_copies_the_cache_after_the_chosen_forward(fake_mx, caplog):+ language_model = FakeLanguageModel()+ cache = make_cache()+ original_class = type(language_model)+ with RecordingForward(language_model) as recording:+ recording.record.capture_at = 2+ assert type(language_model) is not original_class+ outputs = [+ language_model(chunk, cache = cache, per_layer_inputs = "kept")+ for chunk in ([1, 2], [3, 4], [5, 6])+ ]+ recording.unrecorded([7], cache = cache)+ assert outputs == language_model.outputs[:3] and recording.record.forwards == 3+ snapshot = recording.record.snapshot+ assert snapshot[0].keys.rows == [1, 2, 3, 4] and snapshot[0].offset == 4+ assert snapshot[1].cache[1].rows == [7]+ assert cache[0].offset == 7 and snapshot[0] is not cache[0]+ assert all(kw == {"per_layer_inputs": "kept"} for kw in language_model.seen_kwargs[:3])+ assert type(language_model) is original_class+ assert "_studio_forward_record" not in vars(language_model)++ with RecordingForward(language_model) as recording:+ language_model([1], cache = make_cache())+ assert recording.record.snapshot is None and recording.record.forwards == 1+ with pytest.raises(RuntimeError):+ with RecordingForward(language_model):+ raise RuntimeError("generation failed")+ assert type(language_model) is original_class++ # A cache that cannot be copied still answers.+ opaque = [types.SimpleNamespace(advance = lambda _t: None)]+ with caplog.at_level("INFO"), RecordingForward(language_model) as recording:+ recording.record.capture_at = 1+ language_model([1], cache = opaque)+ output = language_model([2], cache = opaque)+ assert output is language_model.outputs[-1]+ assert recording.record.snapshot is None+ assert "SimpleNamespace cannot be copied" in caplog.text+++def test_recording_forward_copies_what_generation_converted_after_the_boundary_forward(fake_mx):+ """mlx-vlm quantizes the live cache after a chunk; the snapshot must hold that."""++ class FakeQuantizedKV(FakeKV):+ pass++ def quantize(cache):+ if cache[0].offset >= 512:+ converted = FakeQuantizedKV()+ converted.keys, converted.offset = cache[0].keys, cache[0].offset+ cache[0] = converted++ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ ids = list(range(700))+ with VLMPromptCacheSession(store, "m", FakeLanguageModel(), make_cache) as session:+ session.find_prefix_length(ids)+ run_generation(session._forward._language_model, ids, session.cache, 0, between = quantize)+ assert session.finish()+ entries, prefix = store.lookup("m", ids, limit = 512)+ assert prefix == 512 and type(entries[0]) is FakeQuantizedKV+ assert entries[0].keys.rows == ids[:512]+++class Sliceable:+ def __init__(self, rows):+ self.rows = list(rows)+ self.shape = (1, len(self.rows), 8)++ def __getitem__(self, item):+ return Sliceable(self.rows[item[1]])+++def test_recording_forward_slices_per_layer_inputs_from_the_resume_offset(fake_mx):+ language_model = FakeLanguageModel()+ embeds = lambda rows: types.SimpleNamespace(shape = (1, rows, 8))+ for resumed in (0, 512):+ suffix = Sliceable(range(resumed, resumed + 300))+ cache = make_cache()+ cache[0].advance(range(resumed))+ with RecordingForward(language_model):+ for rows in (256, 43):+ language_model(+ inputs = [0] * rows,+ inputs_embeds = embeds(rows),+ cache = cache,+ per_layer_inputs = suffix,+ other = 1,+ )+ # A single token: the model computes its own from the id.+ language_model([0], inputs_embeds = embeds(1), cache = cache, per_layer_inputs = suffix)+ seen = [kw.get("per_layer_inputs") for kw in language_model.seen_kwargs[-3:]]+ assert seen[0].rows == list(range(resumed, resumed + 256))+ assert seen[1].rows == list(range(resumed + 256, resumed + 299))+ assert seen[2] is None+ assert language_model.seen_kwargs[0]["other"] == 1++ short = Sliceable(range(100))+ cache = make_cache()+ cache[0].advance(range(512))+ with RecordingForward(language_model):+ language_model(+ types.SimpleNamespace(shape = (1, 43)), cache = [], per_layer_inputs = Sliceable(range(300))+ )+ language_model(+ inputs = [0] * 256, inputs_embeds = embeds(256), cache = cache, per_layer_inputs = short+ )+ language_model(+ inputs = [0] * 256, inputs_embeds = embeds(256), cache = [], per_layer_inputs = short+ )+ seen = [kw["per_layer_inputs"] for kw in language_model.seen_kwargs[-3:]]+ assert seen[0].rows == list(range(43)) and seen[1] is short and seen[2] is short+++def test_recording_forward_withholds_only_prompt_wide_position_ids(fake_mx):+ language_model = FakeLanguageModel()+ shaped = types.SimpleNamespace+ embedded = dict(inputs = [1, 2, 3, 4, 5], inputs_embeds = shaped(shape = (1, 5, 8)), cache = [])+ with RecordingForward(language_model):+ language_model(shaped(shape = (1, 256)), cache = [], position_ids = shaped(shape = (3, 1, 900)))+ language_model(shaped(shape = (1, 256)), cache = [], position_ids = shaped(shape = (3, 1, 256)))+ language_model(position_ids = shaped(shape = (1, 5)), **embedded)+ language_model(position_ids = shaped(shape = (3, 1, 900)), **embedded)+ language_model([1, 2], cache = [], position_ids = None)+ kept = ["position_ids" in kw for kw in language_model.seen_kwargs]+ assert kept == [False, True, True, False, True]+++def test_store_serves_the_longest_prefix_and_evicts_to_fit(fake_mx):+ store = VLMPromptSnapshotStore(max_bytes = 10**6)+ ids = list(range(1000))+ store.store("m", ids[:256], _snapshot(ids[:256]))+ store.store("m", ids[:512], _snapshot(ids[:512]))+ store.store("m", [7] * 768, _snapshot([7] * 768))+ store.store("other", ids[:768], _snapshot(ids[:768]))+ entries, prefix = store.lookup("m", ids, limit = 768)+ assert prefix == 512 and entries[0].offset == 512+ assert store.lookup("m", ids, limit = 511) == (store.lookup("m", ids, limit = 256)[0], 256)+ assert store.lookup("m", ids, limit = 255) == (None, 0)+ assert store.lookup("m", [7] * 800, limit = 768)[1] == 768+ assert store.lookup("m", [1] + ids[1:], limit = 768) == (None, 0)++ store = VLMPromptSnapshotStore(max_bytes = 4 * 700)+ a, b, c = [1] * 256, [2] * 256, [3] * 256+ assert store.store("m", a, _snapshot(a)) and store.store("m", b, _snapshot(b))+ store.lookup("m", a + [0], limit = 256) # a is now the most recent+ assert store.store("m", c, _snapshot(c))+ assert store.lookup("m", b + [0], limit = 256) == (None, 0)+ assert store.lookup("m", a + [0], limit = 256)[1] == 256+ assert store.nbytes == 4 * 512 and len(store) == 2+ assert not store.store("m", [4] * 800, _snapshot([4] * 800))+ assert len(store) == 2 and store.nbytes == 4 * 512++ store = VLMPromptSnapshotStore(max_bytes = 10**9, max_entries = 2)+ store.store("m", [1], _snapshot([1]))+ store.store("m", [1], _snapshot([1, 1]))+ assert len(store) == 1 and store.nbytes == 8+ store.store("m", [2], _snapshot([2]))+ store.store("m", [3], _snapshot([3]))+ assert len(store) == 2 and store.lookup("m", [1, 0], limit = 1) == (None, 0)++ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ store.store("a", [1, 2], _snapshot([1, 2]))+ store.store("b", [1, 2, 3], _snapshot([1, 2, 3]))+ store.store("a", [1, 2, 3, 4], _snapshot([1, 2, 3, 4]))+ store.retain(("a", (1, 2, 3, 4)))+ assert list(store._entries) == [("a", (1, 2, 3, 4))]+ assert store.nbytes == cache_entries_nbytes(_snapshot([1, 2, 3, 4]))+ store.retain(None)+ assert len(store) == 0 and store.nbytes == 0+++def test_session_captures_the_boundary_and_resumes_leaving_a_copy_behind(fake_mx):+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ language_model = FakeLanguageModel()+ ids = list(range(700))+ session, cache, stored = _generate(store, language_model, ids)+ assert session.reused_tokens == 0 and stored and cache[0].offset == 700+ stored_entries, prefix = store.lookup("m", ids, limit = 512)+ assert prefix == 512 and stored_entries[0].keys.rows == ids[:512]+ assert stored_entries[1].cache[0].rows == [511]+ store.store("m", ids[:256], _snapshot(range(9000, 9256)))+ store.store("t", ids[:512], _snapshot(range(9000, 9512)))++ longer = ids + list(range(700, 800))+ fake_mx.clear()+ session, cache, stored = _generate(store, language_model, longer)+ assert session.reused_tokens == 512 and cache is stored_entries+ kept = store.lookup("m", ids, limit = 512)[0]+ assert kept is not stored_entries and kept[0] is not cache[0]+ assert kept[0].offset == 512 and kept[0].keys.rows == ids[:512] # the copy never moved+ assert kept[0].keys in fake_mx[0] # the copy, evaluated at the first forward+ assert cache[0].offset == 800 and cache[0].keys.rows == longer+ assert stored and store.lookup("m", longer, limit = 768)[1] == 768++ session, _cache, stored = _generate(store, language_model, longer + [1])+ assert session.reused_tokens == 768 and not stored and len(store) == 4+++def test_session_stores_what_the_snapshot_holds_when_reuse_was_declined(fake_mx, monkeypatch):+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ language_model = FakeLanguageModel()+ ids = list(range(1100))+ _generate(store, language_model, ids) # boundary 1024+ original = store.lookup("m", ids, limit = 1024)[0]+ store.store("t", ids[:512], _snapshot(range(9000, 9512))) # a decoy+ fake_mx.clear()+ session, _cache, stored = _generate(store, language_model, ids + [1] * 300, honour_reuse = False)+ assert session.reused_tokens == 1024 and stored+ assert store.lookup("m", ids, limit = 256)[1] == 256+ # The declined offer is released, not copied: it would be declined again.+ assert len(store) == 2 and store.lookup("m", ids, limit = 1024)[1] == 256+ assert store.lookup("t", ids, limit = 512)[1] == 512+ assert not list(snapshots._arrays(original, sys.modules["mlx.core"]))+ assert original[0].offset == 1024 and len(fake_mx) == 1++ # A copy that cannot be made drops the snapshot it was taken from, too.+ store, ids = VLMPromptSnapshotStore(max_bytes = 10**9), list(range(700))+ _generate(store, language_model, ids)++ def _fail(_arrays):+ raise MemoryError("no room for a copy")++ monkeypatch.setattr(sys.modules["mlx.core"], "eval", _fail)+ with VLMPromptCacheSession(store, "m", language_model, make_cache) as session:+ assert session.find_prefix_length(ids + [1]) == 512+ run_generation(language_model, ids + [1], session.cache, 512)+ assert session.cache[0].offset == 701 and len(store) == 0+ assert not session.finish()+++def test_session_stores_only_snapshots_that_sit_on_the_grid(fake_mx):+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ language_model = FakeLanguageModel()+ ids = list(range(600))+ with VLMPromptCacheSession(store, "m", language_model, make_cache) as session:+ session.find_prefix_length(ids)+ language_model(ids[:150], cache = session.cache)+ language_model(ids[150:300], cache = session.cache)+ language_model(ids[300:], cache = session.cache)+ assert session._forward.record.snapshot is not None+ assert not session.finish()+ with VLMPromptCacheSession(store, "m", language_model, lambda: [FakeState()]) as session:+ session.find_prefix_length(ids[:300])+ run_generation(session._forward._language_model, ids[:300], session.cache, 0)+ assert session._forward.record.snapshot is not None and not session.finish()+ with VLMPromptCacheSession(store, "m", language_model, make_cache) as session:+ assert not session.finish() and session.cache[0].offset == 0+ assert len(store) == 0++ layout = lambda: [FakeCacheList(FakeKV(), FakeState()), FakeCacheList(FakeKV(), FakeState())]+ with VLMPromptCacheSession(store, "m", language_model, layout) as session:+ session.find_prefix_length(ids)+ run_generation(language_model, ids, session.cache, 0)+ assert session.finish()+ entries, prefix = store.lookup("m", ids, limit = 512)+ assert prefix == 512 and entries[1].caches[0].offset == 512+ assert store.nbytes == 2 * 4 * (512 + 1 + 1)+++def _media_prompt(n):+ ids = list(range(1000, 1000 + n))+ ids[500:601] = [9] * 101+ return ids+++def test_session_serves_and_stores_only_prefixes_past_the_last_media_token(fake_mx):+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ language_model = FakeLanguageModel()+ session, _cache, stored = _generate(+ store, language_model, _media_prompt(700), media_token_ids = (9,)+ )+ assert not stored and len(store) == 0 and session.reused_tokens == 0 and not fake_mx+ _generate(store, language_model, _media_prompt(900), media_token_ids = (9,))+ assert store.lookup("m", _media_prompt(900), limit = 768)[1] == 768+ session, _cache, _stored = _generate(+ store, language_model, _media_prompt(1000), media_token_ids = (9,)+ )+ assert session.reused_tokens == 768+ session, _cache, stored = _generate(+ store, language_model, _media_prompt(1100), honour_reuse = False, media_token_ids = (9,)+ )+ assert session.reused_tokens == 768 and not stored and len(store) == 0++ prompt = _media_prompt(1000)+ _generate(store, language_model, prompt, media_token_ids = (9,))+ store.store("t", prompt[:768], _snapshot(prompt[:768]))+ store.store("m", [5] + prompt[1:768], _snapshot(range(768)))+ session = lambda **kw: VLMPromptCacheSession(+ store, "m", language_model, make_cache, media_token_ids = (9,), **kw+ )+ assert session().find_prefix_length(prompt) == 768 and len(store) == 3+ # A media request keeps only what serves it, and these three serve nothing.+ assert session(releases_unserved = True).find_prefix_length(prompt) == 768+ assert list(store._entries) == [("m", tuple(prompt[:768]))]+ assert session(releases_unserved = True).find_prefix_length(_media_prompt(700)) == 0+ assert len(store) == 0 and store.nbytes == 0+++class FakeMediaBlock:+ """A prompt's first ``rows`` rows are its image; prefilled outside the count."""++ fail = False+ prefilled = 0+ store = None++ def __init__(self, rows):+ self.block_rows = rows++ def rows(self, token_ids):+ return self.block_rows if len(token_ids) > self.block_rows else 0++ def prefill(self, forward, rows):+ if self.fail:+ raise RuntimeError("no block")+ self.prefilled += 1+ self.entries_at_prefill = len(self.store)+ entries = make_cache()+ forward.unrecorded(list(range(rows)), cache = entries)+ return entries+++def _block_prompt(n):+ return [9] * 100 + list(range(1000, 900 + n))+++def test_session_prefills_the_media_block_and_chains_from_it(fake_mx, caplog):+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ language_model = FakeLanguageModel()+ block = FakeMediaBlock(100)+ block.store = store+ store.store("t", [1, 2, 3], _snapshot(range(3)))+ kwargs = dict(media_token_ids = (9,), media_block = block, releases_unserved = True)+ generate = lambda n, **kw: _generate(store, language_model, _block_prompt(n), **kwargs, **kw)+ session, cache, stored = generate(500)+ assert session.reused_tokens == 100 and block.prefilled == 1 and stored+ assert block.entries_at_prefill == 0 and session.produced_seconds > 0+ assert session.produced_tokens == 100 and cache[0].offset == 500 and len(fake_mx) == 2+ assert [len(item[1]) for item in store._entries] == [100, 356]+ session, _cache, stored = generate(700)+ assert session.reused_tokens == 356 and block.prefilled == 1 and stored+ assert session.produced_tokens == 0+ assert [len(item[1]) for item in store._entries] == [356, 612]+ store.clear()+ session, _cache, stored = generate(300) # no whole chunk past the block+ assert session.reused_tokens == 100 and block.prefilled == 2 and not stored+ assert [len(item[1]) for item in store._entries] == [100]+ # Declined and run from zero: the capture lands at 256, off the grid; block dropped.+ session, _cache, stored = generate(500, honour_reuse = False)+ assert session.reused_tokens == 100 and block.prefilled == 2+ assert not stored and len(store) == 0++ # A block that fails: prefilled by the caller as before, nothing captured.+ store, failing = VLMPromptSnapshotStore(max_bytes = 10**9), FakeMediaBlock(100)+ failing.fail = True+ fake_mx.clear()+ with caplog.at_level("INFO"):+ session, cache, stored = _generate(+ store,+ FakeLanguageModel(),+ _block_prompt(500),+ media_token_ids = (9,),+ media_block = failing,+ )+ assert session.reused_tokens == 0 and cache[0].offset == 500+ assert not stored and len(store) == 0 and not fake_mx+ assert session.produced_tokens == 0 and session.produced_seconds > 0+ assert "media block not prefilled" in caplog.text+++class FakeTypeIds:+ def __init__(self, n, start):+ self.shape = (1, n)+ self.start = start++ def __getitem__(self, item):+ offset = item[1].start or 0+ return FakeTypeIds(self.shape[1] - offset, self.start + offset)+++class FakeHost:+ def __init__(self):+ self.seen = []++ def chunked_prefill_policy(self, **kwargs):+ self.seen.append(kwargs["prefill_kwargs"]["mm_token_type_ids"].start)+ return True+++def test_session_feeds_the_chunking_policy_only_the_rows_past_the_cache(fake_mx):+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ host, plain = FakeHost(), object()+ resumed = make_cache()+ resumed[0].advance(range(100))+ ask = lambda cache, n: host.chunked_prefill_policy(+ prompt_cache = cache, prefill_kwargs = {"mm_token_type_ids": FakeTypeIds(n, 0)}+ )+ with VLMPromptCacheSession(+ store, "m", FakeLanguageModel(), make_cache, policy_hosts = (host, plain)+ ):+ assert ask(resumed, 300) is True+ ask(make_cache(), 300)+ ask(resumed, 50)+ assert host.seen == [100, 0, 0]+ assert "chunked_prefill_policy" not in vars(host)+ ask(resumed, 300)+ assert host.seen[-1] == 0+++def test_snapshot_module_imports_mlx_only_when_copying(monkeypatch):+ monkeypatch.delitem(sys.modules, "mlx.core", raising = False)+ monkeypatch.setitem(sys.modules, "mlx", None)+ monkeypatch.setitem(sys.modules, "mlx.core", None)+ assert shape_stable_prefix(300) == 256+ with pytest.raises(ImportError):+ copy_cache_entries([FakeKV()])+ assert snapshots.VLM_PROMPT_CACHE_ENTRIES == 6+++class FakeSlottedKV:+ """A cache whose fields live in ``__slots__``: ``vars()`` cannot reach them."""++ __slots__ = ("keys", "offset")+ state = property(lambda self: self.keys)++ def __init__(self):+ self.keys = FakeArray([1, 2, 3])+ self.offset = 3+++class FakeDictKV:+ """A cache holding its arrays in a dict, as a hybrid layout would."""++ state = property(lambda self: self.tensors)++ def __init__(self):+ self.tensors = {"keys": FakeArray([1, 2, 3])}+ self.offset = 3+++def test_copy_walks_a_dict_held_state(fake_mx):+ """A dict of arrays used to fall through the copier and be shared, so the store+ would hand back a dict the next generation writes through."""+ live = [FakeCacheList(FakeDictKV())]+ saved = copy_cache_entries(live)+ assert saved[0].caches[0].tensors is not live[0].caches[0].tensors+ assert saved[0].caches[0].tensors["keys"] is not live[0].caches[0].tensors["keys"]+ assert cache_entries_nbytes(saved) == 12+ release_cache_entries(saved)+ assert saved[0].caches[0].tensors["keys"] is None+++def test_copy_refuses_a_cache_it_cannot_walk_rather_than_sharing_it(fake_mx):+ """The top level already refuses an unrecognised entry. Nested, one used to be+ returned as itself: a live cache in the store, advanced by the turn that served it.+ Refusing costs the next turn its reuse; sharing costs it its answer."""+ with pytest.raises(TypeError):+ copy_cache_entries([FakeCacheList(FakeSlottedKV())])+++def test_session_restores_the_model_when_one_host_is_named_twice(fake_mx):+ """``policy_hosts`` is (model, language_model), and the second falls back to the+ first when the wrapper exposes no language model, so the same object can be listed+ twice. Unpatching it twice must not strand the recording class on the model."""+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ host = FakeHost()+ before = type(host)+ with VLMPromptCacheSession(store, "m", host, make_cache, policy_hosts = (host, host)):+ pass+ assert type(host) is before+ assert "chunked_prefill_policy" not in vars(host)+++def test_session_restores_the_model_even_if_unpatching_fails(fake_mx):+ """Any failure while unpatching leaves the model wrapped otherwise, and every later+ request on that load then answers through a stale forward record."""+ store = VLMPromptSnapshotStore(max_bytes = 10**9)+ host = FakeHost()+ before = type(host)+ session = VLMPromptCacheSession(store, "m", host, make_cache, policy_hosts = (host,))+ session.__enter__()+ del host.chunked_prefill_policy+ session.__exit__(None, None, None)+ assert type(host) is beforediff --git a/studio/backend/tests/test_vision_client_tools.py b/studio/backend/tests/test_vision_client_tools.pyindex 247769751bb..9f6ac065944 100644--- a/studio/backend/tests/test_vision_client_tools.py+++ b/studio/backend/tests/test_vision_client_tools.py@@ -842,6 +842,88 @@ def test_a_historical_image_stays_on_the_turn_that_sent_it():)+def _historical_image_thread():+ from models.inference import ChatMessage+ return [+ ChatMessage(role = "user", content = "EARLIER_QUESTION with no picture"),+ ChatMessage(role = "assistant", content = "hello"),+ ChatMessage(+ role = "user",+ content = [+ {"type": "text", "text": "IMAGE_QUESTION about the picture"},+ {"type": "image_url", "image_url": {"url": _PNG_DATA_URL}},+ ],+ ),+ ChatMessage(role = "assistant", content = "it is a dot"),+ ChatMessage(role = "user", content = "LATER_QUESTION unrelated to it"),+ ]+++def _plain_route_messages(chat_template_info):+ import asyncio+ import os+ import sys++ import pytest as _pytest++ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import test_sf_client_tools_passthrough as passthrough+ from models.inference import ChatCompletionRequest++ backend = passthrough._ScriptedBackend(passthrough._fixed("a plain answer"))+ backend.models["sf-model"]["is_vision"] = True+ backend.models["sf-model"]["chat_template_info"] = chat_template_info+ payload = ChatCompletionRequest(+ model = "default", stream = False, messages = _historical_image_thread()+ )+ monkeypatch = _pytest.MonkeyPatch()+ try:+ passthrough._call(payload, monkeypatch, backend)+ finally:+ monkeypatch.undo()+ assert backend.calls, "generation never ran"+ return backend.calls[0]["messages"]+++def test_a_historical_image_stays_on_the_turn_that_sent_it_without_tools():+ """The plain route attached the thread's latest picture to the newest question on+ every request, so the prompt prefix holding it was never shared between turns."""+ # A template-less processor still places the image: the gate is renders_image.+ sent = _plain_route_messages({"template": _CHATML_WITH_TOOLS, "renders_image": True})+ earlier, owning, later = [m for m in sent if m.get("role") == "user"]+ assert [p.get("type") for p in owning["content"]] == ["image", "text"]+ assert owning["content"][1]["text"] == "IMAGE_QUESTION about the picture"+ assert earlier["content"] == "EARLIER_QUESTION with no picture"+ assert later["content"] == "LATER_QUESTION unrelated to it"+++def test_no_image_marker_on_the_plain_route_when_renders_image_is_false():+ """``renders_image`` is the whole gate, and it is read with ``.get``, so a model whose+ capability probe never reported one leaves the thread as strings.++ Named for the key it actually varies. As "..._when_the_render_is_text_only", carrying a+ ``processor_template``, it read as a claim about the render target and asserted nothing+ about it: the same dict without ``renders_image`` passes identically on the commit+ before this one, so it could not have caught the marker firing on a text render.+ """+ sent = _plain_route_messages(+ {"template": _CHATML_WITH_TOOLS, "processor_template": _CHATML_WITH_TOOLS}+ )+ assert all(isinstance(m.get("content"), str) for m in sent if m.get("role") == "user")++ # And with the gate open, the same thread is marked: the assertion above is about+ # renders_image, not about the processor_template sitting next to it.+ marked = _plain_route_messages(+ {+ "template": _CHATML_WITH_TOOLS,+ "processor_template": _CHATML_WITH_TOOLS,+ "renders_image": True,+ }+ )+ owning = [m for m in marked if m.get("role") == "user"][1]+ assert [p.get("type") for p in owning["content"]] == ["image", "text"]++def test_a_tool_loop_replay_is_wrapped_for_a_part_based_processor():"""A parts-expecting processor template raises while iterating replayed assistant androle="tool" turns left as bare strings, turning a valid request into a 500 (#10092)."""