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
GLM: a cached picture row says which model and settings produced it
MangetsuCd4c97ca4a58e
diff --git a/doc/logging.md b/doc/logging.mdindex 78b4239..309cb1f 100644--- a/doc/logging.md+++ b/doc/logging.md@@ -86,7 +86,7 @@ elsewhere. They go through the log's raw `log()` call, and no other server needs|---|---|---|| `serve_start` | once, when the server is ready | `model`, `model_id`, `pid`, `ctx`, `cache_tokens`, `sessions`, `num_draft`, `row_budget`, `max_history`, `vision`, `conv_gemm`, `dense_tune`, `moe_fused`, `image_cache_mb`, `image_cache_items`, `image_cache_format`, `image_cache_policy`, `image_cache_dir`, `image_cache_dir_cap_mb`, `image_cache_dir_lock_s`, `heartbeat_s`, `sse_ping_s` || `img_cache` | an image request, after `job_done` | `imgs`, `hits`, `misses`, `first_missing`, `entries`, `mb`, `budget_mb`, `item_cap`, `evicted` |-| `img_disk` | the same request, when `--image-cache-dir` is set | `files`, `mb`, `cap_mb`, `locked`, `loaded`, `stored`, `dropped`, `skipped`, `written_bytes`, `written_mb`, `skipped_mb`, `errors` |+| (inside `img_cache`) | the same request, as the `disk=` report, when the disk tier is on | `env`, `files`, `mb`, `cap_mb`, `locked`, `loaded`, `stored`, `dropped`, `skipped`, `written_bytes`, `written_mb`, `skipped_mb`, `errors` |`img_cache` is the line for image sessions: `hits` and `misses` are the embeddings the cache already heldand the ones it re-encoded, and **`first_missing` is the index of the first picture that had to bediff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 0ce30cb..7b8916a 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -32,7 +32,7 @@ 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` | `1024` | host memory for the decoded image embeddings, in MiB, one pool shared by all sessions; `0` = no byte 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` | `~/.cache/kyojin/image-embeddings` | directory of the second-level picture cache; used only when `--image-cache-dir-max-gb` is set. A file is named after the pack and its preprocessing settings as well as the picture, so another model or other pixel settings never reach rows computed with the old ones || `--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 || `--image-cache-format` | `fp32` | row storage: `fp32` as the vision merger emits them, `fp16` (half the bytes, bit-exact on this pack) or `q8` (8 bit with one fp16 scale per row, a quarter, 0.86 % error) |@@ -163,7 +163,13 @@ the comparison with the default configuration: [doc/EXL3_CONV_GEMM.md](../../docWith `--image-cache-dir-max-gb` (off by default), the pictures the memory budget gives up are written to disk**when they are evicted** and read back when the client sends them again. It only ever helps a conversation withmore pictures than `--image-cache-mb` holds: a session that fits writes nothing, and a longer one writes each-evicted picture once (files are keyed by content, so a picture evicted twice is not rewritten). The directory is+evicted picture once (files are keyed by content, so a picture evicted twice is not rewritten). A row is only+worth reusing while the model and the preprocessing stay the same, so a file is named after both: a short+fingerprint of the pack and its resize/canvas settings, then the content key and the storage format. Start with+another model, another pack or other pixel settings and the files already there are simply not addressed any more -+they stay until the directory cap takes them, and the request ends up encoding the pictures again. Both the+fingerprint and the fields it was built from are in the log (`image_cache_env` on `serve_start`, `env` inside the+`disk=` report of `img_cache`), so a fingerprint that changed between two runs can be compared. The directory is`--image-cache-dir`, `~/.cache/kyojin/image-embeddings` unless changed, and anything unreadable in it is droppedand 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 evictedpictures are the end of a prompt, restoring them completes the prompt again and the paged prefix survives, which@@ -228,7 +234,7 @@ The log is shared code and its switches, format, every event, the shared/GLM-onlthe output accounting are documented once, in [doc/logging.md](../../doc/logging.md). What belongs tothis server:-* **its events are the reference vocabulary** — `img_cache`, `img_disk` and `serve_start` exist here+* **its events are the reference vocabulary** — `img_cache` and `serve_start` exist herebecause this is the server with an image cache, a disk tier and a start-up record; the other two runthe same `Lifecycle` and `tools/test_serve_logging.py` holds all three to the same field lists;* the start-up lines an operator sees are `serve: request log …` and `serve: SSE keep-alive …`;diff --git a/tools/glm/image_cache_disk.py b/tools/glm/image_cache_disk.pyindex 91bcfd8..7c74fff 100644--- a/tools/glm/image_cache_disk.py+++ b/tools/glm/image_cache_disk.py@@ -36,6 +36,17 @@ from exllamav3.tokenizer.mm_embedding import MMEmbedding, QuantizedMMRowsfrom serve_reqlog import restrict, secure_dir, secure_open+def content_key(path: pathlib.Path) -> str:+ """The picture key out of a file name: `<env_fingerprint>.<key>.<mode>.pt`, or `<key>.<mode>.pt`.++ The parts after the fingerprint are fields of their own, so the key is the part before the mode and this+ cannot be "the first part": with a fingerprint in front that would return the fingerprint itself and every+ file would look like the same picture. Files written before the fingerprint existed have no prefix, and+ then the first part is the key."""+ parts = path.name.split(".")+ return parts[1] if len(parts) > 3 else parts[0]++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]@@ -82,8 +93,14 @@ class ImageEmbeddingDisk:"""def __init__(self, directory: str, max_bytes: int = 0, start_token: int = 0, end_token: int = 0,- lock_s: float = 0.0):+ lock_s: float = 0.0, env_fingerprint: str = ""):self.path = pathlib.Path(directory).expanduser()+ # What the rows in this directory were computed with: the model and the settings that decide how a+ # picture is resized and encoded (`make_env_fingerprint` in the server). It names the files, so a+ # restart with another model or other pixel settings cannot reach rows computed with the old ones,+ # and a file that is somehow in the way is refused rather than injected (`fetch`). Empty means "not+ # told", which is what the tests that only exercise the store/collect logic want.+ self.env_fingerprint = str(env_fingerprint or "")self.max_bytes = max(0, int(max_bytes))self.start_token, self.end_token = int(start_token), int(end_token)# A conversation keeps the room its cache took for this long (0 = no tenure). The clock starts when the@@ -134,6 +151,7 @@ class ImageEmbeddingDisk:def report(self) -> dict:return {"files": self._files, "mb": round(self._bytes / 2 ** 20, 1),+ "env": self.env_fingerprint or None,"written_mb": round(self.stats["written_bytes"] / 2 ** 20, 3),"skipped_mb": round(self.stats["skipped_bytes"] / 2 ** 20, 3),"cap_mb": round(self.max_bytes / 2 ** 20, 1),@@ -143,7 +161,7 @@ class ImageEmbeddingDisk:def _present(self) -> set:try:- return {entry.name.split(".")[0] for entry in self.path.glob("*.pt")}+ return {content_key(entry) for entry in self.path.glob("*.pt")}except OSError:return set()@@ -171,7 +189,8 @@ class ImageEmbeddingDisk:# -- files -----------------------------------------------------------------------------------------------def _file(self, key: str, mode: str) -> pathlib.Path:- return self.path / f"{key}.{mode}.pt"+ prefix = f"{self.env_fingerprint}." if self.env_fingerprint else ""+ return self.path / f"{prefix}{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."""@@ -186,6 +205,11 @@ class ImageEmbeddingDisk:self.stats["errors"] += 1self._unlink(path)return None+ if self.env_fingerprint and blob.get("env_fingerprint") not in (None, self.env_fingerprint):+ # reachable but computed with something else: drop it and let the caller encode the picture+ self.stats["errors"] += 1+ self._unlink(path)+ return Nonetry:rows = blob["rows"] if "rows" in blob else QuantizedMMRows(blob["rows_q"], blob["rows_scale"], getattr(torch, blob["rows_dtype"], torch.float32))@@ -258,6 +282,10 @@ class ImageEmbeddingDisk:payload |= {"grid_thw": getattr(emb, "grid_thw", None),"mrope_merge_size": getattr(emb, "mrope_merge_size", None),"metadata": dict(getattr(emb, "metadata", None) or {})}+ if self.env_fingerprint:+ # a second copy of the identity, in the file itself: the name already keeps a different+ # environment out, this makes a file that got in some other way visible instead of silent+ payload["env_fingerprint"] = self.env_fingerprintpath = self._file(key, mode)tmp = path.with_suffix(".tmp")try:@@ -284,7 +312,7 @@ class ImageEmbeddingDisk:self.collect(live, protect)def _unlink(self, path: pathlib.Path) -> None:- self._locked.pop(path.name.split(".")[0], None)+ self._locked.pop(content_key(path), None)try:size = path.stat().st_sizepath.unlink()@@ -330,16 +358,16 @@ class ImageEmbeddingDisk:return 0.0def within(entry: pathlib.Path) -> float:- position = self._position.get(entry.name.split(".")[0])+ position = self._position.get(content_key(entry))return age(entry) if position is None else -positiondropped = 0if 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]])):+ for entry in sorted(files, key=lambda e: (0, age(e)) if self._position.get(content_key(e)) is None+ else (1, -self._position[content_key(e)])):if self._bytes + reserve <= self.max_bytes:break- if self._locked_now(entry.name.split(".")[0]):+ if self._locked_now(content_key(entry)):continueself._unlink(entry)dropped += 1@@ -360,7 +388,7 @@ class ImageEmbeddingDisk:unclaimed = len(live) + 1groups: dict[int, list] = {}for entry in files:- groups.setdefault(group_of(entry.name.split(".")[0]), []).append(entry)+ groups.setdefault(group_of(content_key(entry)), []).append(entry)for group in sorted(groups, reverse=True): # least wanted firstif self._bytes + reserve <= self.max_bytes:@@ -372,12 +400,12 @@ class ImageEmbeddingDisk:ordered, whole = sorted(entries, key=within), Falseelse: # a remembered conversation: it goes as a unitordered, whole = sorted(entries, key=age), True- if whole and any(self._locked_now(e.name.split(".")[0]) for e in entries):+ if whole and any(self._locked_now(content_key(e)) for e in entries):continue # still within its tenure: leave it alone for nowfor entry in ordered:if not whole and self._bytes + reserve <= self.max_bytes:break- if not whole and self._locked_now(entry.name.split(".")[0]):+ if not whole and self._locked_now(content_key(entry)):continueself._unlink(entry)dropped += 1@@ -391,7 +419,7 @@ class ImageEmbeddingDisk:def _break_tenure(self, files: list, reserve: int = 0) -> int:"""Last resort: the cap has to hold, so the tenures closest to expiring go first."""dropped = 0- for entry in sorted(files, key=lambda e: self._locked.get(e.name.split(".")[0], 0.0)):+ for entry in sorted(files, key=lambda e: self._locked.get(content_key(e), 0.0)):if self._bytes + reserve <= self.max_bytes:breakif not entry.exists():diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex cb29eb1..c612525 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -147,8 +147,58 @@ def make_image_cache(image_cache_bytes: int | None = None, image_cache_items: in**({} if policy is None else {"policy": policy}))+def env_fingerprint_source(model_dir: str | None, config) -> dict:+ """What the rows in the picture cache on disk were computed with (see `make_env_fingerprint`).++ A stored row is only worth keeping while the model and the preprocessing that produced it stay the+ same, and the file name has to say so or a restart with another model would inject rows from the old+ one. What goes in: the pack directory (two packs of the same architecture encode differently), the+ vision settings that decide the resize and the canvas, and the size and mtime of the visual weight+ shards - the cheap stand-in for hashing ~1.5 GB at every start. A pack that is converted again keeps+ its name and its config, so its rows are caught only if its shards change size or date; the disk tier+ is a cache, and a miss costs an encode, not correctness of the answer.+ """+ source: dict = {"model": Path(model_dir).name if model_dir else "?"}+ for attr in ("vision_config", "vision_pp"):+ part = getattr(config, attr, None)+ if part is None:+ continue+ for field in ("patch_size", "merge_size", "temporal_patch_size", "min_image_tokens",+ "max_image_tokens", "spatial_merge_size", "hidden_size"):+ value = getattr(part, field, None)+ if value is not None:+ source[f"{attr}.{field}"] = value+ if model_dir:+ index = Path(model_dir) / "model.safetensors.index.json"+ try:+ weight_map = json.loads(index.read_text())["weight_map"]+ shards = sorted({name for key, name in weight_map.items()+ if "visual" in key or "vision" in key})+ for name in shards:+ shard = Path(model_dir) / name+ stat = shard.stat()+ source[f"shard.{name}"] = f"{stat.st_size}:{int(stat.st_mtime)}"+ except (OSError, KeyError, ValueError):+ pass+ return source+++def make_env_fingerprint(model_dir: str | None, config) -> str:+ """`env_fingerprint_source` reduced to a short name that can go in a file name.++ Hashed rather than spelled out, so the name stays portable and fixed-length; the source dictionary is+ written into the request log too - `image_cache_env` on the `serve_start` line and `env` inside the+ `disk=` report of `img_cache` - which is what makes a fingerprint that changed between two runs visible+ instead of mysterious.+ """+ import hashlib+ source = env_fingerprint_source(model_dir, config)+ blob = json.dumps(source, sort_keys=True).encode()+ return hashlib.sha256(blob).hexdigest()[:16]++def make_image_disk(image_cache_dir: str | None, image_cache_dir_max_gb: float, image_cache_dir_lock_s: float,- start_token: int = 0, end_token: int = 0):+ start_token: int = 0, end_token: int = 0, env_fingerprint: str = ""):"""The second-level picture cache, or None when it is off (`--image-cache-dir-max-gb` 0 or less).A cap is required: the disk cache is meant for conversations with more pictures than `--image-cache-mb`@@ -160,7 +210,8 @@ def make_image_disk(image_cache_dir: str | None, image_cache_dir_max_gb: float,return ImageEmbeddingDisk(image_cache_dir or IMAGE_CACHE_DIR_DEFAULT,int(float(image_cache_dir_max_gb) * 2 ** 30),start_token=int(start_token or 0), end_token=int(end_token or 0),- lock_s=max(0.0, float(image_cache_dir_lock_s)))+ lock_s=max(0.0, float(image_cache_dir_lock_s)),+ env_fingerprint=env_fingerprint)def apply_eh_sidecar_default(model_dir: str | None = None) -> str:@@ -522,9 +573,11 @@ class ResidentEngine: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. Off unless a cap is given# (--image-cache-dir-max-gb > 0), because the memory budget above is what a normal session needs.+ self.env_fingerprint = make_env_fingerprint(model_path, self.config)self.emb_disk = make_image_disk(image_cache_dir, image_cache_dir_max_gb, image_cache_dir_lock_s,getattr(self.config, "vision_start_token_id", 0),- getattr(self.config, "vision_end_token_id", 0))+ getattr(self.config, "vision_end_token_id", 0),+ env_fingerprint=self.env_fingerprint)if vision:self.vision = self._load_vision()self.supports_vision = self.vision is not None@@ -1871,6 +1924,7 @@ def main() -> 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,+ image_cache_env=getattr(engine, "env_fingerprint", None),heartbeat_s=reqlog.heartbeat_s,sse_ping_s=ping.interval_s or None)sock = startup_health.finish() # the early listener's open socket: no refused connectiondiff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex ab826c8..a75ea7f 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -88,7 +88,7 @@ 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, policy: str = "tail"):+ lock_s: float = 0.0, policy: str = "tail", fingerprint: str = ""):"""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@@ -130,7 +130,8 @@ def disk_engine(directory, budget_bytes: int = 768, mode: str = "fp32", cap_byteeng.emb_disk = Noneif on_disk:from image_cache_disk import ImageEmbeddingDisk- eng.emb_disk = ImageEmbeddingDisk(directory, max_bytes=cap_bytes, start_token=7, end_token=8, lock_s=lock_s)+ eng.emb_disk = ImageEmbeddingDisk(directory, max_bytes=cap_bytes, start_token=7, end_token=8,+ lock_s=lock_s, env_fingerprint=fingerprint)return eng, calls@@ -226,6 +227,48 @@ class ImageDiskCacheTests(unittest.TestCase):self.assertEqual(len(out), 2)self.assertEqual(len(calls), 2)+ def test_the_model_fingerprint_is_stable_and_setting_specific(self):+ """The name of every cached row comes from here, so it has to be stable and to notice a change.++ A fingerprint that moved on its own would make the disk tier unreachable and turn every restart into+ re-encoding; one that ignored a setting would hand back rows the new setting never produced. Built+ from a synthetic pack here, so the check does not need the 93 GB one to be on the machine."""+ import json+ import tempfile+ from serve import env_fingerprint_source, make_env_fingerprint++ class Pre:+ patch_size, merge_size, temporal_patch_size = 14, 2, 2+ min_image_tokens, max_image_tokens = 16, 8000+ spatial_merge_size, hidden_size = 2, 1024++ class Config:+ vision_config, vision_pp = Pre(), Pre()++ def pack(directory: pathlib.Path, name: str, tokens: int = 8000) -> str:+ """A pack is its directory name, its configuration and the size/date of the visual shards."""+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "model.safetensors.index.json").write_text(json.dumps(+ {"weight_map": {"model.visual.blocks.0.w": f"{name}.safetensors"}}))+ (directory / f"{name}.safetensors").write_bytes(b"x" * (1024 if tokens == 8000 else 2048))+ config = Config()+ config.vision_pp = type("Pre", (Pre,), {"max_image_tokens": tokens})()+ return make_env_fingerprint(str(directory), config)++ with tempfile.TemporaryDirectory() as tmp:+ base = pathlib.Path(tmp)+ first = pack(base / "pack-a", "shard")+ self.assertEqual(first, pack(base / "pack-a", "shard")) # same pack, same name+ self.assertNotEqual(first, pack(base / "pack-b", "shard")) # another pack directory+ self.assertNotEqual(first, pack(base / "pack-a", "shard", tokens=7999)) # another canvas budget++ source = env_fingerprint_source(str(base / "pack-a"), Config())+ for field in ("vision_pp.patch_size", "vision_pp.merge_size", "vision_pp.max_image_tokens"):+ self.assertIn(field, source)+ self.assertEqual(source["model"], "pack-a")+ self.assertTrue(any(k.startswith("shard.") for k in source)) # the weights are in it+ json.dumps(source, sort_keys=True) # and it can be logged+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.@@ -240,6 +283,77 @@ class ImageDiskCacheTests(unittest.TestCase):self.assertTrue(serve.IMAGE_CACHE_DIR_DEFAULT.endswith(".cache/kyojin/image-embeddings"))self.assertEqual(serve.IMAGE_CACHE_DIR_LOCK_S, 300.0)+ def test_the_disk_rows_are_kept_per_environment(self):+ """A row is only reusable while the model and the preprocessing stay the same.++ The file name carries the fingerprint of what produced it, so a restart with another pack or other+ pixel settings cannot reach the old rows; they stay on disk until the cap takes them, the same+ treatment as any other unusable file."""+ with tempfile.TemporaryDirectory() as tmp:+ eng, _ = disk_engine(tmp, budget_bytes=384, cap_bytes=64 << 20, fingerprint="aaaa") # room for one+ images = tiny_pictures(2)+ serve.ResidentEngine._embed(eng, images)+ names = sorted(p.name for p in pathlib.Path(tmp).glob("*.pt"))+ self.assertEqual(len(names), 1)+ self.assertTrue(names[0].startswith("aaaa."), names) # the fingerprint names the file+ self.assertEqual(eng.emb_disk.report()["env"], "aaaa")++ other, calls = disk_engine(tmp, budget_bytes=384, cap_bytes=64 << 20, fingerprint="bbbb")+ images = tiny_pictures(2)+ serve.ResidentEngine._embed(other, images)+ self.assertEqual(len(calls), 2) # nothing of ours is reachable+ self.assertEqual(len(list(pathlib.Path(tmp).glob("*.pt"))), 2)++ again, calls = disk_engine(tmp, budget_bytes=384, cap_bytes=64 << 20, fingerprint="aaaa") # a restart+ serve.ResidentEngine._embed(again, images)+ self.assertEqual(len(calls), 1) # the second picture came back+ self.assertEqual(len(list(pathlib.Path(tmp).glob("*.pt"))), 2) # and nothing was written again++ def test_a_row_from_another_environment_is_refused_rather_than_injected(self):+ """The name keeps another environment out. The copy inside the file is the second line: a file that+ got there some other way (copied in, restored from a backup, a name collision) is refused and+ dropped, rather than having its rows injected into a prompt as if this environment had made them."""+ with tempfile.TemporaryDirectory() as tmp:+ eng, _ = disk_engine(tmp, budget_bytes=384, cap_bytes=64 << 20, fingerprint="aaaa")+ serve.ResidentEngine._embed(eng, tiny_pictures(2))+ path = next(pathlib.Path(tmp).glob("*.pt"))+ import torch+ blob = torch.load(path, weights_only=True)+ blob["env_fingerprint"] = "bbbb" # the contents say another environment+ torch.save(blob, path)++ disk = eng.emb_disk+ self.assertIsNone(disk.fetch(path.name.split(".")[1], "fp32")) # refused, not injected+ self.assertEqual(disk.stats["errors"], 1)+ self.assertFalse(path.exists()) # and dropped, so it is encoded fresh++ def test_the_fingerprint_is_not_mistaken_for_the_picture_key(self):+ """Every part of the disk cache that names a picture reads the key out of the file name - the+ eviction grouping, the tenure map, the set of pictures present. With the fingerprint in front, "the+ first part" is the fingerprint, which would make every file of one environment look like the same+ picture: the grouping would then free whatever it walks over instead of the pictures the cap is meant+ to give up, and the files of the environment being served would be sacrificed for the files of an+ old one. The disk layer's whole point is that a conversation keeps the head of its prompt, so the+ reading is pinned here."""+ import tempfile+ from image_cache_disk import content_key+ self.assertEqual(content_key(pathlib.Path("81a20c24930c549a.abcdef.q8.pt")), "abcdef")+ self.assertEqual(content_key(pathlib.Path("abcdef.fp32.pt")), "abcdef") # before the prefix++ with tempfile.TemporaryDirectory() as tmp:+ # room for one picture in memory, so the other two are written to disk+ eng, _ = disk_engine(tmp, budget_bytes=384, cap_bytes=64 << 20, fingerprint="aaaa")+ serve.ResidentEngine._embed(eng, tiny_pictures(3))+ disk = eng.emb_disk+ written = sorted(p.name for p in pathlib.Path(tmp).glob("*.pt"))+ self.assertEqual(len(written), 2, written)+ # the keys of the files this cache holds: two pictures, not one fingerprint twice+ self.assertEqual(disk._present(), {"key1", "key2"})+ # ...and the same reading for a directory written before the fingerprint existed+ for entry in pathlib.Path(tmp).glob("aaaa.*.pt"):+ entry.rename(entry.with_name(entry.name.split(".", 1)[1]))+ self.assertEqual(disk._present(), {"key1", "key2"})+def test_the_disk_cache_needs_a_cap(self):# `--image-cache-dir-max-gb 0` (the default) is off; any positive value is a real cap, never "unlimited".self.assertIsNone(serve.make_image_disk(serve.IMAGE_CACHE_DIR_DEFAULT, 0, 300.0))diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.mdindex a294efe..992e584 100644--- a/tools/mimo/SERVE.md+++ b/tools/mimo/SERVE.md@@ -65,7 +65,7 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.The log and the stream keep-alive are shared code: switches, format, every event and how to read theoutput accounting are documented once, in [doc/logging.md](../../doc/logging.md). This server writes the-same events as GLM except for `serve_start`, `img_cache` and `img_disk` (GLM's image cache and disk tier)+same events as GLM except for `serve_start` and `img_cache` (GLM's image cache and its disk tier)and `sse_ping` (this server's pinger writes no log line); `tools/test_serve_logging.py` checks the sharedpart against all three servers at once. Turn it on with `KYOJIN_REQLOG=<path>` (or `1`) and hold a silentstream open with `KYOJIN_SSE_PING_S=<seconds>`; both are in [doc/env_vars.md](../../doc/env_vars.md).diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdindex effa426..bff5db1 100644--- a/tools/qwen/SERVE.md+++ b/tools/qwen/SERVE.md@@ -105,7 +105,7 @@ The pack is tied to one set of weights: download it from the same model repo.The log and the stream keep-alive are shared code: switches, format, every event and how to read theoutput accounting are documented once, in [doc/logging.md](../../doc/logging.md). This server writes the-same events as GLM except for `serve_start`, `img_cache` and `img_disk` (GLM's image cache and disk tier)+same events as GLM except for `serve_start` and `img_cache` (GLM's image cache and its disk tier)and `sse_ping` (this server's pinger writes no log line); `tools/test_serve_logging.py` checks the sharedpart against all three servers at once. Turn it on with `KYOJIN_REQLOG=<path>` (or `1`) and hold a silentstream open with `KYOJIN_SSE_PING_S=<seconds>`; both are in [doc/env_vars.md](../../doc/env_vars.md).diff --git a/tools/strix_halo/image_cache.py b/tools/strix_halo/image_cache.pyindex 6487b91..3a62bfc 100644--- a/tools/strix_halo/image_cache.py+++ b/tools/strix_halo/image_cache.py@@ -54,7 +54,8 @@ def policy_from_env(default: str = DEFAULT_POLICY) -> str: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."""+ so the bytes alone decide the embedding; the cache dies with the process. A store that outlives the+ process has to add what the process fixed (see `env_fingerprint` in tools/glm/image_cache_disk.py)."""return hashlib.sha256(raw).hexdigest()