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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Servers: one picture cache for the three servers, with the eviction policy a switch
MangetsuC07166f450d78
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex d49f714..dca8a11 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -31,7 +31,7 @@ call, a streamed call, a tool call, and two 400-token benchmark calls.| `--max-history` | `1` | recurrent history slots; must equal draft tokens (1 for MTP). Each extra slot costs ~2.15 GiB || `-c`, `--max-ctx` | `131072` | context window in tokens, shared by all sessions || `--image-cache-mb` | `1024` | host memory for the decoded image embeddings, in MiB, one pool shared by all sessions; `0` = no byte limit |-| `--image-cache-items` | `0` | optional cap on how many pictures are held at once; `0` = no limit |+| `--image-cache-items` | `32` | cap on how many pictures are held at once; `0` = no limit || `--image-cache-dir` | `~/.cache/kyojin/image-embeddings` | directory of the second-level picture cache; used only when `--image-cache-dir-max-gb` is set || `--image-cache-dir-max-gb` | `0` | GiB cap on that directory; `0` = disabled. There is no unlimited setting || `--image-cache-dir-lock-s` | `300` | seconds a conversation keeps the room its files took before another may take it; `0` = no tenure |@@ -52,6 +52,10 @@ collector freeze (`EXL3_GC_FREEZE`) are described in [doc/env_vars.md](../../docThe lookup code is `tools/qwen/spec_policy.py`, which the GLM server finds through its own file path, so `tools/qwen`must ship next to `tools/glm`.+The picture cache's eviction policy is an environment variable rather than a flag:+**`KYOJIN_IMAGE_CACHE_POLICY`**, `head` (the default, a plain LRU) or `tail` (keep the head of a prompt and give up its+end); anything else is an error at start-up. See [Images](#images).+### MTP sidecar (higher draft acceptance)The pack stores the MTP `eh_proj` at 2 bits. The pack also ships an unquantized copy,@@ -129,10 +133,13 @@ server keeps the decoded embeddings of recent pictures in host memory (GLM's merpicture fresh pseudo token ids and breaks the paged prefix *from that picture on*. `--image-cache-mb` sizes thecache: 1024 MiB by default, about 20 pages of 1568x1568 at 49.0 MiB each, one pool shared by all sessionslike `-c`.-A conversation larger than the budget keeps its **earliest** pictures and gives up the last ones, so the match-still runs from the first page to where the cache ended rather than collapsing to nothing. The request log's-`img_cache` line reports `hits`, `misses` and `first_missing`, the index the prefix could match up to;-`--image-cache-items` adds an optional cap on the number of pictures.+Which pictures a full cache gives up is the eviction policy of the shared cache, `KYOJIN_IMAGE_CACHE_POLICY`:+`head` (the default) is a plain LRU — the same behaviour this cache always had — and it drops the *earliest*+pictures of a history, which are exactly the ones the paged prefix starts from; `tail` drops the *last* ones+instead, so a conversation a client keeps re-sending keeps its head. The request log's `img_cache` line reports+`hits`, `misses` and `first_missing`, the index the prefix could match up to; `--image-cache-items` caps the+number of pictures held (32 by default, as upstream's shared cache; `0` = no limit), which for small crops binds+before the byte budget does.`--image-cache-format` stores those rows packed instead of as fp32 (49.0 MiB for a 1568x1568 page): `fp16` is24.5 MiB and `q8` is 12.3 MiB. Measured per picture that is actually@@ -161,8 +168,12 @@ With `--image-cache-dir-max-gb` (off by default), the pictures the memory budgetmore pictures than `--image-cache-mb` holds: a session that fits writes nothing, and a longer one writes eachevicted picture once (files are keyed by content, so a picture evicted twice is not rewritten). The directory is`--image-cache-dir`, `~/.cache/kyojin/image-embeddings` unless changed, and anything unreadable in it is dropped-and re-encoded: the disk never becomes a reason for a request to fail. Note what it stores: the **rows derived-from the input images stay on disk**, which is a privacy and disk-wear consideration. Two knobs bound it:+and re-encoded: the disk never becomes a reason for a request to fail. It is meant to be used with `KYOJIN_IMAGE_CACHE_POLICY=tail`: then the evicted+pictures are the end of a prompt, restoring them completes the prompt again and the paged prefix survives, which+is where the large win is (99.8 % of a 24-page prompt reused, 1.2 s against 82.0 s). Under the default `head`+policy it still saves the vision pass for the pictures it holds, but the prefix is broken at the first of them.+Note what it stores: the **rows derived from the input images stay on disk**, which is a privacy and disk-wear+consideration. Two knobs bound it:`--image-cache-dir-max-gb` caps the directory and `--image-cache-dir-lock-s` caps how often a conversation canlose its place to another one.@@ -337,6 +348,9 @@ Model-free: a `FakeEngine` emits deterministic GLM XML in 3-character chunks sosplit mid-token, covering template rendering, think/tool parsing, stop strings, SSEframing, `/v1/models`, usage, and the streamed open-`<think>` path. No GPU needed.+`tools/strix_halo/test_image_cache.py` covers the shared cache itself, including both eviction policies (the+default LRU and `KYOJIN_IMAGE_CACHE_POLICY=tail`).+`test_serve_glm_additional.py` holds the tests for what this checkout adds locally: therequest log (`KYOJIN_REQLOG`, off by default, no request text) and the image cache(`--image-cache-mb` / `--image-cache-items`, the defaults of the `--image-cache-dir*` options,diff --git a/tools/glm/image_cache.py b/tools/glm/image_cache.pyindex 78cc369..8991ae3 120000--- a/tools/glm/image_cache.py+++ b/tools/glm/image_cache.py@@ -1 +1 @@-image_cache_glm.py\ No newline at end of file+../strix_halo/image_cache.py\ No newline at end of filediff --git a/tools/glm/image_cache_disk.py b/tools/glm/image_cache_disk.pyindex 7523d6d..4dac090 100644--- a/tools/glm/image_cache_disk.py+++ b/tools/glm/image_cache_disk.py@@ -1,9 +1,11 @@#!/usr/bin/env python3"""Second-level picture cache on disk: the rows of the pictures the memory cache had to evict.-The memory cache (`image_cache_glm.py`) keeps the *earliest* pictures of a prompt and gives up the tail, so the-pictures a client re-sends a moment later are exactly the ones it dropped, and today they cost a vision pass-plus the re-prefill of everything from their position on. Writing a picture out **when it is evicted** and+The memory cache (the shared `image_cache.py`) gives up the pictures its eviction policy weighs least, and with+`KYOJIN_IMAGE_CACHE_POLICY=tail` those are the *last* ones of a prompt, so the pictures a client re-sends a moment+later are exactly the ones it dropped — which today cost a vision pass plus the re-prefill of everything from+their position on. (Under the default `head` policy the first pictures go instead, and then this directory can+still save the vision pass for them, but not the prefix.) Writing a picture out **when it is evicted** andreading it back later replaces that with a file read: the server also keeps the picture's identity (its pseudotoken ids) for the life of the process, so a restored picture reproduces the prompt token for token and thepaged KV prefix still matches.diff --git a/tools/glm/image_cache_glm.py b/tools/glm/image_cache_glm.pydeleted file mode 100644index 05642a3..0000000--- a/tools/glm/image_cache_glm.py+++ /dev/null@@ -1,199 +0,0 @@-#!/usr/bin/env python3-"""Bounded cache of image embeddings for the GLM server: a full cache gives up the *tail* of the prompt.--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.--What a hit is worth depends on *where* the picture sits in the prompt: the paged prefix matches from the first-token on and stops at the first picture that had to be re-encoded, so the n-th picture buys reuse only if every-earlier one is still held, and the first picture buys the whole prompt. The eviction order therefore follows the-prompt, not the clock: an entry no longer referenced by a remembered prompt goes first, then the *last* pictures-of the remembered prompts, and the head of the prompt is the last thing given up. A plain LRU does the opposite —-it drops the oldest pictures, which are exactly the ones the match depends on, and turns "the cache is one picture-too small" into "nothing at all is reused" (measured: 21 pictures against a 20-picture budget, 99.8 % of a 63K-prompt reused before the change, 0 % — the full 63K re-prefilled — after it).--The cache is bounded by total bytes, with an optional entry count on top; the GLM server sizes the byte budget-from RAM and its own flags (see `--image-cache-mb`). Each entry holds the embedding rows on the host plus the same-again for each deepstack layer, so the budget is host memory, not VRAM: GLM's vision merger emits fp32, about-49.0 MiB for one 1568x1568 page (3,136 tokens) and 1 MB for a 224x224 crop.--When the budget cannot hold every active conversation, each one keeps its head and re-encodes its tail: the loss-is a few pictures per turn, not the prompt. `max_orders` is how many recent prompts the policy weighs, and among-pictures at the same distance from the start, the one from the conversation served longest ago goes first.-"""-from __future__ import annotations--import collections-import hashlib-import threading-from typing import Any, Callable--DEFAULT_MAX_ITEMS = 0 # the byte budget is the real bound; a count cap is optional on top of it-DEFAULT_MAX_BYTES = 1 << 30 # 1 GiB of host memory, as upstream sizes it (--image-cache-mb overrides)-DEFAULT_MAX_ORDERS = 2 # prompts whose picture order the eviction policy remembers---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, in whatever form they are stored.- Quantized rows report their own size (int8 plus scales), so the budget counts what is really held."""- total = 0- for t in [getattr(emb, "embeddings", None), *(getattr(emb, "deepstack_embeddings", None) or [])]:- if t is None:- continue- nbytes = getattr(t, "nbytes", None)- total += int(nbytes) if nbytes is not None else int(t.numel()) * int(t.element_size())- return total---class ImageEmbeddingCache:- """Embeddings keyed by (content, occurrence), sized in bytes, evicted from the end of the prompt backwards.-- `max_bytes` or `max_items` at 0 means that bound is not applied. `max_orders` is how many recent prompts the- eviction policy keeps in mind: 1 is enough for one request at a time and gives exactly "give up the tail of- this prompt", while a server running `--sessions N` passes N (or a little more) so that concurrent- conversations do not evict each other's heads. Thread safe: one vision pass per picture, also across requests.- """-- def __init__(self, max_items: int = DEFAULT_MAX_ITEMS, max_bytes: int = DEFAULT_MAX_BYTES,- max_orders: int = DEFAULT_MAX_ORDERS):- self.max_items = max(0, int(max_items))- self.max_bytes = max(0, int(max_bytes))- self.max_orders = max(1, int(max_orders))- self._items: collections.OrderedDict = collections.OrderedDict() # slot -> (embedding, nbytes)- self._orders: collections.OrderedDict = collections.OrderedDict() # prompt serial -> [slot, ...]- self._seq = 0- self._nbytes = 0- self._last_order: list = [] # slots of the prompt being served, in prompt order- self._lock = threading.RLock()-- def __len__(self) -> int:- return len(self._items)-- @property- def nbytes(self) -> int:- return self._nbytes-- @property- def live_orders(self) -> list:- """The pictures the remembered prompts refer to, newest prompt first, as a list of content-key sets.-- A second-level store needs this to tell conversations apart: the newest entry is the one being served- (its pictures must stay complete or the prompt cannot be reproduced), older entries are conversations the- user may come back to, and a picture in none of them belongs to a conversation that is over. The cache- only remembers the last `max_orders` prompts, so a conversation the user has left ages out on its own.- """- return [{slot[0] for slot in slots} for slots in reversed(self._orders.values())]-- def clear(self) -> None:- with self._lock:- self._items.clear()- self._orders.clear()- self._nbytes = 0-- def _over_budget(self) -> bool:- return bool((self.max_items and len(self._items) > self.max_items) or- (self.max_bytes and self._nbytes > self.max_bytes))-- def _eviction_order(self) -> list:- """Slots of the held embeddings, the one to give up first first.-- Least valuable first: an entry that no remembered prompt refers to, then the entries of those prompts- ordered by how far into the prompt they sit (the last picture of a prompt is worth the least), and among- equal positions the prompt that was seen longest ago.- """- position: dict = {}- for age, slots in enumerate(self._orders.values()):- for index, slot in enumerate(slots):- seen = position.get(slot)- if seen is None or index < seen[0]: # keep the earliest position this picture has in any prompt- position[slot] = (index, age)- stale, live = [], []- for lru, slot in enumerate(self._items): # _items is in use order, least recently used first- if slot in position:- index, age = position[slot]- live.append((-index, age, lru, slot))- else:- stale.append((lru, slot))- stale.sort()- live.sort()- return [slot for _, slot in stale] + [slot for *_, slot in live]-- def _trim(self, evicted: list | None = None) -> int:- """Evict until both bounds hold. Returns how many entries went.-- `evicted`, when given, collects the (key, embedding, position-in-this-prompt) of everything that left, so- a caller can put them somewhere cheaper than memory (the server writes them to its picture cache on- disk). Positions are the entries' ranks in the prompt being served, which is the order any second-level- store has to keep: the earliest pictures are the ones the paged prefix needs.- """- if not self._over_budget():- return 0- rank = {slot: i for i, slot in enumerate(self._last_order or [])} if evicted is not None else {}- gone = 0- for slot in self._eviction_order():- if not self._over_budget():- break- item = self._items.pop(slot, None)- if item is not None:- self._nbytes -= item[1]- gone += 1- if evicted is not None:- evicted.append((slot[0], item[0], rank.get(slot)))- return gone-- def get_many(self, images: list[tuple[Any, str]], build: Callable[[Any], Any],- evicted: list | None = None, fetch: Callable[[Any, str], Any] | None = None,- mine: set | None = None) -> list:- """One embedding per (image, key), in order. For a picture not held yet, `fetch(image, key)` is tried- first (a second-level store, e.g. the one on disk) and `build(image)` runs only when it has nothing.- The lock stays held while both run, so two requests never encode the same picture twice.-- The prompt order of this call is remembered for the next `max_orders` calls: they are what the eviction- policy weighs, so a conversation that keeps sending its whole history keeps its earliest pictures.-- `evicted`, when given, is filled with what this call pushed out (see `_trim`), and `mine` with the- content keys of *this* prompt: a caller that writes the evicted pictures somewhere slower needs to know- which conversation it is serving, or concurrent requests would evict each other's caches. The caller must- not touch the cache from a `build` callback and does its own work with both after this returns.- """- out, seen = [], collections.Counter()- order: list = []- with self._lock:- for image, key in images:- slot = (key, seen[key])- seen[key] += 1- order.append(slot)- if mine is not None:- mine.add(key)- hit = self._items.get(slot)- if hit is None:- emb = fetch(image, key) if fetch is not None else None- if emb 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)- if order:- self._seq += 1- self._orders[self._seq] = order- while len(self._orders) > self.max_orders:- self._orders.popitem(last=False)- self._last_order = order- self._trim(evicted)- return outdiff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 9ef78b8..2eda89b 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -111,6 +111,9 @@ SPEED_ENV = {# 1568x1568 page (3,136 tokens) and 1 MB for a 224x224 crop, so pictures, not bytes, are what a conversation# spends: the default holds about 20 of those pages, as upstream's 1 GiB did.IMAGE_CACHE_MB_DEFAULT = 1024+# Count cap on top of the byte budget, as upstream's shared cache defaults to it (0 = no limit). For big pages+# the byte budget binds first; for small ones this keeps the entry count bounded.+IMAGE_CACHE_ITEMS_DEFAULT = 32# How the cached rows are stored (--image-cache-format). fp32 is what the vision merger emits; fp16 is exactly# the same values (the tower computes in fp16) and q8 rounds at one part in 254 of the row's peak. Kept here# rather than imported from the engine, which serve.py must not import before SPEED_ENV is applied.@@ -126,17 +129,19 @@ IMAGE_CACHE_DIR_MAX_GB = 0.0IMAGE_CACHE_DIR_LOCK_S = 300.0-def make_image_cache(image_cache_bytes: int | None = None, image_cache_items: int = 0,- sessions: int = 1) -> ImageEmbeddingCache:+def make_image_cache(image_cache_bytes: int | None = None, image_cache_items: int = IMAGE_CACHE_ITEMS_DEFAULT,+ sessions: int = 1, policy: str | None = None) -> ImageEmbeddingCache:"""The picture cache of the process (--image-cache-mb / --image-cache-items).One cache for the whole server, shared by every session exactly like the KV pool `-c` sizes, with the- eviction policy of image_cache_glm.py: the tail of a prompt is given up before its head, and the policy- remembers one prompt order per concurrent request plus one, so a conversation is not forgotten between two- of its own turns when another session slips in between.+ eviction policy of the shared cache in tools/strix_halo/image_cache.py: the default gives up the head of a+ prompt a client keeps re-sending (what the servers always did), and `KYOJIN_IMAGE_CACHE_POLICY=tail` gives up+ its tail instead. The policy remembers one prompt order per concurrent request plus one, so a conversation is+ not forgotten between two of its own turns when another session slips in between."""return ImageEmbeddingCache(max_items=image_cache_items, max_orders=max(2, sessions),- **({} if image_cache_bytes is None else {"max_bytes": image_cache_bytes}))+ **({} if image_cache_bytes is None else {"max_bytes": image_cache_bytes}),+ **({} if policy is None else {"policy": policy}))def make_image_disk(image_cache_dir: str | None, image_cache_dir_max_gb: float, image_cache_dir_lock_s: float,@@ -1750,8 +1755,9 @@ def main() -> None:help=f"host memory for the decoded image embeddings, in MiB; 0 = no byte limit. Like -c this "f"is one pool shared by every --sessions request (default {IMAGE_CACHE_MB_DEFAULT}): ""about 49 MiB per 1568x1568 page, 1 MB per 224x224 crop")- parser.add_argument("--image-cache-items", type=int, default=0,- help="optional cap on how many pictures are held at once (0 = no limit)")+ parser.add_argument("--image-cache-items", type=int, default=IMAGE_CACHE_ITEMS_DEFAULT,+ help=f"cap on how many pictures are held at once; 0 = no limit "+ f"(default {IMAGE_CACHE_ITEMS_DEFAULT}, as upstream)")parser.add_argument("--image-cache-dir", default=IMAGE_CACHE_DIR_DEFAULT,help=f"directory of the second-level picture cache (default {IMAGE_CACHE_DIR_DEFAULT}); ""only used when --image-cache-dir-max-gb is set")@@ -1825,7 +1831,7 @@ def main() -> None:print(mem_line("loaded"), flush=True)print(f"serve: vision={engine.supports_vision}", flush=True)print(f"serve: image cache {image_cache_size}, {'no count cap' if not engine.emb_cache.max_items else str(engine.emb_cache.max_items) + ' pictures max'}, "- f"{args.image_cache_format} rows, shared by {args.sessions} session(s)", flush=True)+ f"{args.image_cache_format} rows, {engine.emb_cache.policy} policy, shared by {args.sessions} session(s)", flush=True)if engine.emb_disk is not None:print(f"serve: {engine.emb_disk.describe()}", flush=True)# Warm-up before the slot store is attached, so the warm-up prompt never shows in /slots.@@ -1878,6 +1884,7 @@ def main() -> None:image_cache_mb=round(emb_cache.max_bytes / 2 ** 20, 1) if emb_cache is not None else None,image_cache_items=getattr(emb_cache, "max_items", None),image_cache_format=getattr(engine, "image_cache_format", "fp32"),+ image_cache_policy=getattr(getattr(engine, "emb_cache", None), "policy", None),image_cache_dir=str(engine.emb_disk.path) if getattr(engine, "emb_disk", None) else None,image_cache_dir_cap_mb=round(engine.emb_disk.max_bytes / 2 ** 20) if getattr(engine, "emb_disk", None) else None,image_cache_dir_lock_s=engine.emb_disk.lock_s if getattr(engine, "emb_disk", None) else None,diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex 5f9fecc..77ee2de 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -88,9 +88,12 @@ def vision_engine():def disk_engine(directory, budget_bytes: int = 768, mode: str = "fp32", cap_bytes: int = 0, on_disk: bool = True,- lock_s: float = 0.0):+ lock_s: float = 0.0, policy: str = "tail"):"""An engine whose _embed() runs over a real memory cache *and* a real second-level cache on disk.+ The memory cache runs the `tail` policy the disk layer is built for: keeping the head of a prompt is what+ lets a restored picture complete it. The server's own default is the shared cache's LRU (`head`).+The fake pictures carry everything a restore needs (identity, token list, MRoPE metadata) so a test can askwhether the prompt would be reproduced: unlike the tower, the disk has to give back the same pseudo ids."""@@ -121,7 +124,7 @@ def disk_engine(directory, budget_bytes: int = 768, mode: str = "fp32", cap_bytereturn Emb()eng = object.__new__(serve.ResidentEngine)- eng.emb_cache = ImageEmbeddingCache(max_bytes=budget_bytes)+ eng.emb_cache = ImageEmbeddingCache(max_bytes=budget_bytes, policy=policy)eng.vision, eng.tokenizer = Tower(), Noneeng.image_cache_format = modeeng.emb_disk = None@@ -226,8 +229,13 @@ class ImageDiskCacheTests(unittest.TestCase):def test_the_defaults_match_upstream(self):# The memory budget is upstream's 1 GiB, and the disk cache is off unless a cap is given: no auto share# of RAM, and no way to ask for an unbounded directory.+ from image_cache import DEFAULT_MAX_ITEMSself.assertEqual(serve.IMAGE_CACHE_MB_DEFAULT, 1024)self.assertEqual(serve.make_image_cache(None).max_bytes, 1024 << 20)+ # The count cap defaults to the shared cache's, so the three servers behave the same out of the box.+ self.assertEqual(serve.IMAGE_CACHE_ITEMS_DEFAULT, DEFAULT_MAX_ITEMS)+ self.assertEqual(serve.make_image_cache(None).max_items, DEFAULT_MAX_ITEMS)+ self.assertEqual(serve.make_image_cache(None, 0).max_items, 0) # 0 = no limit, when asked forself.assertEqual(serve.IMAGE_CACHE_DIR_MAX_GB, 0.0)self.assertTrue(serve.IMAGE_CACHE_DIR_DEFAULT.endswith(".cache/kyojin/image-embeddings"))self.assertEqual(serve.IMAGE_CACHE_DIR_LOCK_S, 300.0)@@ -266,7 +274,7 @@ class ImageDiskCacheTests(unittest.TestCase):# counts the bytes of the form it actually holds (3 rows x 64 half values = 384 B as they are).from PIL import Imagefrom exllamav3.tokenizer.mm_embedding import QuantizedMMRows- from image_cache_glm import embedding_nbytes+ from image_cache import embedding_nbyteseng, _ = vision_engine()img = Image.new("RGB", (8, 8))counts, packed = {}, {}@@ -454,8 +462,8 @@ class RequestLogTests(unittest.TestCase):self.assertEqual((cache[0]["imgs"], cache[0]["hits"], cache[0]["misses"]), ("2", "0", "2"))self.assertEqual(cache[0]["first_missing"], "0") # the prefix can only match from the startself.assertEqual((cache[0]["entries"], cache[0]["evicted"]), ("2", "0"))- self.assertEqual(cache[0]["budget_mb"], "1024") # image_cache_glm's own default (upstream's 1 GiB)- self.assertEqual(cache[0]["item_cap"], "0")+ self.assertEqual(cache[0]["budget_mb"], "1024") # the shared cache's own default (1 GiB)+ self.assertEqual(cache[0]["item_cap"], "32") # the shared cache's count defaultself.assertEqual((cache[1]["hits"], cache[1]["misses"]), ("2", "0"))self.assertNotIn("first_missing", cache[1]) # a full hit has no gapself.assertNotIn("data:image", "\n".join(self.lines())) # the image URL is never writtendiff --git a/tools/strix_halo/image_cache.py b/tools/strix_halo/image_cache.pyindex cdf9859..6487b91 100644--- a/tools/strix_halo/image_cache.py+++ b/tools/strix_halo/image_cache.py@@ -1,4 +1,4 @@-"""Bounded LRU of image embeddings shared by the model servers.+"""Bounded cache 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 ontoken ids. Building the embedding again for the same picture therefore breaks the prefix match at that picture, on@@ -8,19 +8,48 @@ 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 itsids ambiguous), so the key is (content hash, occurrence in the prompt); each copy stays stable across requests.+Which picture a full cache gives up is a policy, chosen with KYOJIN_IMAGE_CACHE_POLICY:++* `head` (the default, and what this cache always did): a plain LRU, the least recently used picture first. A+ client that re-sends its whole history every turn touches its pictures in prompt order, so the oldest ones are+ the earliest ones in the prompt, and the cache gives up the *head* of the prompt.+* `tail`: the order follows the prompt instead of the clock. An entry that no remembered prompt refers to goes+ first, then the *last* pictures of the remembered prompts, and the head of the prompt is the last thing given+ up. `max_orders` is how many recent prompts the policy weighs.++What a hit is worth depends on where the picture sits: the paged prefix matches from the first token on and stops+at the first picture that had to be re-encoded, so the n-th picture buys reuse only if every earlier one is still+held, and the first picture buys the whole prompt. With `tail` on a 24-page prompt and a budget for 20 pages,+43.5 % of a 75K-token prompt was reused where the default reused nothing, and 99.8 % when the evicted pictures+were also written to a disk cache.+Memory: one entry holds the embedding rows on the host, tokens x hidden x 2 bytes (half), plus the same again foreach 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.+deepstack layers. The cache is bounded by entry count and by total bytes. Rows stored packed (see+`QuantizedMMRows`) report their own size, so the budget counts what is really held."""from __future__ import annotationsimport collectionsimport hashlib+import osimport threadingfrom typing import Any, CallableDEFAULT_MAX_ITEMS = 32 # a long computer-use session re-sends every earlier screenshotDEFAULT_MAX_BYTES = 1 << 30 # 1 GiB of host memory+DEFAULT_MAX_ORDERS = 2 # prompts whose picture order the tail policy remembers+POLICY_ENV = "KYOJIN_IMAGE_CACHE_POLICY"+POLICIES = ("head", "tail")+DEFAULT_POLICY = "head" # what a server did before the switch existed+++def policy_from_env(default: str = DEFAULT_POLICY) -> str:+ """The policy a server gets when it does not name one: KYOJIN_IMAGE_CACHE_POLICY, or `default`."""+ name = (os.environ.get(POLICY_ENV) or default).strip().lower()+ if name not in POLICIES:+ raise ValueError(f"{POLICY_ENV}={name!r} is not one of {', '.join(POLICIES)}")+ return namedef digest(raw: bytes) -> str:@@ -30,19 +59,39 @@ def digest(raw: bytes) -> str:def embedding_nbytes(emb: Any) -> int:- """Host bytes of an MMEmbedding: its rows and its deepstack rows."""+ """Host bytes of an MMEmbedding: its rows and its deepstack rows, in whatever form they are stored.+ Packed rows report their own size (int8 plus scales), so the budget counts what is really held."""total = 0for 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())+ if t is None:+ continue+ nbytes = getattr(t, "nbytes", None)+ total += int(nbytes) if nbytes is not None else int(t.numel()) * int(t.element_size())return totalclass 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+ """Embeddings keyed by (content, occurrence), sized in bytes, evicted by the policy in the module docstring.++ `max_bytes` or `max_items` at 0 means that bound is not applied. `max_orders` is how many recent prompts the+ `tail` policy keeps in mind: 1 is enough for one request at a time and gives exactly "give up the tail of this+ prompt", while a server running `--sessions N` passes N (or a little more) so that concurrent conversations do+ not evict each other's heads. `policy` overrides the environment; the default is the LRU a server had before+ the switch existed. Thread safe: one vision pass per picture, also across requests.+ """++ def __init__(self, max_items: int = DEFAULT_MAX_ITEMS, max_bytes: int = DEFAULT_MAX_BYTES,+ max_orders: int = DEFAULT_MAX_ORDERS, policy: str | None = None):+ self.max_items = max(0, int(max_items))+ self.max_bytes = max(0, int(max_bytes))+ self.max_orders = max(1, int(max_orders))+ self.policy = (policy or policy_from_env()).strip().lower()+ if self.policy not in POLICIES:+ raise ValueError(f"policy {self.policy!r} is not one of {', '.join(POLICIES)}")self._items: collections.OrderedDict = collections.OrderedDict() # (key, occurrence) -> (embedding, nbytes)+ self._orders: collections.OrderedDict = collections.OrderedDict() # prompt serial -> [slot, ...]+ self._seq = 0+ self._last_order: list = [] # slots of the prompt being served, in prompt orderself._nbytes = 0self._lock = threading.RLock()@@ -53,22 +102,109 @@ class ImageEmbeddingCache:def nbytes(self) -> int:return self._nbytes+ @property+ def live_orders(self) -> list:+ """The pictures the remembered prompts refer to, newest prompt first, as a list of content-key sets.++ A second-level store needs this to tell conversations apart: the newest entry is the one being served+ (its pictures must stay complete or the prompt cannot be reproduced), older entries are conversations the+ user may come back to, and a picture in none of them belongs to a conversation that is over. The cache+ only remembers the last `max_orders` prompts, so a conversation the user has left ages out on its own.+ """+ return [{slot[0] for slot in slots} for slots in reversed(self._orders.values())]+def clear(self) -> None:with self._lock:self._items.clear()+ self._orders.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."""+ def _over_budget(self) -> bool:+ return bool((self.max_items and len(self._items) > self.max_items) or+ (self.max_bytes and self._nbytes > self.max_bytes))++ def _by_prompt(self) -> list:+ """Slots by prompt, the one to give up first first (the `tail` policy).++ Least valuable first: an entry that no remembered prompt refers to, then the entries of those prompts+ ordered by how far into the prompt they sit (the last picture of a prompt is worth the least), and among+ equal positions the prompt that was seen longest ago.+ """+ position: dict = {}+ for age, slots in enumerate(self._orders.values()):+ for index, slot in enumerate(slots):+ seen = position.get(slot)+ if seen is None or index < seen[0]: # keep the earliest position this picture has in any prompt+ position[slot] = (index, age)+ stale, live = [], []+ for lru, slot in enumerate(self._items): # _items is in use order, least recently used first+ if slot in position:+ index, age = position[slot]+ live.append((-index, age, lru, slot))+ else:+ stale.append((lru, slot))+ stale.sort()+ live.sort()+ return [slot for _, slot in stale] + [slot for *_, slot in live]++ def _eviction_order(self) -> list:+ """Slots of the held embeddings, the one to give up first first, as the policy asks."""+ if self.policy == "head":+ return list(self._items) # plain LRU: _items is in use order, oldest use first+ return self._by_prompt()++ def _trim(self, evicted: list | None = None) -> int:+ """Evict until both bounds hold. Returns how many entries went.++ `evicted`, when given, collects the (key, embedding, position-in-this-prompt) of everything that left, so+ a caller can put them somewhere cheaper than memory (a server writes them to its picture cache on disk).+ Positions are the entries' ranks in the prompt being served, which is the order any second-level store has+ to keep: the earliest pictures are the ones the paged prefix needs.+ """+ if not self._over_budget():+ return 0+ rank = {slot: i for i, slot in enumerate(self._last_order or [])} if evicted is not None else {}+ gone = 0+ for slot in self._eviction_order():+ if not self._over_budget():+ break+ item = self._items.pop(slot, None)+ if item is not None:+ self._nbytes -= item[1]+ gone += 1+ if evicted is not None:+ evicted.append((slot[0], item[0], rank.get(slot)))+ return gone++ def get_many(self, images: list[tuple[Any, str]], build: Callable[[Any], Any],+ evicted: list | None = None, fetch: Callable[[Any, str], Any] | None = None,+ mine: set | None = None) -> list:+ """One embedding per (image, key), in order. For a picture not held yet, `fetch(image, key)` is tried+ first (a second-level store, e.g. the one on disk) and `build(image)` runs only when it has nothing.+ The lock stays held while both run, so two requests never encode the same picture twice.++ The prompt order of this call is remembered for the next `max_orders` calls: they are what the `tail`+ policy weighs, so a conversation that keeps sending its whole history keeps its earliest pictures.++ `evicted`, when given, is filled with what this call pushed out (see `_trim`), and `mine` with the+ content keys of *this* prompt: a caller that writes the evicted pictures somewhere slower needs to know+ which conversation it is serving, or concurrent requests would evict each other's caches. The caller must+ not touch the cache from a `build` callback and does its own work with both after this returns.+ """out, seen = [], collections.Counter()+ order: list = []with self._lock:for image, key in images:slot = (key, seen[key])seen[key] += 1+ order.append(slot)+ if mine is not None:+ mine.add(key)hit = self._items.get(slot)if hit is None:- emb = build(image)+ emb = fetch(image, key) if fetch is not None else None+ if emb is None:+ emb = build(image)n = embedding_nbytes(emb)self._items[slot] = (emb, n)self._nbytes += n@@ -76,7 +212,11 @@ class ImageEmbeddingCache: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+ if order:+ self._seq += 1+ self._orders[self._seq] = order+ while len(self._orders) > self.max_orders:+ self._orders.popitem(last=False)+ self._last_order = order+ self._trim(evicted)return outdiff --git a/tools/strix_halo/test_image_cache.py b/tools/strix_halo/test_image_cache.pyindex 2a216ed..a586a96 100644--- a/tools/strix_halo/test_image_cache.py+++ b/tools/strix_halo/test_image_cache.py@@ -3,6 +3,7 @@from __future__ import annotationsimport itertools+import osimport sysimport threadingimport unittest@@ -85,6 +86,42 @@ class ImageCacheTests(unittest.TestCase):cache.get_many([("b", "b")], tower)self.assertEqual(tower.calls, calls + 1)+ def test_the_default_policy_is_the_lru_a_server_always_had(self):+ self.assertEqual(image_cache.DEFAULT_POLICY, "head")+ self.assertEqual(ImageEmbeddingCache().policy, "head") # nothing asked for: the policy upstream had+ cache, tower = ImageEmbeddingCache(max_items=2, max_bytes=0), FakeTower()+ cache.get_many([("a", "a"), ("b", "b")], tower) # a used, then b+ cache.get_many([("b", "b"), ("c", "c")], tower) # b again, then c: a is the oldest use now+ calls = tower.calls+ cache.get_many([("a", "a")], tower) # ... so a was the one given up+ self.assertEqual(tower.calls, calls + 1)+ calls = tower.calls+ cache.get_many([("c", "c")], tower)+ self.assertEqual(tower.calls, calls) # c survived: no encode++ def test_the_policy_can_be_asked_for_by_the_environment(self):+ os.environ[image_cache.POLICY_ENV] = "tail"+ self.addCleanup(os.environ.pop, image_cache.POLICY_ENV, None)+ self.assertEqual(ImageEmbeddingCache().policy, "tail")+ os.environ[image_cache.POLICY_ENV] = "nonsense"+ with self.assertRaises(ValueError):+ ImageEmbeddingCache()+ os.environ.pop(image_cache.POLICY_ENV, None)+ self.assertEqual(ImageEmbeddingCache().policy, "head")+ self.assertEqual(ImageEmbeddingCache(policy="tail").policy, "tail") # explicit beats the environment++ def test_tail_policy_gives_up_the_end_of_a_prompt_first(self):+ cache, tower = ImageEmbeddingCache(max_items=2, max_bytes=0, policy="tail"), FakeTower()+ first = cache.get_many([("a", "a"), ("b", "b")], tower) # one prompt: a sits before b+ cache.get_many([("a", "a"), ("c", "c")], tower) # room for two of a, b and c+ calls = tower.calls # a, b, c encoded+ # a is the head of both prompts and stays; b and c both sit second, and of two pictures at the same+ # distance from the start the one from the prompt seen longest ago goes first, so b is the one given up.+ self.assertIs(cache.get_many([("a", "a")], tower)[0], first[0])+ self.assertEqual(tower.calls, calls) # the head survived: no encode+ cache.get_many([("b", "b")], tower)+ self.assertEqual(tower.calls, calls + 1) # ... and b was the one given up+def test_eviction_by_bytes(self):one = image_cache.embedding_nbytes(FakeEmb(4))self.assertEqual(one, 4 * 8 * 2)