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
fix(studio): restore parallel vision chat slots (#9842)
Kenshic2c3535fa978
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 81a84e00f5d..0dbf05791ab 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -5427,6 +5427,9 @@ class LlamaCppBackend:# the GGUF alone can tell us.self._has_video_input: bool = Falseself._mmproj_has_audio: bool = False # clip.has_audio_encoder, set at load+ # clip.projector_type, set at load: the family whose image-token ceiling KV+ # admission sizes an image against.+ self._mmproj_projector_type: Optional[str] = None# clip.has_vision_encoder, set at load; True keeps an undeclared projector capable.self._mmproj_accepts_image: bool = True# Monotonic timestamp set in _kill_process; read by load_model@@ -19574,13 +19577,20 @@ class LlamaCppBackend:if (_pv_mmproj_unpinnable or (disable_vision and not _dv_env_mmproj_kept))else (os.environ.get("LLAMA_ARG_MMPROJ") or ""))+ self._mmproj_projector_type = Noneif launch_mmproj_path or os.path.isfile(_mmproj_probe):try:- from utils.models.gguf_metadata import mmproj_capabilities+ from utils.models.gguf_metadata import (+ mmproj_capabilities,+ read_mmproj_projector_type,+ )has_audio, accepts_image = mmproj_capabilities(_mmproj_probe)self._mmproj_has_audio = has_audioself._mmproj_accepts_image = accepts_image+ # The family name, so KV admission can look up how many tokens+ # one image may become instead of assuming a ceiling.+ self._mmproj_projector_type = read_mmproj_projector_type(_mmproj_probe)except Exception as e:logger.debug(f"mmproj capability read failed: {e}")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex f5b4dfc8fea..3c020f426eb 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1638,23 +1638,159 @@ def _openai_llama_admission_extra_prompt_tokens(payload) -> int:return extra-def _openai_llama_admission_media_tokens(payload) -> int:- """Media the request carries in Unsloth's legacy top-level fields, in tokens.+# An upper bound per image, not an estimate: under-reserving hands out a slot the cache+# cannot back, which is the overcommit #9392 exists to stop.+#+# 4096 is llama.cpp's default Qwen-VL embedding cap (the projector resizes to its own+# pixel limits, so transport size never enters into it), but mtmd wraps the embeddings+# in delimiters. Measured on llama-server b10639: 4098 for a 2048x2048 image on+# Qwen3-VL-4B, 258 on Gemma 3 4B. The wrapper allowance is far above the two measured+# so longer delimiters still fit. Only the DEFAULT, though: a load may raise the cap+# (`_openai_llama_admission_image_tokens`), and a projector whose embeddings exceed it+# on their own (tiling or multi-crop families) still wants an allowance read off the+# loaded mmproj rather than a bigger number here.+_OPENAI_LLAMA_ADMISSION_IMAGE_EMBEDDING_CAP = 4096+_OPENAI_LLAMA_ADMISSION_IMAGE_WRAPPER_TOKENS = 128+_OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS = (+ _OPENAI_LLAMA_ADMISSION_IMAGE_EMBEDDING_CAP + _OPENAI_LLAMA_ADMISSION_IMAGE_WRAPPER_TOKENS+)+++def _extra_args_image_max_tokens(extra_args) -> Optional[int]:+ """The ``--image-max-tokens N`` a load passed through, or None. Last wins.++ Both spellings, since llama-server accepts ``--flag N`` and ``--flag=N``.+ """+ args = [str(arg) for arg in (extra_args or ())]+ found = None+ for index, raw in enumerate(args):+ if raw.startswith("--image-max-tokens="):+ value = raw.partition("=")[2]+ elif raw == "--image-max-tokens" and index + 1 < len(args):+ value = args[index + 1]+ else:+ continue+ parsed = _positive_int_or_none(value)+ if parsed is not None:+ found = parsed+ return found+++# Embeddings one image may become, per projector family, from llama.cpp's own+# `set_limit_image_tokens` calls in tools/mtmd/clip.cpp; the keys are the+# `clip.projector_type` strings in clip-impl.h, which is what the mmproj GGUF carries.+# There is no universal default -- `--image-max-tokens` documents itself as "read from+# model" -- and the spread is three orders of magnitude, so assuming any one number+# under-reserves somebody. A family absent here falls back to the default ceiling+# below, which is the pre-existing behaviour rather than a new guess.+_MMPROJ_IMAGE_TOKEN_MAX = {+ "qwen2vl_merger": 4096,+ "qwen2.5vl_merger": 4096,+ "qwen3vl_merger": 4096,+ "glm4v": 4096,+ "kimik25": 4096,+ "muse-glimmer": 4096,+ "youtuvl": 62500,+ "hunyuanvl": 16384,+ "pixtral": 1024,+ "lightonocr": 1024,+ "kimivl": 1024,+ "minimax_m3": 576,+ "gemma4v": 280,+ "gemma4uv": 280,+ "lfm2": 256,+}+++def _openai_llama_admission_image_tokens(llama_backend) -> int:+ """Per-image KV allowance for the backend that is actually running.++ Two things move the ceiling off the default. The loaded projector sets its own:+ measured on b10639, a max-resolution image is 4098 KV positions on Qwen3-VL-4B and+ 258 on Gemma 3 4B, and clip.cpp's own table runs from 256 (lfm2) to 62500 (youtuvl).+ And ``--image-max-tokens`` is not an Unsloth-managed flag, so ``llama_extra_args``+ forwards one verbatim: with ``--image-max-tokens 8192`` that same Qwen3-VL image+ costs 8102.++ Takes the LARGER of the two rather than trusting the flag, because llama-server+ applies it only to dynamic-resolution projectors -- a low cap against a fixed+ resolution one is ignored, and believing it would reserve less than the image costs.+ Over-reserving is the safe direction; under-reserving hands out a slot the cache+ cannot back.+ """+ projector = getattr(llama_backend, "_mmproj_projector_type", None)+ known = _MMPROJ_IMAGE_TOKEN_MAX.get(str(projector).strip().lower()) if projector else None+ cap = max(+ known or _OPENAI_LLAMA_ADMISSION_IMAGE_EMBEDDING_CAP,+ _extra_args_image_max_tokens(getattr(llama_backend, "_extra_args", None)) or 0,+ )+ return cap + _OPENAI_LLAMA_ADMISSION_IMAGE_WRAPPER_TOKENS+++def _openai_llama_admission_messages_for_estimate(messages) -> tuple[list[dict], int]:+ """Remove image bytes before estimating the textual part of a prompt.++ mtmd turns an image into model-specific embedding tokens, so its base64 transport+ is neither prompt text nor a proxy for that count. Keep each image part's shape for+ the JSON estimate and return the count, so the caller can add a bounded allowance.+ """+ estimate_messages = []+ image_parts = 0+ for message in messages:+ # exclude_none like every other dump here, including the generation paths this+ # predicts: the five unset optionals on ChatMessage otherwise serialise as+ # `"name": null` and get priced as prompt text (34 tokens for a two-key message+ # against 8), reserving KV for punctuation that is never sent.+ message_dict = (+ message if isinstance(message, dict) else message.model_dump(exclude_none = True)+ )+ estimate_message = dict(message_dict)+ content = message_dict.get("content")+ if isinstance(content, list):+ estimate_content = []+ for part in content:+ if not isinstance(part, dict) or part.get("type") != "image_url":+ estimate_content.append(part)+ continue++ image_parts += 1+ image_url = part.get("image_url")+ compact_image_url = {"url": "[image]"}+ if isinstance(image_url, dict) and image_url.get("detail") is not None:+ compact_image_url["detail"] = image_url["detail"]+ estimate_content.append(+ {+ "type": "image_url",+ "image_url": compact_image_url,+ }+ )+ estimate_message["content"] = estimate_content+ estimate_messages.append(estimate_message)+ return estimate_messages, image_parts- Unsloth's own composer sends every attachment as ``image_base64`` /- ``audio_base64`` / ``video_base64``, never as ``messages`` content parts, and the- generation path splices them into the prompt AFTER this estimate is taken- (``_openai_messages_for_gguf_chat``, ``_inject_audio_part``,- ``_inject_video_part``). Charging only ``messages`` therefore priced an image at- zero while llama.cpp's mtmd embeddings occupy real KV positions, so two- media-heavy chats with a line of text each were admitted against a cache that- holds one.- Sized as the same media inlined as a data URL is already sized, so the two- spellings of one request cost the same rather than 30x apart.+def _openai_llama_admission_media_tokens(+ payload,+ *,+ message_image_parts: int = 0,+ image_tokens: int = _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS,+) -> int:+ """Estimate media KV usage without charging transport bytes as prompt tokens.++ Charges the legacy top-level image on exactly the condition both builders splice it+ on, ``_legacy_image_is_distinct``: Studio echoes one image into both spellings, so+ charging that twice reserves it twice, while a legacy image the messages do not+ already carry is a second image really sent. The allowance is per-image rather than+ per-byte because the real mtmd count follows the loaded projector, not base64 length.++ Audio and video keep the old top-level accounting until they have a model-specific+ estimate; this is scoped to the image path that regressed vision concurrency."""extra = 0- for attribute in ("image_base64", "audio_base64", "video_base64"):+ extra += max(0, message_image_parts) * image_tokens+ if _legacy_image_is_distinct(payload):+ extra += image_tokens+ for attribute in ("audio_base64", "video_base64"):value = getattr(payload, attribute, None)if isinstance(value, str) and value:extra += max(1, len(value) // 4)@@ -1667,6 +1803,7 @@ def _openai_llama_admission_tokens(budget: Optional[int],capacity: int,tool_loop: bool = False,+ image_tokens: int = _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS,) -> Optional[int]:"""KV a request will occupy: what is sent, plus what it may generate.@@ -1683,11 +1820,16 @@ def _openai_llama_admission_tokens(messages = getattr(payload, "messages", None)if isinstance(messages, list) and messages:try:- prompt_tokens = estimate_messages_tokens_dense(- [m if isinstance(m, dict) else m.model_dump() for m in messages]+ estimate_messages, message_image_parts = _openai_llama_admission_messages_for_estimate(+ messages)+ prompt_tokens = estimate_messages_tokens_dense(estimate_messages)prompt_tokens += _openai_llama_admission_extra_prompt_tokens(payload)- prompt_tokens += _openai_llama_admission_media_tokens(payload)+ prompt_tokens += _openai_llama_admission_media_tokens(+ payload,+ message_image_parts = message_image_parts,+ image_tokens = image_tokens,+ )except Exception:prompt_tokens = Noneelse:@@ -1756,6 +1898,7 @@ def _openai_llama_admission_reserve(budget = budget,capacity = capacity,tool_loop = tool_loop,+ image_tokens = _openai_llama_admission_image_tokens(llama_backend),)if payload is not Noneelse None,@@ -16342,26 +16485,42 @@ def _legacy_image_is_distinct(payload) -> bool:against that one value alone: matching any image in the thread let a clientresend an older image, or an assistant's, and hid a real attachment."""- if not payload.image_base64:+ image = getattr(payload, "image_base64", None)+ if not image:return False- return _latest_user_image_payload(payload.messages) != payload.image_base64+ return _latest_user_image_payload(getattr(payload, "messages", None)) != image-def _latest_user_image_payload(messages: list) -> "Optional[str]":+def _latest_user_image_payload(messages) -> "Optional[str]":"""The value ``findLatestUserImageBase64`` would put in ``image_base64``.Its scan order: newest turn first, user turns only, first image part, ``data:``prefix stripped the way :func:`_extract_content_parts` strips it. A part thatyields nothing does not end the scan, since the frontend walks on past a falsyread; stopping on one refused Studio's echo of a valid earlier image.++ Reads models and plain dicts alike: the generation paths only ever hold models, but+ the KV admission estimate sees whatever the caller passed, and both have to answer+ "is the legacy field an echo?" the same way or the reservation stops matching the+ prompt."""- for msg in reversed(messages):- if msg.role != "user" or not isinstance(msg.content, list):+ for msg in reversed(list(messages or ())):+ role = msg.get("role") if isinstance(msg, dict) else getattr(msg, "role", None)+ content = msg.get("content") if isinstance(msg, dict) else getattr(msg, "content", None)+ if role != "user" or not isinstance(content, list):continue- for part in msg.content:- if part.type != "image_url":+ for part in content:+ if isinstance(part, dict):+ if part.get("type") != "image_url":+ continue+ image_url = part.get("image_url")+ url = image_url.get("url") if isinstance(image_url, dict) else image_url+ else:+ if getattr(part, "type", None) != "image_url":+ continue+ url = getattr(getattr(part, "image_url", None), "url", None)+ if not isinstance(url, str):continue- url = part.image_url.urlencoded = url.partition(",")[2] if url.startswith("data:") else urlif encoded:return encoded@@ -27689,12 +27848,18 @@ def _openai_messages_for_passthrough(payload) -> list[dict]:image is re-encoded to PNG (llama-server's stb_image has limited formatsupport) and spliced into the last user message as an OpenAI ``image_url``content part so vision + function-calling requests work transparently.++ Only when it is a real second image, matching ``_openai_messages_for_gguf_chat`` and+ what admission charges for. Studio echoes the current image into both spellings, so+ splicing that unconditionally sent a tools or response_format request two copies+ against a reservation for one: 4417 reserved against 8466 charged, which overcommits+ the KV cache wherever the slot count lets that gap accumulate."""messages = _strip_provider_synthetic_tool_history(_drop_empty_assistant_sentinels([m.model_dump(exclude_none = True) for m in payload.messages]))- if not payload.image_base64:+ if not _legacy_image_is_distinct(payload):return messagestry:@@ -27779,12 +27944,10 @@ def _openai_messages_for_gguf_chat(payload, is_vision: bool) -> tuple[list[dict])))- has_message_image = any(- isinstance(msg.get("content"), list)- and any(part.get("type") == "image_url" for part in msg["content"])- for msg in messages- )- if payload.image_base64 and not has_message_image:+ # Distinctness, not "the messages carry no image": Studio's echo is byte-equal to a+ # part already here and must not be spliced twice, but a legacy image the thread+ # does not hold is a real attachment. Admission charges on the same predicate.+ if _legacy_image_is_distinct(payload):# Legacy bytes can be any format; the normalizer below sniffs and# re-encodes to PNG, so the declared mime is rewritten anyway.image_part = {diff --git a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.pyindex afc41b6ae1f..16209bd63f3 100644--- a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py+++ b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py@@ -1,12 +1,12 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Two holes in the KV reservation the estimator has to charge for.+"""Media and tool-loop cases that the KV reservation has to charge for.-Media: Unsloth's composer sends attachments in the legacy top-level ``image_base64`` /-``audio_base64`` / ``video_base64`` fields, and the generation path splices them into-the prompt AFTER admission is decided. Charging only ``messages`` priced an image at-zero while llama.cpp's mtmd embeddings take real KV positions.+Media: Unsloth's composer sends the current image in both a message-level+``image_url`` part and the legacy top-level ``image_base64`` field. The generation+path splices legacy media into the prompt AFTER admission is decided. Admission must+charge the resulting image once, without treating base64 bytes as prompt text.Tool loop: the server-side loop opens on ``enable_tools`` / ``mcp_enabled`` / the CLIpolicy / a checkpoint repair, none of which require a client ``tools`` array, so a@@ -16,7 +16,10 @@ estimate for a lease that runs up to 25 growing rounds.import base64-from routes.inference import _openai_llama_admission_tokens+from routes.inference import (+ _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS,+ _openai_llama_admission_tokens,+)class _Payload:@@ -31,6 +34,18 @@ def _image_b64(kib: int = 200) -> str:return base64.b64encode(b"\x89PNG" + b"x" * (kib * 1024)).decode()+# Two real, decodable, DIFFERENT PNGs. The builders decode and re-encode, unlike the+# estimator, so the synthetic fixture above cannot reach them; and the pair has to+# differ for a distinct-legacy-image case to be distinct at all.+_TINY_PNG = (+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNgYGAAAAAEAAH2FzhVAAAAAElFTkSuQmCC"+)+_OTHER_PNG = (+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVR4nGP8z8DAwMDAxMDAwMDAAAANHQED"+ "asKb6QAAAABJRU5ErkJggg=="+)++class TestMediaIsCharged:def test_legacy_image_costs_what_the_same_image_inline_costs(self):image = _image_b64()@@ -54,11 +69,257 @@ class TestMediaIsCharged:],max_tokens = 128,)- legacy_cost = _openai_llama_admission_tokens(legacy, budget = 4096, capacity = 4)- inline_cost = _openai_llama_admission_tokens(inline, budget = 4096, capacity = 4)- # Before the fix this was 139 against 4096: the same request, one spelling- # charged the whole cache and the other charged its 13 characters of text.- assert legacy_cost == inline_cost+ # Clear of the clamp: at 4096 `max(1, min(budget, ...))` pinned both sides to the+ # budget, so they agreed whatever the estimator did and this proved nothing.+ legacy_cost = _openai_llama_admission_tokens(legacy, budget = 1_000_000, capacity = 4)+ inline_cost = _openai_llama_admission_tokens(inline, budget = 1_000_000, capacity = 4)+ # The wire spelling must not change the commitment. Not to the token: inline+ # really does send a content-part wrapper legacy does not, and the marker is+ # itself a little JSON. What must not survive is the 30x gap between pricing an+ # image at its base64 length and at its text.+ assert abs(legacy_cost - inline_cost) <= 64, (legacy_cost, inline_cost)+ assert max(legacy_cost, inline_cost) < 2 * _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS++ def test_studio_image_echo_is_charged_once_and_is_bounded(self):+ image = _image_b64(1024)+ inline_messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this?"},+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{image}"},+ },+ ],+ }+ ]+ dual = _Payload(+ messages = inline_messages,+ image_base64 = image,+ max_tokens = 128,+ )+ inline = _Payload(messages = inline_messages, max_tokens = 128)++ # Clear of the clamp: at 65536 a 1 MiB image priced as prompt text pinned both+ # sides to the budget, so `dual == inline` held on the unfixed estimator too.+ dual_cost = _openai_llama_admission_tokens(dual, budget = 1_000_000, capacity = 4)+ inline_cost = _openai_llama_admission_tokens(inline, budget = 1_000_000, capacity = 4)++ assert dual_cost == inline_cost+ assert dual_cost < 2 * _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS, (+ "the echo must be charged once, not once per spelling"+ )+ assert dual_cost >= _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS, (+ "image bytes must be bounded but still charged"+ )++ def test_every_builder_forwards_exactly_what_admission_charged(self):+ """The reservation is only a bound if it counts the images actually sent.++ Studio echoes one image into both spellings. The GGUF builder always dropped the+ echo; `_openai_messages_for_passthrough` (taken when a client sends ``tools`` or+ a ``response_format``) spliced it in regardless, sending two copies against a+ reservation for one: 4417 reserved against 8466 charged on llama-server b10639.++ The echo is the only thing that may be dropped. A legacy image the thread does+ not already hold is a real attachment, so both builders send it and admission+ charges for it -- keyed on the same predicate, or the two answers drift again.+ """+ from models.inference import ChatCompletionRequest+ from routes.inference import (+ _openai_llama_admission_media_tokens,+ _openai_llama_admission_messages_for_estimate,+ _openai_messages_for_gguf_chat,+ _openai_messages_for_passthrough,+ )++ image = _TINY_PNG+ inline_part = {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{image}"},+ }+ shapes = {+ "studio dual": ChatCompletionRequest(+ model = "m",+ max_tokens = 128,+ messages = [+ {+ "role": "user",+ "content": [{"type": "text", "text": "what is this?"}, inline_part],+ }+ ],+ image_base64 = image,+ ),+ "inline only": ChatCompletionRequest(+ model = "m",+ max_tokens = 128,+ messages = [+ {+ "role": "user",+ "content": [{"type": "text", "text": "what is this?"}, inline_part],+ }+ ],+ ),+ "legacy only": ChatCompletionRequest(+ model = "m",+ max_tokens = 128,+ messages = [{"role": "user", "content": "what is this?"}],+ image_base64 = image,+ ),+ # An older image in history plus a genuinely different one attached to this+ # turn through the legacy field: two images, and both must be charged.+ "history image plus a distinct legacy attachment": ChatCompletionRequest(+ model = "m",+ max_tokens = 128,+ messages = [+ {+ "role": "user",+ "content": [{"type": "text", "text": "and this?"}, inline_part],+ }+ ],+ image_base64 = _OTHER_PNG,+ ),+ }++ def _forwarded(messages):+ return sum(+ 1+ for msg in messages+ if isinstance(msg.get("content"), list)+ for part in msg["content"]+ if isinstance(part, dict) and part.get("type") == "image_url"+ )++ for name, payload in shapes.items():+ _, message_image_parts = _openai_llama_admission_messages_for_estimate(payload.messages)+ billed = (+ _openai_llama_admission_media_tokens(+ payload, message_image_parts = message_image_parts+ )+ // _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS+ )+ for builder_name, messages in (+ ("gguf chat", _openai_messages_for_gguf_chat(payload, True)[0]),+ ("passthrough", _openai_messages_for_passthrough(payload)),+ ):+ assert _forwarded(messages) == billed, (+ f"{name} via {builder_name}: forwarded {_forwarded(messages)} "+ f"image(s) but admission charged for {billed}"+ )++ def test_the_allowance_bounds_a_real_projector(self):+ """The per-image charge is an upper bound, not an estimate.++ Measured on llama-server b10639: 4098 KV positions for a 2048x2048 image on+ Qwen3-VL-4B (the 4096-embedding cap plus two mtmd delimiters) and 258 on Gemma 3+ 4B, at every resolution and encoded size. A flat 4096 sat below the Qwen figure,+ and reserving less than a request costs is what lets two collide in one cache.+ """+ measured_worst_case = {"qwen3-vl-4b": 4098, "gemma-3-4b": 258}+ for model, tokens in measured_worst_case.items():+ assert _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS >= tokens, (+ f"per-image allowance under-reserves {model}"+ )++ def test_the_allowance_follows_a_raised_image_token_cap(self):+ """A load can raise the projector ceiling, and the reservation has to follow it.++ ``--image-max-tokens`` is not Unsloth-managed, so ``llama_extra_args`` forwards+ it verbatim. Measured on b10639 with ``--image-max-tokens 8192``: a 4096x4096+ Qwen3-VL image costs 8102, against 4098 at the default. Reserving the default+ against that backend admits concurrent requests the cache cannot hold.+ """+ from routes.inference import (+ _MMPROJ_IMAGE_TOKEN_MAX,+ _openai_llama_admission_image_tokens,+ )++ class _Backend:+ def __init__(+ self,+ extra_args = None,+ projector = None,+ ):+ self._extra_args = extra_args+ self._mmproj_projector_type = projector++ assert _openai_llama_admission_image_tokens(_Backend()) == (+ _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS+ )+ for spelling in (["--image-max-tokens", "8192"], ["--image-max-tokens=8192"]):+ allowance = _openai_llama_admission_image_tokens(_Backend(spelling))+ assert allowance > _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS+ assert allowance >= 8102, f"{spelling} under-reserves the measured cost"+ # Junk must not be mistaken for a cap, and must not raise.+ for junk in (["--image-max-tokens"], ["--image-max-tokens", "abc"], ["-c", "40000"]):+ assert _openai_llama_admission_image_tokens(_Backend(junk)) == (+ _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS+ )++ # Every family llama.cpp gives its own ceiling must be bounded, including the+ # ones far above the default: youtuvl is 62500 and hunyuanvl 16384, so a flat+ # default would have reserved a fraction of what one image really costs.+ for projector, ceiling in _MMPROJ_IMAGE_TOKEN_MAX.items():+ assert _openai_llama_admission_image_tokens(_Backend(projector = projector)) >= ceiling+ assert _openai_llama_admission_image_tokens(_Backend(projector = "youtuvl")) >= 62500+ # A projector with a small ceiling reserves near it rather than the default.+ assert _openai_llama_admission_image_tokens(_Backend(projector = "lfm2")) < 1024+ # An unknown family keeps the default rather than inventing a number.+ assert _openai_llama_admission_image_tokens(_Backend(projector = "nope")) == (+ _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS+ )+ # The flag is only honoured by dynamic-resolution projectors, so a LOW cap must+ # not talk the reservation below what a fixed-resolution one really costs.+ assert (+ _openai_llama_admission_image_tokens(+ _Backend(["--image-max-tokens", "16"], projector = "qwen3vl_merger")+ )+ >= _MMPROJ_IMAGE_TOKEN_MAX["qwen3vl_merger"]+ )++ def test_two_large_studio_image_chats_can_be_admitted_together(self):+ """A large base64 transport must not turn each vision request into a full-cache lease."""+ import asyncio++ from core.inference.llama_admission import LlamaAdmissionConfig, LlamaAdmissionQueue++ async def scenario():+ queue = LlamaAdmissionQueue("media")+ config = LlamaAdmissionConfig()+ image = _image_b64(1024)+ leases = []+ for _ in range(2):+ payload = _Payload(+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "describe"},+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{image}"},+ },+ ],+ }+ ],+ image_base64 = image,+ max_tokens = 128,+ )+ reservation = queue.reserve(+ capacity = 4,+ config = config,+ budget = 12_000,+ tokens = _openai_llama_admission_tokens(payload, budget = 12_000, capacity = 4),+ )+ leases.append(reservation.lease_nowait())+ admitted = [lease is not None for lease in leases]+ for lease in leases:+ if lease is not None:+ lease.release()+ return admitted++ assert asyncio.run(scenario()) == [True, True]def test_two_image_chats_are_not_both_admitted(self):"""The live failure, with images instead of text."""@@ -88,8 +349,8 @@ class TestMediaIsCharged:first, second = asyncio.run(scenario())assert first is not None, "the first image chat owns the cache"- # A 4 KiB image is ~5.4k base64 characters, about 1365 tokens on top of a- # 2048 cache that already holds one such request: the second must queue.+ # The conservative per-image allowance alone is larger than this tiny cache,+ # so the second request must still queue rather than overcommit it.assert second is Nonedef test_audio_and_video_are_charged_too(self):diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.pyindex 0d18b3b1ad6..73322f70d4e 100644--- a/studio/backend/utils/models/gguf_metadata.py+++ b/studio/backend/utils/models/gguf_metadata.py@@ -595,6 +595,16 @@ def read_mmproj_audio_capability(path: str) -> Optional[bool]:return _read_gguf_bool(path, "clip.has_audio_encoder")+def read_mmproj_projector_type(path: str) -> Optional[str]:+ """``clip.projector_type`` from an mmproj GGUF, or None if absent/unreadable.++ The family name llama.cpp keys its per-projector image-token limits on+ (``qwen3vl_merger``, ``gemma3``, ``pixtral``, ...), so a caller sizing the KV an+ image will occupy can look the ceiling up instead of assuming one.+ """+ return _read_gguf_string(path, "clip.projector_type")++def read_mmproj_vision_capability(path: str) -> Optional[bool]:"""``clip.has_vision_encoder`` from an mmproj GGUF: ``True``/``False`` ifpresent, ``None`` if absent/unreadable."""