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.

GLM server: a second-level picture cache on disk (--image-cache-dir, off by default)

MangetsuC752f4219ffa6
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index d0eec6b..44ff7ed 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -32,6 +32,8 @@ call, a streamed call, a tool call, and two 400-token benchmark calls.
| `-c`, `--max-ctx` | `131072` | context window in tokens, shared by all sessions |
| `--image-cache-mb` | 2 GiB on a 128 GB Strix Halo | host memory for the decoded image embeddings, shared by all sessions; `0` = no byte limit. Default is 2 percent of RAM clamped to `[512, 2048]` MiB (see [Images](#images)) |
| `--image-cache-items` | `0` | optional cap on how many pictures are held at once; `0` = only the byte budget |
+| `--image-cache-dir` | none | a second-level picture cache on disk, **off by default**. The rows of the pictures the memory budget evicts are written there (and only those: a session that fits in `--image-cache-mb` writes nothing) and read back when the client sends the picture again. With the picture's identity kept for the life of the process, a restored picture reproduces the prompt token for token, so the paged prefix still matches. Holds rows derived from the images the clients send, never an image file or a path |
+| `--image-cache-dir-max-gb` | `4` | cap on that directory (0 = no cap). It is enforced per *conversation*, not per file: pictures no remembered conversation claims go first (oldest file first); then a conversation the server remembers but this request is not serving is released **whole**, oldest conversation first, so with `--sessions N` as many conversations as fit keep a complete cache instead of N half-caches; the conversation the request itself is serving is the last to be touched and only in part if its own files alone exceed the cap (end of its prompt first). Trimming also happens at start-up |
| `--image-cache-format` | `fp32` | how the cached rows are stored: `fp32` as the vision merger emits them, `fp16` (half the bytes, **measured bit-exact on this pack**) or `q8` (8 bit with one fp16 scale per row, a quarter, 0.86 % error) |
| `--sessions` | `1` | requests decoded together through the one model (multi-user). `1` = one request at a time, others wait |
| `--row-budget` | `5` when `--sessions` > 1 | caps the verify rows per round by lowering the draft depth when several sessions are busy; `0` = off |
@@ -155,6 +157,15 @@ With `EXL3_CONV_GEMM=0`, `MIOPEN_FIND_MODE=FAST` alone removes the convolution h
pre-tuning, exactly as the default has them. Measurements, the offline pre-generation alternative, and
the comparison with the default configuration: [doc/EXL3_CONV_GEMM.md](../../doc/EXL3_CONV_GEMM.md).
+With `--image-cache-dir`, the pictures the memory budget gives up are written to disk **when they are evicted**
+and read back the next time the client sends them. Because the server also keeps each picture's identity (its
+pseudo token ids) for the life of the process, a restored picture reproduces the prompt token for token and the
+paged KV prefix still matches: measured on 1568x1568 pages as q8 rows, the second and third request of the same
+six-picture conversation reused 98.8 % of the prompt with **no vision pass at all** (18.9 K tokens, 0.9 s prefill
+against 30.9 s cold), from 4 files of 12.3 MiB. A session that fits in `--image-cache-mb` writes nothing; a
+longer one writes each evicted picture once (files are keyed by content, so a picture evicted twice is not
+rewritten). Anything unreadable is dropped and re-encoded: the disk never becomes a reason for a request to fail.
+
### Streaming format
`Content-Type: text/event-stream`. Every frame is a bare `data: {...}` line (no `event:`
name is emitted); frames are:
@@ -197,6 +208,7 @@ simply absent. GLM tool calls are emitted by the model as `<\u200btool_call>name
deliberate so plain prose never triggers the parser; arg values are JSON-parsed when they
parse, otherwise kept as strings.
+
## Diagnostics: the request log
**It is off unless you ask for it.** With `KYOJIN_REQLOG` unset, nothing is opened and every call is a
diff --git a/tools/glm/image_cache_disk.py b/tools/glm/image_cache_disk.py
new file mode 100644
index 0000000..b4fe46a
--- /dev/null
+++ b/tools/glm/image_cache_disk.py
@@ -0,0 +1,302 @@
+#!/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
+reading it back later replaces that with a file read: the server also keeps the picture's identity (its pseudo
+token ids) for the life of the process, so a restored picture reproduces the prompt token for token and the
+paged KV prefix still matches.
+
+Why only evicted pictures: that is the set that ever needs to come back *within* a process, which is the only
+case where the re-prefill can be saved at all (after a restart the KV pool is empty). A session that fits in
+`--image-cache-mb` therefore writes nothing, and a session that does not writes each evicted picture once.
+
+Files hold the rows only (`--image-cache-format` decides their width) plus what the model needs to use them
+again (`grid_thw`); no identity, no image file, no path. Everything here is fail-soft: a missing, corrupt,
+unwritable or full directory means "no second-level cache", never a failed request.
+
+ --image-cache-dir DIR off by default
+ --image-cache-dir-max-gb 4 cap on the directory: a conversation this server no longer remembers goes
+ first (oldest file first), then the end of the one it does. A directory left
+ over the cap by an earlier run is trimmed at start-up the same way.
+"""
+from __future__ import annotations
+
+import os
+import pathlib
+import torch
+
+from exllamav3.tokenizer.mm_embedding import MMEmbedding, QuantizedMMRows
+
+
+def dtype_name(dtype: torch.dtype) -> str:
+ """`torch.float32` -> "float32": what a stored payload records about the rows it holds."""
+ return str(dtype).rsplit(".", 1)[-1]
+
+
+def _rows_payload(emb: Any) -> dict | None:
+ """The rows of one picture, in the form the memory cache holds them (plain tensor or packed holder)."""
+ rows = emb.embeddings
+ if isinstance(rows, QuantizedMMRows):
+ return {"rows_q": rows.q, "rows_scale": rows.scale, "rows_dtype": dtype_name(rows.dtype)}
+ if rows is not None and hasattr(rows, "element_size"):
+ return {"rows": rows.detach().clone()}
+ return None
+
+
+def as_live(live) -> list | None:
+ """`live` as a list of conversations (each a set of content keys), newest first; None means "not told"."""
+ if live is None:
+ return None
+ if isinstance(live, (set, frozenset)):
+ return [set(live)]
+ return [set(keys) for keys in live]
+
+
+class ImageEmbeddingDisk:
+ """Rows of evicted pictures, keyed by content hash, with a process-local identity map.
+
+ `remember()` is called for every picture the tower encodes: it keeps the identity (pseudo ids, alias, token
+ list, MRoPE metadata) that has to be put back for the prompt to be reproduced. `store()` writes the rows of
+ pictures the memory cache just evicted; `fetch()` reads a picture back, restoring the identity when this
+ process knows it (otherwise the picture comes back with fresh ids and only the vision pass is saved). When
+ the directory is over its cap, `collect()` gives up whole conversations rather than single files — see there
+ for why, and for the order it uses.
+ """
+
+ def __init__(self, directory: str, max_bytes: int = 0, start_token: int = 0, end_token: int = 0):
+ self.path = pathlib.Path(directory).expanduser()
+ self.max_bytes = max(0, int(max_bytes))
+ self.start_token, self.end_token = int(start_token), int(end_token)
+ self.enabled = False
+ self.error: str | None = None
+ self._identity: dict[str, dict] = {}
+ self._position: dict[str, int] = {}
+ self._live: list | None = None # conversations the memory cache last said it refers to
+ self._bytes = 0
+ self._files = 0
+ self.stats = {"loaded": 0, "stored": 0, "dropped": 0, "errors": 0}
+ try:
+ self.path.mkdir(parents=True, exist_ok=True)
+ self.enabled = True
+ for entry in self.path.glob("*.pt"):
+ try:
+ self._bytes += entry.stat().st_size
+ self._files += 1
+ except OSError:
+ pass
+ # A directory left over the cap by an earlier run (or a smaller cap now) is trimmed here, oldest
+ # first: at start-up no conversation is remembered yet, so nothing is preferred over anything.
+ self.collect(live=set())
+ except OSError as exc:
+ self.error = f"{type(exc).__name__}: {exc}"
+
+ # -- reporting -------------------------------------------------------------------------------------------
+
+ def describe(self) -> str:
+ if not self.enabled:
+ return f"picture cache on disk off ({self.error})"
+ cap = f"{self.max_bytes / 2 ** 30:.1f} GiB cap" if self.max_bytes else "no cap"
+ return f"picture cache on disk {self.path} ({self._files} files, {self._bytes / 2 ** 20:.1f} MiB, {cap})"
+
+ def report(self) -> dict:
+ return {"files": self._files, "mb": round(self._bytes / 2 ** 20, 1),
+ "cap_mb": round(self.max_bytes / 2 ** 20, 1), **self.stats}
+
+ # -- identity --------------------------------------------------------------------------------------------
+
+ def remember(self, key: str, emb: Any) -> None:
+ """Keep what a later restore needs to reproduce the prompt: the ids and the text that carries them."""
+ if not self.enabled:
+ return
+ self._identity[key] = {
+ "first_index": int(emb.first_index), "last_index": int(emb.last_index),
+ "text_alias": emb.text_alias, "token_string": emb.token_string,
+ "token_list": list(emb.token_list) if emb.token_list is not None else None,
+ "grid_thw": emb.grid_thw, "mrope_merge_size": emb.mrope_merge_size, "metadata": emb.metadata,
+ }
+
+ def position(self, key: str, position: int | None) -> None:
+ """Where the picture sat in the prompt that last used it: what the eviction order is built from."""
+ if position is not None:
+ self._position[key] = int(position)
+
+ # -- files -----------------------------------------------------------------------------------------------
+
+ def _file(self, key: str, mode: str) -> pathlib.Path:
+ return self.path / f"{key}.{mode}.pt"
+
+ def fetch(self, key: str, mode: str):
+ """The picture back, or None. Rows from the file; identity from this process when it is known."""
+ if not self.enabled:
+ return None
+ path = self._file(key, mode)
+ try:
+ blob = torch.load(path, weights_only=True)
+ except FileNotFoundError:
+ return None
+ except Exception: # partial or foreign file: drop it and re-encode
+ self.stats["errors"] += 1
+ self._unlink(path)
+ return None
+ try:
+ rows = blob["rows"] if "rows" in blob else QuantizedMMRows(
+ blob["rows_q"], blob["rows_scale"], getattr(torch, blob["rows_dtype"], torch.float32))
+ rows_count = int(rows.shape[-2])
+ token_string = torch.tensor([[self.start_token] + [-1] * rows_count + [self.end_token]], dtype=torch.long)
+ emb = MMEmbedding(embeddings=rows, token_string=token_string, text_alias=None,
+ grid_thw=blob.get("grid_thw"), mrope_merge_size=blob.get("mrope_merge_size"))
+ emb.metadata = dict(blob.get("metadata") or {})
+ except Exception: # unreadable content: same treatment
+ self.stats["errors"] += 1
+ self._unlink(path)
+ return None
+ known = self._identity.get(key)
+ if known is not None: # put the identity back: the prompt is reproduced
+ emb.first_index, emb.last_index = known["first_index"], known["last_index"]
+ emb.text_alias, emb.token_string = known["text_alias"], known["token_string"]
+ emb.token_list = known["token_list"]
+ emb.grid_thw, emb.mrope_merge_size = known["grid_thw"], known["mrope_merge_size"]
+ emb.metadata = known["metadata"]
+ try:
+ os.utime(path, None) # used now: the last thing the collector takes
+ except OSError:
+ pass
+ self.stats["loaded"] += 1
+ return emb
+
+ def store(self, evicted: list, mode: str, live: list | set | None = None,
+ protect: set | None = None) -> None:
+ """Write the pictures that just left the memory cache. `evicted` is [(key, embedding, position), ...].
+
+ `live` is `ImageEmbeddingCache.live_orders` (remembered conversations, newest first) and `protect` is the
+ conversation this request is serving, so that concurrent requests cannot release each other's cache.
+ """
+ if not self.enabled or not evicted:
+ return
+ if live is not None:
+ self._live = as_live(live) # the conversations the cache still refers to (see collect)
+ for key, emb, position in evicted:
+ self.position(key, position)
+ payload = _rows_payload(emb)
+ if payload is None:
+ continue
+ if getattr(emb, "deepstack_embeddings", None) is not None:
+ continue # not stored: only the merger rows are (GLM has none)
+ payload |= {"grid_thw": getattr(emb, "grid_thw", None),
+ "mrope_merge_size": getattr(emb, "mrope_merge_size", None),
+ "metadata": dict(getattr(emb, "metadata", None) or {})}
+ path = self._file(key, mode)
+ if path.exists():
+ continue # same picture evicted again: already on disk
+ tmp = path.with_suffix(".tmp")
+ try:
+ torch.save(payload, tmp)
+ os.replace(tmp, path)
+ self._bytes += path.stat().st_size
+ self._files += 1
+ self.stats["stored"] += 1
+ except Exception: # disk full, permissions, ...: keep serving
+ self.stats["errors"] += 1
+ try:
+ tmp.unlink()
+ except OSError:
+ pass
+ self.collect(live, protect)
+
+ def _unlink(self, path: pathlib.Path) -> None:
+ try:
+ size = path.stat().st_size
+ path.unlink()
+ self._bytes = max(0, self._bytes - size)
+ self._files = max(0, self._files - 1)
+ except OSError:
+ pass
+
+ def collect(self, live: list | set | None = None, protect: set | None = None) -> int:
+ """Enforce the cap. The unit of eviction is a *conversation*, not a file.
+
+ A conversation's pictures are only worth keeping together: the engine resumes at a checkpoint only when a
+ whole prompt is reproduced, so a conversation that loses one file has already lost its reuse — what is
+ left of it saves a vision pass per picture but nothing else, and it occupies the room a complete
+ conversation would need. So, in order:
+
+ 1. pictures no remembered conversation claims, oldest file first, one at a time (the leftovers of a
+ conversation the user has moved on from and the server has since forgotten);
+ 2. a conversation the server remembers but that is not the one being served, released **whole**, oldest
+ conversation first — with `--sessions N` the caches of N conversations coexist, and this is what keeps
+ as many of them complete as the cap allows;
+ 3. the conversation being served, last of all, and only in part if its own files alone exceed the cap:
+ the end of its prompt goes first, because the head is what a resume point needs.
+
+ `live` is the remembered conversations, newest first (`ImageEmbeddingCache.live_orders`); `protect` is the
+ conversation the calling request is serving (`mine` from `get_many`), which must never be released whole
+ just because some other request happened to be served more recently. Without `protect` the newest
+ remembered conversation plays that part.
+ """
+ if not self.enabled or not self.max_bytes or self._bytes <= self.max_bytes:
+ return 0
+ live = self._live if live is None else as_live(live)
+ protected = set(protect) if protect is not None else (set(live[0]) if live else set())
+ try:
+ files = list(self.path.glob("*.pt"))
+ except OSError:
+ return 0
+
+ def age(entry: pathlib.Path) -> float:
+ try:
+ return entry.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ def within(entry: pathlib.Path) -> float:
+ position = self._position.get(entry.name.split(".")[0])
+ return age(entry) if position is None else -position
+
+ dropped = 0
+ if live is None: # nobody said which conversations are live: position only
+ for entry in sorted(files, key=lambda e: (0, age(e)) if self._position.get(e.name.split(".")[0]) is None
+ else (1, -self._position[e.name.split(".")[0]])):
+ if self._bytes <= self.max_bytes:
+ break
+ self._unlink(entry)
+ dropped += 1
+ self.stats["dropped"] += dropped
+ return dropped
+
+ def group_of(key: str) -> int:
+ """0 = the conversation being served, 1..len(live) = remembered ones (older = larger),
+ len(live)+1 = claimed by none of them."""
+ if key in protected:
+ return 0
+ for rank, keys in enumerate(live):
+ if key in keys:
+ return rank + 1
+ return len(live) + 1
+
+ unclaimed = len(live) + 1
+ groups: dict[int, list] = {}
+ for entry in files:
+ groups.setdefault(group_of(entry.name.split(".")[0]), []).append(entry)
+
+ for group in sorted(groups, reverse=True): # least wanted first
+ if self._bytes <= self.max_bytes:
+ break
+ entries = groups[group]
+ if group == unclaimed: # nobody claims these: the oldest goes first
+ ordered = sorted(entries, key=age)
+ whole = False
+ elif group == 0: # the one being served: only as a last resort, tail first
+ ordered = sorted(entries, key=within)
+ whole = False
+ else: # a remembered conversation: it goes as a unit
+ ordered = sorted(entries, key=age)
+ whole = True
+ for entry in ordered:
+ if not whole and self._bytes <= self.max_bytes:
+ break
+ self._unlink(entry)
+ dropped += 1
+ self.stats["dropped"] += dropped
+ return dropped
diff --git a/tools/glm/image_cache_glm.py b/tools/glm/image_cache_glm.py
index 7a54b88..6e24111 100644
--- a/tools/glm/image_cache_glm.py
+++ b/tools/glm/image_cache_glm.py
@@ -75,6 +75,7 @@ class ImageEmbeddingCache:
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:
@@ -84,6 +85,17 @@ 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()
@@ -118,26 +130,43 @@ class ImageEmbeddingCache:
live.sort()
return [slot for _, slot in stale] + [slot for *_, slot in live]
- def _trim(self) -> int:
- """Evict until both bounds hold. Returns how many entries went."""
- evicted = 0
+ 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]
- evicted += 1
- return evicted
-
- 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.
+ 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 = []
@@ -146,9 +175,13 @@ class ImageEmbeddingCache:
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
@@ -161,5 +194,6 @@ class ImageEmbeddingCache:
self._orders[self._seq] = order
while len(self._orders) > self.max_orders:
self._orders.popitem(last=False)
- self._trim()
+ self._last_order = order
+ self._trim(evicted)
return out
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 04a8066..668e418 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -119,6 +119,10 @@ IMAGE_CACHE_AUTO_SHARE = 0.02
# because serve.py must not import exllamav3 before SPEED_ENV is applied; a test checks it matches
# exllamav3.tokenizer.mm_embedding.MM_QUANT_MODES.
IMAGE_CACHE_FORMATS = ("fp32", "fp16", "q8")
+# Cap on the second-level picture cache (--image-cache-dir). It holds only the pictures the memory budget had to
+# evict, so it is deliberately independent of --image-cache-mb: 4 GiB is 87 manga pages as fp32, 175 as fp16 and
+# 349 as q8, which covers the sessions this server is run for. 0 = no cap.
+IMAGE_CACHE_DIR_MAX_GB = 4.0
def physical_ram_bytes() -> int:
@@ -470,7 +474,8 @@ class ResidentEngine:
def __init__(self, model_path: str, max_history: int = 1, max_ctx: int = 131072, num_draft: int = 1,
vision: bool = True, sessions: int = 1,
image_cache_bytes: int | None = None, image_cache_items: int = 0,
- image_cache_format: str = "fp32"):
+ image_cache_format: str = "fp32",
+ image_cache_dir: str | None = None, image_cache_dir_max_gb: float = IMAGE_CACHE_DIR_MAX_GB):
import torch
from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer
from exllamav3.generator import generator as GM
@@ -522,6 +527,14 @@ class ResidentEngine:
self.vision = None
self.image_cache_format = image_cache_format
self.emb_cache = make_image_cache(image_cache_bytes, image_cache_items, sessions)
+ # Second-level cache: the rows of the pictures the memory cache evicts (--image-cache-dir, off by default)
+ self.emb_disk = None
+ if image_cache_dir:
+ from image_cache_disk import ImageEmbeddingDisk # imports exllamav3: only once it is wanted
+ self.emb_disk = ImageEmbeddingDisk(
+ image_cache_dir, int(max(0.0, float(image_cache_dir_max_gb)) * 2 ** 30),
+ start_token=int(getattr(self.config, "vision_start_token_id", 0) or 0),
+ end_token=int(getattr(self.config, "vision_end_token_id", 0) or 0))
if vision:
self.vision = self._load_vision()
self.supports_vision = self.vision is not None
@@ -609,10 +622,15 @@ class ResidentEngine:
match up to it, so `first_missing` (index of the first picture not held) is the number to watch. This
only reports: the cache policy itself is untouched."""
cache = self.emb_cache
- entries_before = len(cache)
+ disk = getattr(self, "emb_disk", None)
built: set[int] = set()
+ evicted: list = []
mode = getattr(self, "image_cache_format", "fp32")
+ def fetch(image, key):
+ """One picture back from the second-level cache, or None: its identity comes back with it."""
+ return disk.fetch(key, mode) if disk is not None else None
+
def build(image):
t0 = time.perf_counter()
emb = self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=image)
@@ -625,7 +643,20 @@ class ResidentEngine:
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
- out = cache.get_many(images, build)
+ mine: set = set() # the pictures of *this* prompt: the conversation this request serves
+ out = cache.get_many(images, build, evicted, fetch, mine)
+ if disk is not None:
+ # Every picture of this request keeps its identity, so a later restore reproduces the prompt; then
+ # the ones that just left memory are written, outside the cache lock. A session that fits in
+ # --image-cache-mb writes nothing, one that does not writes each evicted picture once
+ # (see image_cache_disk.py). The cache hands over (key, embedding, position-in-this-prompt), the
+ # conversations it still remembers and the keys of this one, so the collector can give up an
+ # abandoned conversation first and never release the cache of a conversation that is being served.
+ for (_, key), emb in zip(images, out):
+ disk.remember(key, emb)
+ disk.store(evicted, mode, live=cache.live_orders, protect=mine)
+ if stats is not None:
+ stats["disk"] = disk.report()
if stats is not None:
missed = [id(emb) in built for emb in out]
misses = sum(missed)
@@ -635,7 +666,9 @@ class ResidentEngine:
"entries": len(cache), "mb": round(cache.nbytes / 2 ** 20, 1),
"budget_mb": round(float(getattr(cache, "max_bytes", 0)) / 2 ** 20, 1),
"item_cap": int(getattr(cache, "max_items", 0) or 0),
- "evicted": max(0, entries_before + misses - len(cache)),
+ # real evictions, not a difference of counts: a picture that came back from disk also enters
+ # the cache, so entries_before + misses - len() would miss those
+ "evicted": len(evicted),
})
return out
@@ -1729,6 +1762,16 @@ def main() -> None:
"Strix Halo: about 50 MiB per manga page, 1 MB per small crop")
parser.add_argument("--image-cache-items", type=int, default=0,
help="optional cap on how many pictures are held at once (0 = only the byte budget)")
+ parser.add_argument("--image-cache-dir", default=None,
+ help="directory of a second-level picture cache: the rows of the pictures the memory "
+ "budget evicts are written there and read back, so a picture that comes back costs "
+ "a file read instead of a vision pass plus a re-prefill of everything after it. "
+ "Off by default (nothing is written). Holds rows derived from the images the "
+ "clients send, never an image file or a path")
+ parser.add_argument("--image-cache-dir-max-gb", type=float, default=IMAGE_CACHE_DIR_MAX_GB,
+ help=f"cap on that directory, in GiB (default {IMAGE_CACHE_DIR_MAX_GB:g}; 0 = no cap). The "
+ "pictures the memory cache is most likely to need again are the earliest ones, so "
+ "the collector drops the end of a prompt first")
parser.add_argument("--image-cache-format", choices=IMAGE_CACHE_FORMATS, default="fp32",
help="how the cached image embeddings are stored in host memory: fp32 as the vision merger "
"emits them (default), fp16 (half the bytes, bit-exact on this pack) or q8 (8 bit with one fp16 scale per row, a quarter, "
@@ -1789,13 +1832,16 @@ def main() -> None:
engine = ResidentEngine(args.model, max_history=args.max_history or max(args.num_draft, 1), max_ctx=args.max_ctx, num_draft=args.num_draft,
vision=not args.no_vision, sessions=args.sessions,
image_cache_bytes=image_cache_bytes, image_cache_items=args.image_cache_items,
- image_cache_format=args.image_cache_format)
+ image_cache_format=args.image_cache_format,
+ image_cache_dir=args.image_cache_dir, image_cache_dir_max_gb=args.image_cache_dir_max_gb)
engine.row_budget = (5 if args.row_budget is None else args.row_budget) if args.sessions > 1 else 0
template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")
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)
+ if args.image_cache_dir:
+ 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.
# EXL3_SERVE_WARMUP=0 skips it.
if os.environ.get("EXL3_SERVE_WARMUP", "1") != "0":
@@ -1846,6 +1892,8 @@ 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_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,
heartbeat_s=reqlog.heartbeat_s)
sock = startup_health.finish() # the early listener's open socket: no refused connection
if sock is not None:
diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.py
index b71dae4..eb32e03 100644
--- a/tools/glm/test_serve_glm_additional.py
+++ b/tools/glm/test_serve_glm_additional.py
@@ -16,6 +16,7 @@ import asyncio
import base64
import io
import os
+import pathlib
import sys
import tempfile
import unittest
@@ -86,6 +87,117 @@ def vision_engine():
return eng, calls
+def disk_engine(directory, budget_bytes: int = 768, mode: str = "fp32", cap_bytes: int = 0, on_disk: bool = True):
+ """An engine whose _embed() runs over a real memory cache *and* a real second-level cache on disk.
+
+ The fake pictures carry everything a restore needs (identity, token list, MRoPE metadata) so a test can ask
+ whether the prompt would be reproduced: unlike the tower, the disk has to give back the same pseudo ids.
+ """
+ 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.mm_length = 3
+ self.last_index = self.first_index + self.mm_length
+ self.embeddings = torch.zeros(3, 64, dtype=torch.half)
+ self.deepstack_embeddings = None
+ self.grid_thw = (1, 1, 1)
+ self.mrope_merge_size = 2
+ self.metadata = {"original_size": (8, 8)}
+ self.token_string = torch.tensor([[7] + list(range(self.first_index, self.last_index)) + [8]])
+ self.token_list = self.token_string[0].tolist()
+ self.text_alias = f"<$EMB_{self.first_index}$>"
+
+ class Tower:
+ def get_image_embeddings(self, *args, **kw):
+ calls.append(1)
+ return Emb()
+
+ eng = object.__new__(serve.ResidentEngine)
+ eng.emb_cache = ImageEmbeddingCache(max_bytes=budget_bytes)
+ eng.vision, eng.tokenizer = Tower(), None
+ eng.image_cache_format = mode
+ eng.emb_disk = None
+ if on_disk:
+ from image_cache_disk import ImageEmbeddingDisk
+ eng.emb_disk = ImageEmbeddingDisk(directory, max_bytes=cap_bytes, start_token=7, end_token=8)
+ return eng, calls
+
+
+def tiny_pictures(count: int):
+ """Whatever `_embed` needs: a PIL image and its content key."""
+ from PIL import Image
+ return [(Image.new("RGB", (8, 8), (i * 30 % 255, 0, 0)), f"key{i}") for i in range(count)]
+
+
+class ImageDiskCacheTests(unittest.TestCase):
+ """--image-cache-dir: what leaves memory is written once, and comes back with its identity."""
+
+ def test_the_default_cap_is_four_gib(self):
+ self.assertEqual(serve.IMAGE_CACHE_DIR_MAX_GB, 4.0)
+ self.assertNotIn("EXL3_IMAGE_CACHE_DIR", os.environ) # a flag, not an environment variable
+
+ def test_only_what_memory_gave_up_is_written(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ eng, calls = disk_engine(tmp, budget_bytes=768) # room for two of the four pictures
+ images = tiny_pictures(4)
+ serve.ResidentEngine._embed(eng, images)
+ self.assertEqual(len(calls), 4) # a cold pass encodes all four
+ self.assertEqual(len(list(pathlib.Path(tmp).glob("*.pt"))), 2) # ... and two were evicted
+ self.assertEqual(eng.emb_disk.report()["stored"], 2)
+
+ serve.ResidentEngine._embed(eng, images) # same conversation again
+ self.assertEqual(len(calls), 4) # two from memory, two from disk: no vision pass
+ self.assertEqual(eng.emb_disk.report()["loaded"], 2)
+
+ def test_a_restored_picture_keeps_the_ids_the_prompt_was_built_from(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ eng, calls = disk_engine(tmp, budget_bytes=384) # room for one
+ images = tiny_pictures(2)
+ first = serve.ResidentEngine._embed(eng, images)
+ self.assertEqual(len(list(pathlib.Path(tmp).glob("*.pt"))), 1)
+ self.assertEqual(first[1].embeddings.shape, (3, 64)) # the second picture went to disk
+
+ again = serve.ResidentEngine._embed(eng, images)
+ self.assertEqual(len(calls), 2) # no second vision pass
+ self.assertEqual(again[1].first_index, first[1].first_index)
+ self.assertEqual(again[1].token_list, first[1].token_list)
+ self.assertEqual(again[1].text_alias, first[1].text_alias)
+ self.assertEqual(again[1].grid_thw, first[1].grid_thw)
+
+ def test_without_a_directory_nothing_is_written_and_the_tower_runs_again(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ eng, calls = disk_engine(tmp, budget_bytes=768, on_disk=False)
+ images = tiny_pictures(4)
+ serve.ResidentEngine._embed(eng, images)
+ serve.ResidentEngine._embed(eng, images)
+ self.assertEqual(list(pathlib.Path(tmp).rglob("*.pt")), [])
+ self.assertEqual(len(calls), 6) # 4 cold, then the 2 that memory dropped
+
+ def test_an_unusable_directory_does_not_stop_a_request(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ blocker = pathlib.Path(tmp) / "blocker"
+ blocker.write_text("not a directory")
+ eng, calls = disk_engine(str(blocker), budget_bytes=384)
+ self.assertFalse(eng.emb_disk.enabled)
+ out = serve.ResidentEngine._embed(eng, tiny_pictures(2))
+ self.assertEqual(len(out), 2)
+ self.assertEqual(len(calls), 2)
+
+ def test_the_collector_runs_from_the_request_path(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ eng, _ = disk_engine(tmp, budget_bytes=384, cap_bytes=1) # cap for nothing at all
+ serve.ResidentEngine._embed(eng, tiny_pictures(2))
+ self.assertEqual(list(pathlib.Path(tmp).glob("*.pt")), [])
+ self.assertGreaterEqual(eng.emb_disk.report()["dropped"], 1)
+
+
class ImageCacheBudgetTests(unittest.TestCase):
"""--image-cache-mb / --image-cache-items, and the automatic budget behind them."""