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 server: upstream image-cache defaults, and a disk cache that needs an explicit cap
MangetsuC2c95d6ff63c5
diff --git a/exllamav3/tokenizer/mm_embedding.py b/exllamav3/tokenizer/mm_embedding.pyindex 78e4156..c6fabd2 100644--- a/exllamav3/tokenizer/mm_embedding.py+++ b/exllamav3/tokenizer/mm_embedding.py@@ -159,7 +159,8 @@ class QuantizedMMRows:"""Rows `index` in `out_dtype` (default: the dtype the rows had). `index` may live anywhere: thegather is on the host where the rows are, the scaling where the result is wanted. The scale is appliedin place, which measured ~15 % faster than allocating the product: 6 ms against 5 ms for the same rows- as fp32, for one 3179-token page, so re-prefilling one picture costs about half a millisecond more."""+ as fp32, for one 1568x1568 page (3,136 tokens), so re-prefilling one picture costs about half a+ millisecond more."""out_dtype = out_dtype or self.dtypeindex = index.to(self.q.device)values = self.q[index].to(out_dtype).sub_(128.0) # stored offset by half the range, so uint8diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex acbd66e..d49f714 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -30,12 +30,12 @@ call, a streamed call, a tool call, and two 400-token benchmark calls.| `--default-reasoning-effort` | `medium` | template `reasoning_effort` when a request omits it: `low`, `medium`, `high` or `max` || `--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` | 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-dir-lock-s` | `300` | seconds a conversation keeps the room its files took before another conversation may take it (0 = no tenure). The clock starts when the files are written and is **not** refreshed by later requests, so the conversation that grabbed the cache cannot keep it for ever. Tenure never costs a write: a batch that would have to push a recent conversation out is judged *before* anything is written and simply skipped (a conversation cached only in part has no reuse anyway), so the bytes stay on the client's side of the wire — which is what matters for wear |-| `--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) |+| `--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-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 |+| `--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) || `--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 || `--num-draft` | `2` | draft tokens per speculative round; `0` = plain decode, no drafter |@@ -124,22 +124,20 @@ server does not fetch remote URLs). One image takes 40 to about 8,000 tokens deppage is 3,136). `--no-vision` skips the tower; an image request then gets HTTP 400, as do video and audio parts.An image that is sent again in a later turn keeps the prompt cache **while its embedding is still held**. The-server keeps the decoded embeddings of recent pictures in host memory (GLM's merger emits fp32: 49.7 MiB for a-3,179-token manga page, 1 MB for a 224x224 crop) and re-encodes a picture it had to give up, which gives that+server keeps the decoded embeddings of recent pictures in host memory (GLM's merger emits fp32: 49.0 MiB for a+1568x1568 page, 3,136 tokens, 1 MB for a 224x224 crop) and re-encodes a picture it had to give up, which gives thatpicture fresh pseudo token ids and breaks the paged prefix *from that picture on*. `--image-cache-mb` sizes the-cache: 2 GiB by default on a 128 GB Strix Halo, 41 manga pages at 49.7 MiB each, one pool shared by all sessions like `-c`.+cache: 1024 MiB by default, about 20 pages of 1568x1568 at 49.0 MiB each, one pool shared by all sessions+like `-c`.A conversation larger than the budget keeps its **earliest** pictures and gives up the last ones, so the matchstill 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.-`--image-cache-format` stores those rows packed instead of as fp32 (49.0 MiB for a 3179-token page): `fp16` is-24.5 MiB and `q8` is 12.3 MiB. The rows are put back to their working dtype where the model gathers them — the-same place the fp32 rows were read before, `mm_rows()` in `exllamav3/tokenizer/mm_embedding.py`, called from the-embedding module, on the host because that module is a CPU module. Measured per picture that is actually+`--image-cache-format` stores those rows packed instead of as fp32 (49.0 MiB for a 1568x1568 page): `fp16` is+24.5 MiB and `q8` is 12.3 MiB. Measured per picture that is actuallyre-prefilled: `q8` +0.5 ms against the 5.2 ms the fp32 path takes, i.e. 0.01 % of a 40-page cold prefill and-nothing at all on a turn the cache serves from the paged prefix. All of them are off by default. Measured against-fp32 on this pack (12544 rows of four real pages): **`fp16` is bit-exact** — the+nothing at all on a turn the cache serves from the paged prefix. All of them are off by default. **`fp16` is bit-exact** — themerger's fp32 output is an fp16 value widened, so nothing is rounded and the saving is free — and `q8` loses0.863 % (rms 1.3e-4, 41 dB).@@ -158,14 +156,15 @@ With `EXL3_CONV_GEMM=0`, `MIOPEN_FIND_MODE=FAST` alone removes the convolution hpre-tuning, exactly as the default has them. Measurements, the offline pre-generation alternative, andthe 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.+With `--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 with+more 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+`--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:+`--image-cache-dir-max-gb` caps the directory and `--image-cache-dir-lock-s` caps how often a conversation can+lose its place to another one.### Streaming format`Content-Type: text/event-stream`. Every frame is a bare `data: {...}` line (no `event:`@@ -303,6 +302,10 @@ models:in the standalone MTP bench. The gap is content, not the server: mtp_round on the same prose promptgives 24.6 t/s (draft acceptance 0.57) vs 28.2 on chat (0.79); server overhead is ~3%.- No auth, no CORS, no embeddings endpoint. Bind to 127.0.0.1.+- **The image disk cache degrades with `--sessions > 1`.** With several conversations taking turns, a directory+ too small for all of them makes each request rewrite what the previous one dropped. `--image-cache-dir-lock-s`+ reduces that writing but does not remove it; a directory with room for every active conversation does. This+ needs many pictures *and* concurrent conversations at once, so it is rare in practice.## Open issues (found while documenting, NOT fixed)@@ -335,10 +338,10 @@ split mid-token, covering template rendering, think/tool parsing, stop strings,framing, `/v1/models`, usage, and the streamed open-`<think>` path. No GPU needed.`test_serve_glm_additional.py` holds the tests for what this checkout adds locally: the-request log (`KYOJIN_REQLOG`, off by default, no request text) and the image cache budget-(`--image-cache-mb` / `--image-cache-items`, the automatic share of RAM, what `img_cache`-reports). It is a file of its own so upstream's `test_serve.py` stays untouched and merges-cleanly; fold it back in if the features are ever proposed upstream.+request 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,+the row format, what `img_cache` reports). It is a file of its own so upstream's `test_serve.py`+stays untouched and merges cleanly.## Lane launcherdiff --git a/tools/glm/image_cache_glm.py b/tools/glm/image_cache_glm.pyindex 6e24111..05642a3 100644--- a/tools/glm/image_cache_glm.py+++ b/tools/glm/image_cache_glm.py@@ -21,7 +21,7 @@ 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 budgetfrom RAM and its own flags (see `--image-cache-mb`). Each entry holds the embedding rows on the host plus the sameagain for each deepstack layer, so the budget is host memory, not VRAM: GLM's vision merger emits fp32, about-49.7 MiB for one 3179-token manga page and 1 MB for a 224x224 crop.+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 lossis a few pictures per turn, not the prompt. `max_orders` is how many recent prompts the policy weighs, and among@@ -35,7 +35,7 @@ import threadingfrom typing import Any, CallableDEFAULT_MAX_ITEMS = 0 # the byte budget is the real bound; a count cap is optional on top of it-DEFAULT_MAX_BYTES = 2 << 30 # 2 GiB of host memory (Strix Halo: ~104 GB of weights + the KV pool)+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 remembersdiff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 87fa663..9ef78b8 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -107,54 +107,25 @@ SPEED_ENV = {"EXL3_SPEC_SAMPLED": "1",}-# Host memory for the decoded image embeddings (--image-cache-mb). One entry per picture is 49.7 MiB for a-# 3179-token manga page and 1 MB for a 224x224 crop, so pictures, not bytes, are what a conversation spends.-# The automatic budget is a share of RAM clamped to this range; the ceiling is what a Strix Halo box can spare-# next to ~104 GB of weights and the KV pool: 2 GiB holds 41 manga pages (49.7 MiB each), measured.-IMAGE_CACHE_AUTO_MIN_MB = 512-IMAGE_CACHE_AUTO_MAX_MB = 2048-IMAGE_CACHE_AUTO_SHARE = 0.02--# How the cached rows may be stored (--image-cache-format). Kept here rather than imported from the engine-# because serve.py must not import exllamav3 before SPEED_ENV is applied; a test checks it matches-# exllamav3.tokenizer.mm_embedding.MM_QUANT_MODES.+# Host memory for the decoded image embeddings (--image-cache-mb). One entry per picture is 49.0 MiB for a+# 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+# 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.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+IMAGE_CACHE_DIR_DEFAULT = "~/.cache/kyojin/image-embeddings"+# GiB cap on the second-level picture cache directory. 0 means the disk cache is off, which is the default: the+# memory cache above is what a normal session needs, and the disk cache exists for conversations with more+# pictures than that budget holds. A positive value is always a real cap, there is no "unlimited".+IMAGE_CACHE_DIR_MAX_GB = 0.0# How long a conversation keeps the room its picture cache took on disk (--image-cache-dir-lock-s). The clock# starts when the files are written and is not refreshed by later requests, so a conversation that grabbed the-# cache cannot keep it for ever; within the window a cyclic workload cannot evict each conversation just before-# it is served again.+# cache cannot keep it for ever.IMAGE_CACHE_DIR_LOCK_S = 300.0-def physical_ram_bytes() -> int:- """Installed RAM, or 0 when the platform will not say."""- try:- return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")- except (ValueError, OSError, AttributeError):- return 0---def auto_image_cache_bytes(ram_bytes: int | None = None) -> int:- """Default byte budget for the image embedding cache: 2 % of RAM, clamped to [512 MiB, 2 GiB].-- The budget has to cover the pictures of the conversation being served: the paged prefix stops at the first- picture whose embedding was evicted, so a budget that is one picture short costs the whole prompt, and how- many pictures a history holds cannot be predicted from a request. A share of RAM therefore beats a constant,- and the clamp keeps it sane on a small box (never below 512 MiB) and on a large one (never above 2 GiB,- which is 41 manga pages and what a 128 GB Strix Halo can spare next to the weights).- """- if ram_bytes is None:- ram_bytes = physical_ram_bytes()- mb = ram_bytes / 2 ** 20 * IMAGE_CACHE_AUTO_SHARE- if not ram_bytes:- mb = IMAGE_CACHE_AUTO_MIN_MB- return int(min(IMAGE_CACHE_AUTO_MAX_MB, max(IMAGE_CACHE_AUTO_MIN_MB, mb))) * 2 ** 20--def make_image_cache(image_cache_bytes: int | None = None, image_cache_items: int = 0,sessions: int = 1) -> ImageEmbeddingCache:"""The picture cache of the process (--image-cache-mb / --image-cache-items).@@ -168,6 +139,22 @@ def make_image_cache(image_cache_bytes: int | None = None, image_cache_items: in**({} if image_cache_bytes is None else {"max_bytes": image_cache_bytes}))+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):+ """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`+ holds, and an unbounded directory is not something a server should be able to create by omission.+ """+ if not image_cache_dir_max_gb or image_cache_dir_max_gb <= 0:+ return None+ from image_cache_disk import ImageEmbeddingDisk # imports exllamav3: only once it is wanted+ 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)))++def apply_eh_sidecar_default(model_dir: str | None = None) -> str:"""Pick the optional unquantized MTP eh_proj sidecar and log which source is used.@@ -480,7 +467,8 @@ class ResidentEngine:vision: bool = True, sessions: int = 1,image_cache_bytes: int | None = None, image_cache_items: int = 0,image_cache_format: str = "fp32",- image_cache_dir: str | None = None, image_cache_dir_max_gb: float = IMAGE_CACHE_DIR_MAX_GB,+ image_cache_dir: str | None = IMAGE_CACHE_DIR_DEFAULT,+ image_cache_dir_max_gb: float = IMAGE_CACHE_DIR_MAX_GB,image_cache_dir_lock_s: float = IMAGE_CACHE_DIR_LOCK_S):import torchfrom exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer@@ -533,15 +521,11 @@ class ResidentEngine:self.vision = Noneself.image_cache_format = image_cache_formatself.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),- lock_s=max(0.0, float(image_cache_dir_lock_s)))+ # 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.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))if vision:self.vision = self._load_vision()self.supports_vision = self.vision is not None@@ -1762,19 +1746,15 @@ def main() -> None:help=f"requests decoded together through the one Generator (1..{MAX_SESSIONS}); default 1 = one request at a time. ""The KV pool (-c) is shared by all sessions")parser.add_argument("-c", "--max-ctx", type=int, default=131072, help="context window (capped by max_position_embeddings)")- parser.add_argument("--image-cache-mb", type=int, default=None,- help="host memory for the decoded image embeddings, in MiB; 0 = no byte limit. Like -c this is one pool "- "shared by every --sessions request. Default: a share of RAM (2 percent) clamped to "- f"[{IMAGE_CACHE_AUTO_MIN_MB}, {IMAGE_CACHE_AUTO_MAX_MB}] MiB, which is {IMAGE_CACHE_AUTO_MAX_MB} MiB on a 128 GB "- "Strix Halo: about 50 MiB per manga page, 1 MB per small crop")+ parser.add_argument("--image-cache-mb", type=int, default=IMAGE_CACHE_MB_DEFAULT,+ 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 = 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")+ help="optional cap on how many pictures are held at once (0 = no limit)")+ 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")parser.add_argument("--image-cache-dir-lock-s", type=float, default=IMAGE_CACHE_DIR_LOCK_S,help=f"seconds a conversation keeps its files on disk before another conversation may "f"take the room (default {IMAGE_CACHE_DIR_LOCK_S:g} = 5 min, 0 = no tenure). Tenure "@@ -1782,13 +1762,12 @@ def main() -> None:"before it is served again; while it holds, a new picture that would have to push a ""recent conversation out is simply not cached")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")+ help=f"cap on that directory, in GiB; 0 = off, which is the default "+ f"({IMAGE_CACHE_DIR_MAX_GB:g}). No unlimited setting: a positive value is the cap")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, "- "measured 0.86 percent error)")+ "emits them (default), fp16 (half the bytes, bit-exact on this pack) or q8 (8 bit with "+ "one fp16 scale per row, a quarter of the bytes, 0.86 percent error)")parser.add_argument("--slot-save-path", default="~/cache/llama-slots",help="directory for /slots save/restore files (llama.cpp compatible)")parser.add_argument("--chat-template", default=None,@@ -1832,16 +1811,9 @@ def main() -> None:variant="tuned" if tune and dense_tune_path().exists() else "untuned")startup_health.report_compiler()try:- if args.image_cache_mb is None:- ram = physical_ram_bytes()- image_cache_bytes = auto_image_cache_bytes(ram)- image_cache_src = (f"auto: {IMAGE_CACHE_AUTO_SHARE:.0%} of {ram / 2 ** 30:.1f} GiB RAM, "- f"clamped to [{IMAGE_CACHE_AUTO_MIN_MB}, {IMAGE_CACHE_AUTO_MAX_MB}] MiB")- else:- image_cache_bytes = max(0, args.image_cache_mb) * 2 ** 20- image_cache_src = f"--image-cache-mb {args.image_cache_mb}"- image_cache_size = (f"{image_cache_bytes / 2 ** 20:.0f} MiB of host memory ({image_cache_src})"- if image_cache_bytes else f"unlimited host memory ({image_cache_src})")+ image_cache_bytes = max(0, int(args.image_cache_mb)) * 2 ** 20+ image_cache_size = (f"{args.image_cache_mb} MiB of host memory (--image-cache-mb)" if image_cache_bytes+ else "no byte limit (--image-cache-mb 0)")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,@@ -1854,7 +1826,7 @@ def main() -> None: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:+ 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.# EXL3_SERVE_WARMUP=0 skips it.diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex 5adafd6..5f9fecc 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -140,10 +140,9 @@ def tiny_pictures(count: int):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.assertEqual(serve.IMAGE_CACHE_DIR_LOCK_S, 300.0) # 5 minutes of tenure for a conversation's files- self.assertNotIn("EXL3_IMAGE_CACHE_DIR", os.environ) # a flag, not an environment variable+ def test_the_disk_cache_is_a_flag_not_an_environment_variable(self):+ self.assertNotIn("EXL3_IMAGE_CACHE_DIR", os.environ)+ self.assertNotIn("EXL3_IMAGE_CACHE_MB", os.environ)def test_the_tenure_reaches_the_disk_cache(self):with tempfile.TemporaryDirectory() as tmp:@@ -224,31 +223,37 @@ class ImageDiskCacheTests(unittest.TestCase):self.assertEqual(len(out), 2)self.assertEqual(len(calls), 2)- def test_auto_budget_is_a_share_of_ram_clamped_to_this_box(self):- low, high = serve.IMAGE_CACHE_AUTO_MIN_MB, serve.IMAGE_CACHE_AUTO_MAX_MB- self.assertEqual(serve.auto_image_cache_bytes(8 << 30), low << 20) # 2 % of 8 GiB would be 164 MiB- self.assertEqual(serve.auto_image_cache_bytes(123 << 30), high << 20) # 2519 MiB, clamped to 2048- self.assertEqual(serve.auto_image_cache_bytes(128 << 30), high << 20)- self.assertEqual(serve.auto_image_cache_bytes(64 << 30), 1310 << 20) # inside the range: 2 % of RAM- self.assertEqual(serve.auto_image_cache_bytes(0), low << 20) # unreadable RAM: the floor-- def test_the_box_this_runs_on_gets_the_ceiling(self):- self.assertGreater(serve.physical_ram_bytes(), 0)- self.assertEqual(serve.auto_image_cache_bytes(), serve.IMAGE_CACHE_AUTO_MAX_MB << 20)+ 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.+ self.assertEqual(serve.IMAGE_CACHE_MB_DEFAULT, 1024)+ self.assertEqual(serve.make_image_cache(None).max_bytes, 1024 << 20)+ self.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)++ 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))+ self.assertIsNone(serve.make_image_disk(None, 0.0, 300.0))+ with tempfile.TemporaryDirectory() as tmp:+ disk = serve.make_image_disk(tmp, 0.5, 60.0, start_token=7, end_token=8)+ self.assertEqual(disk.max_bytes, int(0.5 * 2 ** 30))+ self.assertEqual(disk.lock_s, 60.0)def test_flags_reach_the_cache(self):cache = serve.make_image_cache(1024 << 20, image_cache_items=7, sessions=3)self.assertEqual(cache.max_bytes, 1024 << 20)self.assertEqual(cache.max_items, 7)self.assertEqual(cache.max_orders, 3) # one prompt order per session- self.assertEqual(serve.make_image_cache(None, sessions=1).max_orders, 2)+ self.assertEqual(serve.make_image_cache(512 << 20, sessions=1).max_orders, 2)self.assertEqual(serve.make_image_cache(0, 0).max_bytes, 0) # 0 = no boundself.assertEqual(serve.make_image_cache(0, 0).max_items, 0)- self.assertEqual(serve.make_image_cache().max_bytes, 2 << 30) # engine default: 2 GiB+ self.assertEqual(serve.make_image_cache().max_bytes, 1024 << 20) # engine default: 1 GiBdef test_the_cache_the_engine_would_build_reports_its_budget(self):- cache = serve.make_image_cache(serve.auto_image_cache_bytes(123 << 30), 0)- self.assertEqual(cache.max_bytes, 2048 << 20)+ cache = serve.make_image_cache(serve.IMAGE_CACHE_MB_DEFAULT << 20, 0)+ self.assertEqual(cache.max_bytes, 1024 << 20)self.assertEqual(cache.max_items, 0)def test_the_cli_format_list_covers_every_engine_mode(self):@@ -449,7 +454,7 @@ 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"], "2048") # image_cache_glm's own default+ 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[1]["hits"], cache[1]["misses"]), ("2", "0"))self.assertNotIn("first_missing", cache[1]) # a full hit has no gap