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 GGUF vision chat: reuse the image normalization for history images sent again (#17263)
Daniel Hanba14177cffb5
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 7dc5ff54bc1..4a16c025c26 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -42029,6 +42029,42 @@ def _llama_image_data_url(raw: bytes) -> str:return f"data:image/png;base64,{_image_bytes_to_png_b64(raw)}"+# Chat history images are sent again on every turn and the result depends only on the payload.+_LLAMA_IMAGE_MEMO: "collections.OrderedDict[bytes, str]" = collections.OrderedDict()+_LLAMA_IMAGE_MEMO_MAX_CHARS = 64 * 1024 * 1024+# Also bound the entry count: a pass-through entry stores only its short prefix.+_LLAMA_IMAGE_MEMO_MAX_ENTRIES = 256+_llama_image_memo_chars = 0+_llama_image_memo_lock = threading.Lock()+++def _llama_image_data_url_from_b64(b64data: str) -> str:+ """_llama_image_data_url(base64.b64decode(b64data)), remembering recent successful results; failures raise as before"""+ global _llama_image_memo_chars+ key = _hashlib.sha256(b64data.encode("utf-8", "surrogatepass")).digest()+ with _llama_image_memo_lock:+ kept = _LLAMA_IMAGE_MEMO.get(key)+ if kept is not None:+ _LLAMA_IMAGE_MEMO.move_to_end(key)+ if kept is not None:+ # A bare prefix means the payload passed through unchanged.+ return kept + b64data if kept.endswith(",") else kept+ data_url = _llama_image_data_url(base64.b64decode(b64data))+ prefix = data_url[: len(data_url) - len(b64data)]+ kept = prefix if data_url.endswith(b64data) and prefix.endswith(";base64,") else data_url+ with _llama_image_memo_lock:+ if key not in _LLAMA_IMAGE_MEMO and len(kept) <= _LLAMA_IMAGE_MEMO_MAX_CHARS:+ _LLAMA_IMAGE_MEMO[key] = kept+ _llama_image_memo_chars += len(kept)+ while (+ _llama_image_memo_chars > _LLAMA_IMAGE_MEMO_MAX_CHARS+ or len(_LLAMA_IMAGE_MEMO) > _LLAMA_IMAGE_MEMO_MAX_ENTRIES+ ):+ _, dropped = _LLAMA_IMAGE_MEMO.popitem(last = False)+ _llama_image_memo_chars -= len(dropped)+ return data_url++# Match llama-server's per-image limit and add a per-request budget._REMOTE_IMAGE_MAX_BYTES = 10 * 1024 * 1024_REMOTE_IMAGE_REQUEST_BUDGET_BYTES = 32 * 1024 * 1024@@ -42266,8 +42302,7 @@ def _normalize_openai_image_parts_for_llama(openai_messages: list[dict], on_imagtry:_, b64data = url.split(",", 1)- raw = base64.b64decode(b64data)- data_url = _llama_image_data_url(raw)+ data_url = _llama_image_data_url_from_b64(b64data)except Exception:raise HTTPException(status_code = 400,@@ -46880,8 +46915,7 @@ def _openai_messages_for_passthrough(if normalize_images:try:- raw = base64.b64decode(payload.image_base64)- data_url = _llama_image_data_url(raw)+ data_url = _llama_image_data_url_from_b64(payload.image_base64)except Exception:raise HTTPException(status_code = 400,diff --git a/studio/backend/tests/test_chat_image_exif_orientation.py b/studio/backend/tests/test_chat_image_exif_orientation.pyindex aa7cea9c2b6..5a483fe31f5 100644--- a/studio/backend/tests/test_chat_image_exif_orientation.py+++ b/studio/backend/tests/test_chat_image_exif_orientation.py@@ -94,6 +94,13 @@ def test_llama_server_gets_a_tagged_png_upright():def test_a_tagged_png_is_decoded_once(monkeypatch):+ import collections++ import routes.inference as inference++ # A fresh memo: an earlier test may already have normalized this image.+ monkeypatch.setattr(inference, "_LLAMA_IMAGE_MEMO", collections.OrderedDict())+ monkeypatch.setattr(inference, "_llama_image_memo_chars", 0)opened = []real_open = Image.opendiff --git a/studio/backend/tests/test_llama_image_memo.py b/studio/backend/tests/test_llama_image_memo.pynew file mode 100644index 00000000000..1f7ca4fc920--- /dev/null+++ b/studio/backend/tests/test_llama_image_memo.py@@ -0,0 +1,102 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""History images sent again on a later turn reuse the earlier normalization instead of decoding the image again."""++import base64+import copy+import io++import pytest+from fastapi import HTTPException+from PIL import Image++from routes import inference as inf+++def _b64(img, fmt):+ buf = io.BytesIO()+ img.save(buf, format = fmt)+ return base64.b64encode(buf.getvalue()).decode("ascii")+++def _payloads():+ opaque_png = _b64(Image.new("RGB", (32, 24), (10, 200, 30)), "PNG")+ jpeg = _b64(Image.new("RGB", (32, 24), (200, 10, 30)), "JPEG")+ transparent = Image.new("RGBA", (16, 16), (0, 0, 255, 255))+ transparent.putpixel((0, 0), (0, 0, 0, 0))+ gif = _b64(Image.new("RGB", (8, 8), (1, 2, 3)), "GIF")+ return [opaque_png, jpeg, _b64(transparent, "PNG"), gif]++[email protected](autouse = True)+def _fresh_memo(monkeypatch):+ monkeypatch.setattr(inf, "_LLAMA_IMAGE_MEMO", inf.collections.OrderedDict())+ monkeypatch.setattr(inf, "_llama_image_memo_chars", 0)+++def _history(payloads):+ return [+ {+ "role": "user",+ "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64," + p}}],+ }+ for p in payloads+ ]+++def test_a_repeated_history_is_normalized_once_with_the_same_result(monkeypatch):+ payloads = _payloads()+ expected = [inf._llama_image_data_url(base64.b64decode(p)) for p in payloads]+ calls = []+ original = inf._llama_image_data_url++ def spy(raw):+ calls.append(len(raw))+ return original(raw)++ monkeypatch.setattr(inf, "_llama_image_data_url", spy)+ for turn in range(3):+ messages = copy.deepcopy(_history(payloads))+ assert inf._normalize_openai_image_parts_for_llama(messages) is True+ assert [m["content"][0]["image_url"]["url"] for m in messages] == expected+ assert len(calls) == len(payloads)+++def test_a_payload_that_fails_is_tried_again_and_still_rejected(monkeypatch):+ calls = []+ original = inf._llama_image_data_url++ def spy(raw):+ calls.append(1)+ return original(raw)++ monkeypatch.setattr(inf, "_llama_image_data_url", spy)+ bad = base64.b64encode(b"not an image").decode("ascii")+ for _ in range(2):+ with pytest.raises(HTTPException) as err:+ inf._normalize_openai_image_parts_for_llama(_history([bad]))+ assert err.value.status_code == 400+ assert len(calls) == 2+++def test_the_memo_stays_within_its_budget(monkeypatch):+ payloads = _payloads()+ monkeypatch.setattr(inf, "_LLAMA_IMAGE_MEMO_MAX_CHARS", 200)+ for p in payloads:+ inf._llama_image_data_url_from_b64(p)+ assert inf._llama_image_memo_chars == sum(len(v) for v in inf._LLAMA_IMAGE_MEMO.values())+ assert inf._llama_image_memo_chars <= 200+ for p in payloads:+ assert inf._llama_image_data_url_from_b64(p) == inf._llama_image_data_url(+ base64.b64decode(p)+ )+++def test_the_memo_keeps_a_bounded_number_of_entries(monkeypatch):+ monkeypatch.setattr(inf, "_LLAMA_IMAGE_MEMO_MAX_ENTRIES", 3)+ payloads = [_b64(Image.new("RGB", (4, 4), (i, 0, 0)), "PNG") for i in range(10)]+ for p in payloads:+ inf._llama_image_data_url_from_b64(p)+ assert len(inf._LLAMA_IMAGE_MEMO) == 3+ assert inf._llama_image_memo_chars == sum(len(v) for v in inf._LLAMA_IMAGE_MEMO.values())