Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Servers: keep image embeddings stable across requests so the prompt cache survives an image

YanissAmza4a84b90f9b6
diff --git a/tools/glm/image_cache.py b/tools/glm/image_cache.py
new file mode 120000
index 0000000..8991ae3
--- /dev/null
+++ b/tools/glm/image_cache.py
@@ -0,0 +1 @@
+../strix_halo/image_cache.py
\ No newline at end of file
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index a63d351..aaaac9a 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -6,8 +6,6 @@ import traceback
import argparse
import asyncio
import base64
-import collections
-import hashlib
import io
import json
import os
@@ -27,6 +25,7 @@ sys.path.append(str(Path(__file__).resolve().parent.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py
from serve_metrics import Metrics
+from image_cache import ImageEmbeddingCache, digest
DEFAULT_MODEL = "~/models/glm53-exl3-td205"
EH_SIDECAR_DEFAULT = "~/models/glm53-mtp-eh-proj-bf16.safetensors"
@@ -265,7 +264,6 @@ DEFAULT_SAMPLER_KW: dict = json.loads(os.environ.get("SERVE_SAMPLER_KW", "{}") o
# which the tokenizer expands to <|begin_of_image|> + one slot per vision token + <|end_of_image|>.
IMAGE_TRIPLE = "<|begin_of_image|><|image|><|end_of_image|>"
MAX_IMAGE_BYTES = 32 * 1024**2
-IMAGE_CACHE_SIZE = 8 # decoded embeddings kept by content hash, so a later turn re-sending the image reuses the KV cache
def _bad(reason: str) -> web.HTTPBadRequest:
@@ -316,7 +314,7 @@ def load_image(url: str) -> tuple[Any, str]:
if len(raw) > MAX_IMAGE_BYTES:
raise _bad("image too large")
try:
- return Image.open(io.BytesIO(raw)).convert("RGB"), hashlib.sha256(raw).hexdigest()
+ return Image.open(io.BytesIO(raw)).convert("RGB"), digest(raw)
except Exception as exc: # noqa: BLE001
raise _bad(f"cannot decode image: {exc}") from exc
@@ -351,7 +349,7 @@ class ResidentEngine:
startup_health.stage("drafter weights")
self.draft_model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())
self.vision = None
- self.emb_cache: collections.OrderedDict = collections.OrderedDict()
+ self.emb_cache = ImageEmbeddingCache()
if vision:
self.vision = self._load_vision()
self.supports_vision = self.vision is not None
@@ -390,19 +388,13 @@ class ResidentEngine:
def _embed(self, images: list[tuple[Any, str]]) -> list:
"""One MMEmbedding per image. The same bytes give the same embedding object (same pseudo token ids), so a
- history turn that repeats an image still matches the paged KV cache; one prompt never holds an object twice."""
- out, used = [], set()
- for image, key in images:
- emb = self.emb_cache.get(key) if key not in used else None
- if emb is None:
- emb = self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=image)
- self.emb_cache[key] = emb
- self.emb_cache.move_to_end(key)
- used.add(key)
- out.append(emb)
- while len(self.emb_cache) > IMAGE_CACHE_SIZE:
- self.emb_cache.popitem(last=False)
- return out
+ history turn that repeats an image still matches the paged KV cache (see image_cache.py)."""
+ def build(image):
+ t0 = time.perf_counter()
+ emb = self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=image)
+ print(f"serve: image {image.size[0]}x{image.size[1]} -> {emb.mm_length} tokens, tower {(time.perf_counter() - t0) * 1000:.0f} ms", flush=True)
+ return emb
+ return self.emb_cache.get_many(images, build)
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, encode_special_tokens=True).numel())
diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.py
index 919761d..e671b44 100644
--- a/tools/glm/test_serve.py
+++ b/tools/glm/test_serve.py
@@ -563,5 +563,43 @@ class ServeTests(unittest.TestCase):
serve.load_image(bad)
+
+class ImageEmbeddingReuseTests(unittest.TestCase):
+ """The same picture must come back as the same embedding object, so the prompt keeps its token ids."""
+
+ def make_engine(self):
+ import itertools
+ import torch
+ from image_cache import ImageEmbeddingCache
+ ids, calls = itertools.count(1_000_000_000, 100), []
+
+ class Emb:
+ def __init__(self):
+ self.first_index = next(ids)
+ self.text_alias = f"<$EMB_{self.first_index}$>"
+ self.mm_length = 3
+ self.embeddings = torch.zeros(3, 4, dtype=torch.half)
+ self.deepstack_embeddings = None
+
+ class Tower:
+ def get_image_embeddings(self, *args, **kw):
+ calls.append(1)
+ return Emb()
+
+ eng = object.__new__(serve.ResidentEngine)
+ eng.emb_cache, eng.vision, eng.tokenizer = ImageEmbeddingCache(), Tower(), None
+ return eng, calls
+
+ def test_embed_reuses_ids_and_encodes_once(self):
+ from PIL import Image
+ eng, calls = self.make_engine()
+ img = Image.new("RGB", (64, 64))
+ a = eng._embed([(img, "k1")])
+ b = eng._embed([(img, "k1"), (img, "k2")])
+ self.assertIs(a[0], b[0])
+ self.assertNotEqual(b[0].first_index, b[1].first_index)
+ self.assertEqual(len(calls), 2)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/mimo/image_cache.py b/tools/mimo/image_cache.py
new file mode 120000
index 0000000..8991ae3
--- /dev/null
+++ b/tools/mimo/image_cache.py
@@ -0,0 +1 @@
+../strix_halo/image_cache.py
\ No newline at end of file
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index 5f3d7cd..1939156 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -16,8 +16,6 @@ import traceback
import argparse
import asyncio
import base64
-import collections
-import hashlib
import io
import json
import os
@@ -37,6 +35,7 @@ sys.path.append(str(Path(__file__).resolve().parent.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py
from serve_metrics import Metrics
+from image_cache import ImageEmbeddingCache, digest
DEFAULT_MODEL = os.path.expanduser("~/models/mimo26-exl3")
DEFAULT_MODEL_ID = "MiMo-2.6-EXL3"
@@ -54,7 +53,6 @@ DEFAULT_TEMPLATE = Path(__file__).with_name("chat_template.jinja")
# <|image_pad|> for the embedding's alias, which the tokenizer expands to one slot per vision token.
IMAGE_PAD = "<|image_pad|>"
MAX_IMAGE_BYTES = 32 * 1024**2
-IMAGE_CACHE_SIZE = 8 # embeddings kept by content hash: a later turn that re-sends the image reuses the KV cache
def _bad(reason: str) -> web.HTTPBadRequest:
@@ -105,7 +103,7 @@ def load_image(url: str) -> tuple[Any, str]:
if len(raw) > MAX_IMAGE_BYTES:
raise _bad("image too large")
try:
- return Image.open(io.BytesIO(raw)).convert("RGB"), hashlib.sha256(raw).hexdigest()
+ return Image.open(io.BytesIO(raw)).convert("RGB"), digest(raw)
except Exception as exc: # noqa: BLE001
raise _bad(f"cannot decode image: {exc}") from exc
@@ -371,7 +369,7 @@ class ResidentEngine:
self.ctx = ctx or config_max_position(self.config)
self.num_draft = self.ndt
self.vision = None
- self.emb_cache: collections.OrderedDict = collections.OrderedDict()
+ self.emb_cache = ImageEmbeddingCache()
if vision:
self.vision = self._load_vision()
self.supports_vision = self.vision is not None
@@ -397,21 +395,13 @@ class ResidentEngine:
def _embed(self, images: list[tuple[Any, str]]) -> list:
"""One MMEmbedding per image. The same bytes give the same embedding object (same pseudo token ids), so a
- history turn that repeats an image still matches the paged KV cache; one prompt never holds an object twice."""
- out, used = [], set()
- for image, key in images:
- emb = self.emb_cache.get(key) if key not in used else None
- if emb is None:
- t0 = time.perf_counter()
- emb = self.vision.get_image_embeddings(image)
- print(f"msrv: image {image.size[0]}x{image.size[1]} -> {emb.mm_length} tokens, tower {(time.perf_counter() - t0) * 1000:.0f} ms", flush=True)
- self.emb_cache[key] = emb
- self.emb_cache.move_to_end(key)
- used.add(key)
- out.append(emb)
- while len(self.emb_cache) > IMAGE_CACHE_SIZE:
- self.emb_cache.popitem(last=False)
- return out
+ history turn that repeats an image still matches the paged KV cache (see image_cache.py)."""
+ def build(image):
+ t0 = time.perf_counter()
+ emb = self.vision.get_image_embeddings(image)
+ print(f"msrv: image {image.size[0]}x{image.size[1]} -> {emb.mm_length} tokens, tower {(time.perf_counter() - t0) * 1000:.0f} ms", flush=True)
+ return emb
+ return self.emb_cache.get_many(images, build)
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, encode_special_tokens=True).numel())
diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.py
index 3b85ebc..950784f 100644
--- a/tools/mimo/test_serve.py
+++ b/tools/mimo/test_serve.py
@@ -592,5 +592,43 @@ class ServeTests(unittest.TestCase):
self.assertEqual(serve.extract_images(msgs), ["a", "b"])
+
+class ImageEmbeddingReuseTests(unittest.TestCase):
+ """The same picture must come back as the same embedding object, so the prompt keeps its token ids."""
+
+ def make_engine(self):
+ import itertools
+ import torch
+ from image_cache import ImageEmbeddingCache
+ ids, calls = itertools.count(1_000_000_000, 100), []
+
+ class Emb:
+ def __init__(self):
+ self.first_index = next(ids)
+ self.text_alias = f"<$EMB_{self.first_index}$>"
+ self.mm_length = 3
+ self.embeddings = torch.zeros(3, 4, dtype=torch.half)
+ self.deepstack_embeddings = None
+
+ class Tower:
+ def get_image_embeddings(self, *args, **kw):
+ calls.append(1)
+ return Emb()
+
+ eng = object.__new__(serve.ResidentEngine)
+ eng.emb_cache, eng.vision, eng.tokenizer = ImageEmbeddingCache(), Tower(), None
+ return eng, calls
+
+ def test_embed_reuses_ids_and_encodes_once(self):
+ from PIL import Image
+ eng, calls = self.make_engine()
+ img = Image.new("RGB", (64, 64))
+ a = eng._embed([(img, "k1")])
+ b = eng._embed([(img, "k1"), (img, "k2")])
+ self.assertIs(a[0], b[0])
+ self.assertNotEqual(b[0].first_index, b[1].first_index)
+ self.assertEqual(len(calls), 2)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/qwen/image_cache.py b/tools/qwen/image_cache.py
new file mode 120000
index 0000000..8991ae3
--- /dev/null
+++ b/tools/qwen/image_cache.py
@@ -0,0 +1 @@
+../strix_halo/image_cache.py
\ No newline at end of file
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index e2f6276..7c45b8c 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -39,6 +39,7 @@ HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.append(str(HERE.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
+import image_cache # noqa: E402 (shared bounded LRU of image embeddings; symlink to tools/strix_halo)
def _load_mimo():
@@ -298,8 +299,8 @@ def normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return out
-def load_image(url: str):
- """PIL image from a data: URI or an http(s) URL (size capped)."""
+def load_image_keyed(url: str):
+ """(PIL image, content hash of the encoded bytes) from a data: URI or an http(s) URL (size capped)."""
from PIL import Image
if not isinstance(url, str) or not url:
raise BadRequest("image_url needs a url")
@@ -316,11 +317,16 @@ def load_image(url: str):
if len(raw) > MAX_IMAGE_BYTES:
raise BadRequest("image too large")
try:
- return Image.open(io.BytesIO(raw)).convert("RGB")
+ return Image.open(io.BytesIO(raw)).convert("RGB"), image_cache.digest(raw)
except Exception as exc: # noqa: BLE001
raise BadRequest(f"cannot decode image: {exc}") from exc
+def load_image(url: str):
+ """PIL image from a data: URI or an http(s) URL (size capped)."""
+ return load_image_keyed(url)[0]
+
+
def sampling_from(body: dict[str, Any], defaults: dict[str, Any]) -> dict[str, Any]:
s = {}
for key in ("temperature", "top_p", "top_k", "min_p"):
@@ -656,6 +662,7 @@ class QwenEngine:
with Heartbeat("loading MTP drafter"):
self.draft_model.load(progressbar=False, callback=startup_health.load_callback())
self.vision = None
+ self.emb_cache = image_cache.ImageEmbeddingCache()
if vision:
try:
self.vision = Model.from_config(self.config, component="vision")
@@ -744,10 +751,18 @@ class QwenEngine:
return ComboSampler(temperature=s["temperature"], top_k=s.get("top_k", 0), top_p=s.get("top_p", 1.0),
min_p=s.get("min_p", 0.0))
+ def _embed(self, images: list[tuple[Any, str]]) -> list:
+ """One MMEmbedding per image. The same bytes give the same embedding object (same pseudo token ids), so a
+ history turn that repeats an image still matches the paged KV cache (see image_cache.py)."""
+ def build(image):
+ t0 = time.perf_counter()
+ emb = self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=image)
+ print(f"qserve: image {image.size[0]}x{image.size[1]} -> {emb.mm_length} tokens, tower {(time.perf_counter() - t0) * 1000:.0f} ms", flush=True)
+ return emb
+ return self.emb_cache.get_many(images, build)
+
def _encode(self, prompt: str, image_urls: list[str]):
- embs = []
- for url in image_urls:
- embs.append(self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=load_image(url)))
+ embs = self._embed([load_image_keyed(url) for url in image_urls]) if image_urls else []
for emb in embs:
prompt = prompt.replace(IMAGE_PAD, emb.text_alias, 1)
kw = {"embeddings": embs} if embs else {}
diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.py
index 9d7c47f..af4e2f1 100644
--- a/tools/qwen/test_serve.py
+++ b/tools/qwen/test_serve.py
@@ -750,5 +750,43 @@ class ServeEnvDefaultsTest(unittest.TestCase):
else: os.environ["EXL3_GDN_FUSE"] = saved
+
+class ImageEmbeddingReuseTests(unittest.TestCase):
+ """The same picture must come back as the same embedding object, so the prompt keeps its token ids."""
+
+ def make_engine(self):
+ import itertools
+ import torch
+ from image_cache import ImageEmbeddingCache
+ ids, calls = itertools.count(1_000_000_000, 100), []
+
+ class Emb:
+ def __init__(self):
+ self.first_index = next(ids)
+ self.text_alias = f"<$EMB_{self.first_index}$>"
+ self.mm_length = 3
+ self.embeddings = torch.zeros(3, 4, dtype=torch.half)
+ self.deepstack_embeddings = None
+
+ class Tower:
+ def get_image_embeddings(self, *args, **kw):
+ calls.append(1)
+ return Emb()
+
+ eng = object.__new__(serve.QwenEngine)
+ eng.emb_cache, eng.vision, eng.tokenizer = ImageEmbeddingCache(), Tower(), None
+ return eng, calls
+
+ def test_embed_reuses_ids_and_encodes_once(self):
+ from PIL import Image
+ eng, calls = self.make_engine()
+ img = Image.new("RGB", (64, 64))
+ a = eng._embed([(img, "k1")])
+ b = eng._embed([(img, "k1"), (img, "k2")])
+ self.assertIs(a[0], b[0])
+ self.assertNotEqual(b[0].first_index, b[1].first_index)
+ self.assertEqual(len(calls), 2)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/strix_halo/image_cache.py b/tools/strix_halo/image_cache.py
new file mode 100644
index 0000000..cdf9859
--- /dev/null
+++ b/tools/strix_halo/image_cache.py
@@ -0,0 +1,82 @@
+"""Bounded LRU of image embeddings shared by the model servers.
+
+A vision embedding takes fresh pseudo token ids every time it is built, and the paged KV cache keys its pages on
+token ids. Building the embedding again for the same picture therefore breaks the prefix match at that picture, on
+every later request. This cache returns the very same embedding object (same ids, same text alias) for the same
+picture, and it skips the vision tower for a picture it already holds.
+
+One picture used n times in a prompt needs n distinct embedding objects (an object spliced twice would make its
+ids ambiguous), so the key is (content hash, occurrence in the prompt); each copy stays stable across requests.
+
+Memory: one entry holds the embedding rows on the host, tokens x hidden x 2 bytes (half), plus the same again for
+each deepstack layer. A 1280x800 screenshot is about 1000 rows: 10 MB at hidden 5120, about 40 MB with three
+deepstack layers. The cache is bounded by entry count and by total bytes.
+"""
+from __future__ import annotations
+
+import collections
+import hashlib
+import threading
+from typing import Any, Callable
+
+DEFAULT_MAX_ITEMS = 32 # a long computer-use session re-sends every earlier screenshot
+DEFAULT_MAX_BYTES = 1 << 30 # 1 GiB of host memory
+
+
+def digest(raw: bytes) -> str:
+ """Content key of an encoded image. One server process holds one vision tower with fixed resize and pixel limits,
+ so the bytes alone decide the embedding; the cache dies with the process."""
+ return hashlib.sha256(raw).hexdigest()
+
+
+def embedding_nbytes(emb: Any) -> int:
+ """Host bytes of an MMEmbedding: its rows and its deepstack rows."""
+ total = 0
+ for t in [getattr(emb, "embeddings", None), *(getattr(emb, "deepstack_embeddings", None) or [])]:
+ if t is not None:
+ total += int(t.numel()) * int(t.element_size())
+ return total
+
+
+class ImageEmbeddingCache:
+ def __init__(self, max_items: int = DEFAULT_MAX_ITEMS, max_bytes: int = DEFAULT_MAX_BYTES):
+ self.max_items = max_items
+ self.max_bytes = max_bytes
+ self._items: collections.OrderedDict = collections.OrderedDict() # (key, occurrence) -> (embedding, nbytes)
+ self._nbytes = 0
+ self._lock = threading.RLock()
+
+ def __len__(self) -> int:
+ return len(self._items)
+
+ @property
+ def nbytes(self) -> int:
+ return self._nbytes
+
+ def clear(self) -> None:
+ with self._lock:
+ self._items.clear()
+ self._nbytes = 0
+
+ def get_many(self, images: list[tuple[Any, str]], build: Callable[[Any], Any]) -> list:
+ """One embedding per (image, key), in order. `build(image)` runs only for a picture not held yet.
+ The lock stays held while building, so two requests never encode the same picture twice."""
+ out, seen = [], collections.Counter()
+ with self._lock:
+ for image, key in images:
+ slot = (key, seen[key])
+ seen[key] += 1
+ hit = self._items.get(slot)
+ if hit is None:
+ emb = build(image)
+ n = embedding_nbytes(emb)
+ self._items[slot] = (emb, n)
+ self._nbytes += n
+ else:
+ emb = hit[0]
+ self._items.move_to_end(slot)
+ out.append(emb)
+ while self._items and (len(self._items) > self.max_items or self._nbytes > self.max_bytes):
+ _, (_, n) = self._items.popitem(last=False)
+ self._nbytes -= n
+ return out
diff --git a/tools/strix_halo/test_image_cache.py b/tools/strix_halo/test_image_cache.py
new file mode 100644
index 0000000..2a216ed
--- /dev/null
+++ b/tools/strix_halo/test_image_cache.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+"""Image embedding cache tests: CPU only, a fake vision tower, no model, no GPU."""
+from __future__ import annotations
+
+import itertools
+import sys
+import threading
+import unittest
+from pathlib import Path
+
+import torch
+
+sys.path.insert(0, str(Path(__file__).parent))
+import image_cache
+from image_cache import ImageEmbeddingCache
+
+
+class FakeEmb:
+ """Stands in for MMEmbedding: ids come from a counter, like the engine's global allocator."""
+ _next = itertools.count(1_000_000_000, 1000)
+
+ def __init__(self, rows: int, hidden: int = 8, deepstack: int = 0):
+ self.first_index = next(self._next)
+ self.text_alias = f"<$EMB_{self.first_index}$>"
+ self.embeddings = torch.zeros(rows, hidden, dtype=torch.half)
+ self.deepstack_embeddings = [torch.zeros(rows, hidden, dtype=torch.half) for _ in range(deepstack)] or None
+
+
+class FakeTower:
+ def __init__(self, rows=4, deepstack=0):
+ self.calls, self.rows, self.deepstack = 0, rows, deepstack
+
+ def __call__(self, image):
+ self.calls += 1
+ return FakeEmb(self.rows, deepstack=self.deepstack)
+
+
+class ImageCacheTests(unittest.TestCase):
+ def test_digest_is_stable_and_content_based(self):
+ self.assertEqual(image_cache.digest(b"abc"), image_cache.digest(b"abc"))
+ self.assertNotEqual(image_cache.digest(b"abc"), image_cache.digest(b"abd"))
+
+ def test_same_image_same_object_across_requests(self):
+ cache, tower = ImageEmbeddingCache(), FakeTower()
+ a1 = cache.get_many([("img-a", "a")], tower)[0]
+ a2 = cache.get_many([("img-a", "a")], tower)[0]
+ self.assertIs(a1, a2)
+ self.assertEqual((a1.first_index, a1.text_alias), (a2.first_index, a2.text_alias))
+ self.assertEqual(tower.calls, 1)
+
+ def test_different_image_different_ids(self):
+ cache, tower = ImageEmbeddingCache(), FakeTower()
+ a, b = cache.get_many([("x", "a"), ("y", "b")], tower)
+ self.assertNotEqual(a.first_index, b.first_index)
+ self.assertNotEqual(a.text_alias, b.text_alias)
+ self.assertEqual(tower.calls, 2)
+
+ def test_history_turn_keeps_earlier_ids(self):
+ cache, tower = ImageEmbeddingCache(), FakeTower()
+ t1 = cache.get_many([("s1", "k1")], tower)
+ t2 = cache.get_many([("s1", "k1"), ("s2", "k2")], tower)
+ t3 = cache.get_many([("s1", "k1"), ("s2", "k2"), ("s3", "k3")], tower)
+ self.assertEqual([e.first_index for e in t2[:1]], [e.first_index for e in t1])
+ self.assertEqual([e.first_index for e in t3[:2]], [e.first_index for e in t2])
+ self.assertEqual(tower.calls, 3)
+
+ def test_same_image_twice_in_one_prompt_is_two_stable_objects(self):
+ cache, tower = ImageEmbeddingCache(), FakeTower()
+ first = cache.get_many([("p", "k"), ("p", "k")], tower)
+ self.assertIsNot(first[0], first[1])
+ self.assertNotEqual(first[0].first_index, first[1].first_index)
+ again = cache.get_many([("p", "k"), ("p", "k")], tower)
+ self.assertIs(first[0], again[0])
+ self.assertIs(first[1], again[1])
+
+ def test_eviction_by_count_drops_least_recently_used(self):
+ cache, tower = ImageEmbeddingCache(max_items=2), FakeTower()
+ a = cache.get_many([("a", "a")], tower)[0]
+ cache.get_many([("b", "b")], tower)
+ cache.get_many([("a", "a")], tower) # a is now the most recent
+ cache.get_many([("c", "c")], tower) # evicts b
+ self.assertEqual(len(cache), 2)
+ self.assertIs(cache.get_many([("a", "a")], tower)[0], a)
+ calls = tower.calls
+ cache.get_many([("b", "b")], tower)
+ self.assertEqual(tower.calls, calls + 1)
+
+ def test_eviction_by_bytes(self):
+ one = image_cache.embedding_nbytes(FakeEmb(4))
+ self.assertEqual(one, 4 * 8 * 2)
+ cache, tower = ImageEmbeddingCache(max_items=100, max_bytes=2 * one + 1), FakeTower()
+ for k in "abc":
+ cache.get_many([(k, k)], tower)
+ self.assertEqual(len(cache), 2)
+ self.assertEqual(cache.nbytes, 2 * one)
+
+ def test_bytes_count_deepstack_rows(self):
+ self.assertEqual(image_cache.embedding_nbytes(FakeEmb(10, hidden=16, deepstack=3)), 4 * 10 * 16 * 2)
+
+ def test_clear_resets_memory(self):
+ cache, tower = ImageEmbeddingCache(), FakeTower()
+ cache.get_many([("a", "a")], tower)
+ cache.clear()
+ self.assertEqual((len(cache), cache.nbytes), (0, 0))
+
+ def test_concurrent_requests_encode_once(self):
+ cache, tower, out = ImageEmbeddingCache(), FakeTower(), []
+ ts = [threading.Thread(target=lambda: out.append(cache.get_many([("a", "a")], tower)[0])) for _ in range(8)]
+ [t.start() for t in ts]
+ [t.join() for t in ts]
+ self.assertEqual(tower.calls, 1)
+ self.assertEqual(len({id(e) for e in out}), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()