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: configurable image cache budget, and give up the tail of a prompt
MangetsuC377c6cef9587
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex b20704d..c388d7b 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -30,6 +30,8 @@ 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 || `--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 |@@ -114,9 +116,18 @@ Ignored (accepted, no effect): `n`, `seed`, `logprobs`, `top_k`, `presence_penalThe server loads the vision tower of the pack at start (+0.35 GB GPU memory, about 2 s) and prints `vision=True`.An image goes in a user message as an OpenAI `image_url` part; the URL is a `data:` URI or a local file path (the-server does not fetch remote URLs). One image takes 40 to about 1,500 tokens depending on its size. An image that is-sent again in a later turn keeps the prompt cache. `--no-vision` skips the tower; an image request then gets HTTP 400,-as do video and audio parts.+server does not fetch remote URLs). One image takes 40 to about 8,000 tokens depending on its size (a 1568x1568+page 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+picture 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`.+A conversation larger than the budget keeps its **earliest** pictures and gives up the last ones, so the match+still runs from the first page to where the cache ended rather than collapsing to nothing. The request log's+`img_cache` line reports `hits`, `misses` and `first_missing`, the index the prefix could match up to;+`--image-cache-items` adds an optional cap on the number of pictures.The first image of a new size costs seconds: the server runs the vision spatial-merge convolution as a GEMM(`EXL3_CONV_GEMM=1`) and skips the dense GEMM screening (`EXL3_DENSE_GEMM_TUNE=0`). Both are server defaults@@ -286,13 +297,24 @@ models:## Tests```bash-python -m pytest -q tools/glm/test_serve.py tools/test_serve_compat.py tools/test_startup_health.py+# unittest: no extra dependency, which is what this checkout's venv has+python -m unittest tools.glm.test_serve tools.glm.test_serve_glm_additional \+ tools.test_serve_compat tools.test_startup_health+# the same under pytest, if it is installed+python -m pytest -q tools/glm/test_serve.py tools/glm/test_serve_glm_additional.py \+ tools/test_serve_compat.py tools/test_startup_health.py```Model-free: a `FakeEngine` emits deterministic GLM XML in 3-character chunks so tags aresplit mid-token, covering template rendering, think/tool parsing, stop strings, SSEframing, `/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.+## Lane launcher`tools/lanes/serve_glm.sh` runs this server with the exact flags and speed envs of our serving lane (see `tools/lanes/README.md`). The runtime uncensor hook is off unless `GLM_ABLIT` points at an edit spec.diff --git a/tools/glm/image_cache.py b/tools/glm/image_cache.pyindex 8991ae3..78cc369 120000--- a/tools/glm/image_cache.py+++ b/tools/glm/image_cache.py@@ -1 +1 @@-../strix_halo/image_cache.py\ No newline at end of file+image_cache_glm.py\ No newline at end of filediff --git a/tools/glm/image_cache_glm.py b/tools/glm/image_cache_glm.pynew file mode 100644index 0000000..e48315c--- /dev/null+++ b/tools/glm/image_cache_glm.py@@ -0,0 +1,162 @@+#!/usr/bin/env python3+"""Bounded cache of image embeddings for the GLM server: a full cache gives up the *tail* of the prompt.++A vision embedding takes fresh pseudo token ids every time it is built, and the paged KV cache keys its pages on+token ids. Building the embedding again for the same picture therefore breaks the prefix match at that picture, on+every later request. This cache returns the very same embedding object (same ids, same text alias) for the same+picture, and it skips the vision tower for a picture it already holds.++One picture used n times in a prompt needs n distinct embedding objects (an object spliced twice would make its+ids ambiguous), so the key is (content hash, occurrence in the prompt); each copy stays stable across requests.++What a hit is worth depends on *where* the picture sits in the prompt: the paged prefix matches from the first+token on and stops at the first picture that had to be re-encoded, so the n-th picture buys reuse only if every+earlier one is still held, and the first picture buys the whole prompt. The eviction order therefore follows the+prompt, not the clock: an entry no longer referenced by a remembered prompt goes first, then the *last* pictures+of the remembered prompts, and the head of the prompt is the last thing given up. A plain LRU does the opposite —+it drops the oldest pictures, which are exactly the ones the match depends on, and turns "the cache is one picture+too small" into "nothing at all is reused" (measured: 21 pictures against a 20-picture budget, 99.8 % of a 63K+prompt reused before the change, 0 % — the full 63K re-prefilled — after it).++The cache is bounded by total bytes, with an optional entry count on top; the GLM server sizes the byte budget+from RAM and its own flags (see `--image-cache-mb`). Each entry holds the embedding rows on the host plus the same+again for each deepstack layer, so the budget is host memory, not VRAM: GLM's vision merger emits fp32, about+49.7 MiB for one 3179-token manga page and 1 MB for a 224x224 crop.++When the budget cannot hold every active conversation, each one keeps its head and re-encodes its tail: the loss+is a few pictures per turn, not the prompt. `max_orders` is how many recent prompts the policy weighs, and among+pictures at the same distance from the start, the one from the conversation served longest ago goes first.+"""+from __future__ import annotations++import collections+import hashlib+import threading+from typing import Any, Callable++DEFAULT_MAX_ITEMS = 0 # the byte budget is the real bound; a count cap is optional on top of it+DEFAULT_MAX_BYTES = 2 << 30 # 2 GiB of host memory (Strix Halo: ~104 GB of weights + the KV pool)+DEFAULT_MAX_ORDERS = 2 # prompts whose picture order the eviction policy remembers+++def digest(raw: bytes) -> str:+ """Content key of an encoded image. One server process holds one vision tower with fixed resize and pixel limits,+ so the bytes alone decide the embedding; the cache dies with the process."""+ return hashlib.sha256(raw).hexdigest()+++def embedding_nbytes(emb: Any) -> int:+ """Host bytes of an MMEmbedding: its rows and its deepstack rows."""+ total = 0+ for t in [getattr(emb, "embeddings", None), *(getattr(emb, "deepstack_embeddings", None) or [])]:+ if t is not None:+ total += int(t.numel()) * int(t.element_size())+ return total+++class ImageEmbeddingCache:+ """Embeddings keyed by (content, occurrence), sized in bytes, evicted from the end of the prompt backwards.++ `max_bytes` or `max_items` at 0 means that bound is not applied. `max_orders` is how many recent prompts the+ eviction policy keeps in mind: 1 is enough for one request at a time and gives exactly "give up the tail of+ this prompt", while a server running `--sessions N` passes N (or a little more) so that concurrent+ conversations do not evict each other's heads. Thread safe: one vision pass per picture, also across requests.+ """++ def __init__(self, max_items: int = DEFAULT_MAX_ITEMS, max_bytes: int = DEFAULT_MAX_BYTES,+ max_orders: int = DEFAULT_MAX_ORDERS):+ self.max_items = max(0, int(max_items))+ self.max_bytes = max(0, int(max_bytes))+ self.max_orders = max(1, int(max_orders))+ self._items: collections.OrderedDict = collections.OrderedDict() # slot -> (embedding, nbytes)+ self._orders: collections.OrderedDict = collections.OrderedDict() # prompt serial -> [slot, ...]+ self._seq = 0+ self._nbytes = 0+ self._lock = threading.RLock()++ def __len__(self) -> int:+ return len(self._items)++ @property+ def nbytes(self) -> int:+ return self._nbytes++ def clear(self) -> None:+ with self._lock:+ self._items.clear()+ self._orders.clear()+ self._nbytes = 0++ def _over_budget(self) -> bool:+ return bool((self.max_items and len(self._items) > self.max_items) or+ (self.max_bytes and self._nbytes > self.max_bytes))++ def _eviction_order(self) -> list:+ """Slots of the held embeddings, the one to give up first first.++ Least valuable first: an entry that no remembered prompt refers to, then the entries of those prompts+ ordered by how far into the prompt they sit (the last picture of a prompt is worth the least), and among+ equal positions the prompt that was seen longest ago.+ """+ position: dict = {}+ for age, slots in enumerate(self._orders.values()):+ for index, slot in enumerate(slots):+ seen = position.get(slot)+ if seen is None or index < seen[0]: # keep the earliest position this picture has in any prompt+ position[slot] = (index, age)+ stale, live = [], []+ for lru, slot in enumerate(self._items): # _items is in use order, least recently used first+ if slot in position:+ index, age = position[slot]+ live.append((-index, age, lru, slot))+ else:+ stale.append((lru, slot))+ stale.sort()+ live.sort()+ return [slot for _, slot in stale] + [slot for *_, slot in live]++ def _trim(self) -> int:+ """Evict until both bounds hold. Returns how many entries went."""+ evicted = 0+ if not self._over_budget():+ return 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.++ 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.+ """+ out, seen = [], collections.Counter()+ order: list = []+ with self._lock:+ for image, key in images:+ slot = (key, seen[key])+ seen[key] += 1+ order.append(slot)+ hit = self._items.get(slot)+ if hit is None:+ emb = build(image)+ n = embedding_nbytes(emb)+ self._items[slot] = (emb, n)+ self._nbytes += n+ else:+ emb = hit[0]+ self._items.move_to_end(slot)+ out.append(emb)+ if order:+ self._seq += 1+ self._orders[self._seq] = order+ while len(self._orders) > self.max_orders:+ self._orders.popitem(last=False)+ self._trim()+ return outdiff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 976edd8..8b55a94 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -107,6 +107,53 @@ 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+++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).++ One cache for the whole server, shared by every session exactly like the KV pool `-c` sizes, with the+ eviction policy of image_cache_glm.py: the tail of a prompt is given up before its head, and the policy+ remembers one prompt order per concurrent request plus one, so a conversation is not forgotten between two+ of its own turns when another session slips in between.+ """+ return ImageEmbeddingCache(max_items=image_cache_items, max_orders=max(2, sessions),+ **({} if image_cache_bytes is None else {"max_bytes": image_cache_bytes}))++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.@@ -416,7 +463,8 @@ class ResidentEngine:row_budget = 0def __init__(self, model_path: str, max_history: int = 1, max_ctx: int = 131072, num_draft: int = 1,- vision: bool = True, sessions: int = 1):+ vision: bool = True, sessions: int = 1,+ image_cache_bytes: int | None = None, image_cache_items: int = 0):import torchfrom exllamav3 import Cache, Config, Generator, Job, Model, Tokenizerfrom exllamav3.generator import generator as GM@@ -466,7 +514,7 @@ class ResidentEngine:else: # --num-draft 0: plain decode, no drafterself.draft_model = self.draft_cache = Noneself.vision = None- self.emb_cache = ImageEmbeddingCache()+ self.emb_cache = make_image_cache(image_cache_bytes, image_cache_items, sessions)if vision:self.vision = self._load_vision()self.supports_vision = self.vision is not None@@ -1661,6 +1709,13 @@ 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-items", type=int, default=0,+ help="optional cap on how many pictures are held at once (0 = only the byte budget)")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,@@ -1704,12 +1759,25 @@ 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})")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)+ vision=not args.no_vision, sessions=args.sessions,+ image_cache_bytes=image_cache_bytes, image_cache_items=args.image_cache_items)engine.row_budget = (5 if args.row_budget is None else args.row_budget) if args.sessions > 1 else 0template = 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"shared by {args.sessions} session(s)", 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":diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex 58510b3..7e8cb17 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport asyncioimport json-import osimport sysimport unittestfrom pathlib import Path@@ -967,242 +966,5 @@ class VllmCompatTests(unittest.TestCase):serve.template_kwargs({"chat_template_kwargs": "x"})-class RequestLogTests(unittest.TestCase):- """KYOJIN_REQLOG: off unless asked for; when on, one line per lifecycle event, numbers and names only."""- template = ServeTests.template-- def setUp(self):- import tempfile- self.tmp = tempfile.TemporaryDirectory()- self.addCleanup(self.tmp.cleanup)- self.log_path = Path(self.tmp.name) / "requests.log"- for key in ("KYOJIN_REQLOG", "KYOJIN_REQLOG_HEARTBEAT_S"):- os.environ.pop(key, None)- self.addCleanup(os.environ.pop, key, None)-- def lines(self) -> list[str]:- return self.log_path.read_text(encoding="utf-8").splitlines() if self.log_path.exists() else []-- def events(self) -> list[tuple[str, dict]]:- """(event name, fields) per line; the timestamp is field 0 and the event name field 1."""- out = []- for line in self.lines():- parts = line.split(" ")- fields = {}- for item in parts[2:]:- key, _, value = item.partition("=")- fields[key] = value.strip('"')- out.append((parts[1], fields))- return out-- def names(self) -> list[str]:- return [name for name, _ in self.events()]-- def chat(self, body: dict, **kw) -> int:- from aiohttp.test_utils import TestClient, TestServer-- async def check():- client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))- await client.start_server()- response = await client.post("/v1/chat/completions", json=body, **kw)- await response.read()- status = response.status- await client.close()- return status-- return run(check())-- def test_off_by_default_and_a_request_writes_nothing(self):- from serve_reqlog import ReqLog- log = ReqLog.from_env()- self.assertFalse(log.enabled)- self.assertIsNone(log.path)- self.assertIn("request log off", log.describe())- log.log("req_start", req="r1") # disabled: a no-op, never an error- self.assertEqual(log.lines(), [])-- from aiohttp.test_utils import TestClient, TestServer-- async def check():- app = serve.create_app(FakeEngine("hello"), "m", self.template)- self.assertFalse(app["reqlog"].enabled)- client = TestClient(TestServer(app))- await client.start_server()- response = await client.post("/v1/chat/completions", json={- "model": "m", "messages": [{"role": "user", "content": "hi"}]})- status = response.status- await response.read()- await client.close()- return status-- self.assertEqual(run(check()), 200)- self.assertFalse(self.log_path.exists()) # nothing is created, nothing is written- self.assertFalse(list(Path(self.tmp.name).iterdir()))-- def test_lifecycle_lines_share_one_id_and_never_hold_request_text(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)- secret, reply = "PROMPT-SECRET-7f3a", "REPLY-SECRET-9b1c"- engine = FakeEngine(reply)- from aiohttp.test_utils import TestClient, TestServer-- async def check():- app = serve.create_app(engine, "m", self.template)- self.assertTrue(app["reqlog"].enabled)- client = TestClient(TestServer(app))- await client.start_server()- response = await client.post("/v1/chat/completions", json={- "model": "m", "messages": [{"role": "user", "content": secret}]})- body = await response.json()- await client.close()- return body-- body = run(check())- self.assertEqual(body["choices"][0]["message"]["content"], reply)- events = dict(self.events())- for want in ("req_start", "req_queued", "job_start", "job_first_token", "job_done", "req_done"):- self.assertIn(want, events)- ids = {fields["req"] for name, fields in self.events() if "req" in fields}- self.assertEqual(len(ids), 1) # every line of the request carries the same id- self.assertEqual(events["req_queued"]["queued_ahead"], "0")- self.assertEqual(events["job_done"]["cache_n"], "8") # the engine's own cached_tokens- self.assertEqual(events["job_done"]["cache_pct"], "40")- self.assertIn(secret, " ".join(engine.prompts)) # the prompt really did carry the secret- blob = "\n".join(self.lines())- self.assertNotIn(secret, blob)- self.assertNotIn(reply, blob)-- def test_stream_headers_first_content_and_done(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)- from aiohttp.test_utils import TestClient, TestServer-- async def check():- client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))- await client.start_server()- response = await client.post("/v1/chat/completions", json={- "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})- await response.read()- await client.close()-- run(check())- names = self.names()- for want in ("sse_headers", "sse_first_content", "sse_done", "req_done"):- self.assertIn(want, names)- self.assertLess(names.index("sse_headers"), names.index("sse_first_content"))- self.assertLess(names.index("sse_first_content"), names.index("sse_done"))-- def test_refusals_are_logged_without_quoting_the_body(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)- from aiohttp.test_utils import TestClient, TestServer-- async def check():- client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))- await client.start_server()- bad = await client.post("/v1/chat/completions", json={"model": "m"}) # no messages: 400- broken = await client.post("/v1/chat/completions", data=b'{"model": "m", ',- headers={"Content-Type": "application/json"}) # malformed JSON: 400- await client.close()- return bad.status, broken.status-- self.assertEqual(run(check()), (400, 400))- refused = [fields for name, fields in self.events() if name == "req_refused"]- self.assertEqual(len(refused), 2)- self.assertEqual({f["status"] for f in refused}, {"400"})- reasons = " ".join(f.get("reason", "") for f in refused)- self.assertIn("JSONDecodeError(line=1", reasons) # reduced to line/column, not the body text- self.assertNotIn("model", reasons)-- def test_image_request_logs_cache_hits_misses_and_budget(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)- import base64- import io- from PIL import Image- from aiohttp.test_utils import TestClient, TestServer- tpl = self.template.replace("{{ m.content }}", "{% if m.content is string %}{{ m.content }}{% else %}{% for p in m.content %}{% if p.type == 'text' %}{{ p.text }}{% else %}" + serve.IMAGE_TRIPLE + "{% endif %}{% endfor %}{% endif %}")- eng, _ = ImageEmbeddingReuseTests().make_engine()-- class VisionEngine(FakeEngine):- supports_vision = True-- def image_tokens(self, image):- return 3-- async def generate(self, prompt, images=None, img_stats=None, **kw):- if images:- serve.ResidentEngine._embed(eng, images, img_stats)- async for piece in FakeEngine.generate(self, prompt, **kw):- yield piece-- def uri(color):- buf = io.BytesIO()- Image.new("RGB", (8, 8), color).save(buf, "PNG")- return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()-- body = {"model": "m", "messages": [{"role": "user", "content": [- {"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": uri((255, 0, 0))}},- {"type": "image_url", "image_url": {"url": uri((0, 0, 255))}}]}]}-- async def check():- client = TestClient(TestServer(serve.create_app(VisionEngine("hello"), "m", tpl)))- await client.start_server()- for _ in range(2): # second send: both pictures are held- response = await client.post("/v1/chat/completions", json=body)- await response.read()- await client.close()-- run(check())- cache = [fields for name, fields in self.events() if name == "img_cache"]- self.assertEqual(len(cache), 2)- 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 start- self.assertEqual((cache[0]["entries"], cache[0]["evicted"]), ("2", "0"))- self.assertEqual(cache[0]["budget_mb"], "1024")- self.assertEqual(cache[0]["item_cap"], "32")- self.assertEqual((cache[1]["hits"], cache[1]["misses"]), ("2", "0"))- self.assertNotIn("first_missing", cache[1]) # a full hit has no gap- self.assertNotIn("data:image", "\n".join(self.lines())) # the image URL is never written-- def test_heartbeat_while_a_job_runs(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)- os.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.05"- from aiohttp.test_utils import TestClient, TestServer-- class Slow(FakeEngine):- async def generate(self, prompt, **kwargs):- await asyncio.sleep(0.3)- async for piece in FakeEngine.generate(self, prompt, **kwargs):- yield piece-- async def check():- client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", self.template)))- await client.start_server()- response = await client.post("/v1/chat/completions", json={- "model": "m", "messages": [{"role": "user", "content": "hi"}]})- await response.read()- await client.close()-- run(check())- alive = [fields for name, fields in self.events() if name == "alive"]- self.assertTrue(alive, "no heartbeat lines")- self.assertTrue(all("elapsed_s" in f and "phase" in f for f in alive))- self.assertTrue({f["phase"] for f in alive} <= {"parse", "queued", "prefill", "decode", "stream"})-- def test_v1_completions_is_logged_too(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)- from aiohttp.test_utils import TestClient, TestServer-- async def check():- client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))- await client.start_server()- response = await client.post("/v1/completions", json={"model": "m", "prompt": "hi", "max_tokens": 4})- await response.read()- await client.close()- return response.status-- self.assertEqual(run(check()), 200)- queued = [fields for name, fields in self.events() if name == "req_queued"]- self.assertEqual([f["path"] for f in queued], ["/v1/completions"])- self.assertIn("job_done", self.names())--if __name__ == "__main__":unittest.main()diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pynew file mode 100644index 0000000..db152cd--- /dev/null+++ b/tools/glm/test_serve_glm_additional.py@@ -0,0 +1,339 @@+#!/usr/bin/env python3+"""Local additions to tools/glm/test_serve.py: the request log and the image cache budget.++These tests cover work that is not upstream (yet), so they live in a file of their own instead of patching+upstream's test_serve.py: a merge of upstream's file never conflicts with them, and they can be folded back+into test_serve.py in one move if the features are ever proposed upstream. The fake engine below is a copy of+the one in test_serve.py, deliberately: this file then runs on its own and does not break when upstream edits+its fixtures.++ kyojin/.venv/bin/python -m unittest tools.glm.test_serve_glm_additional # 11 tests, no GPU, no model+ kyojin/.venv/bin/python -m pytest -q tools/glm/test_serve_glm_additional.py+"""+from __future__ import annotations++import asyncio+import base64+import io+import os+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).parent))+import serve # noqa: E402++TEMPLATE = ("{% for m in messages %}<|im_start|>{{ m.role }}: {{ m.content }}<|im_end|>{% endfor %}"+ "{% if tools %}TOOLS={{ tools|length }}{% endif %}")+# The same template with the image placeholders the server matches against the request's image parts.+IMAGE_TEMPLATE = TEMPLATE.replace(+ "{{ m.content }}",+ "{% if m.content is string %}{{ m.content }}{% else %}{% for p in m.content %}"+ "{% if p.type == 'text' %}{{ p.text }}{% else %}" + serve.IMAGE_TRIPLE + "{% endif %}{% endfor %}{% endif %}")+++class FakeGenerator:+ num_draft_tokens = 2 # /metrics derives the round count from the engine's window+++class FakeEngine:+ def __init__(self, output: str):+ self.output = output+ self.prompts = []+ self.greedy_generator = FakeGenerator()++ def count_tokens(self, text: str) -> int:+ return len(text.split())++ async def generate(self, prompt: str, **kwargs):+ self.prompts.append(prompt)+ self.last_stats = {"cached_tokens": 8, "new_tokens": 4, "prompt_tokens": 20,+ "time_prefill": 0.5, "time_generate": 1.0,+ "accepted_draft_tokens": 6, "rejected_draft_tokens": 6}+ for i in range(0, len(self.output), 3): # small chunks cut tags in half+ yield self.output[i:i + 3]+++def run(coro):+ return asyncio.run(coro)+++def vision_engine():+ """A fake engine whose generate() runs the real _embed() on a real cache, plus a tower that counts encodes."""+ import itertools++ import torch+ from image_cache import ImageEmbeddingCache++ ids, calls = itertools.count(1_000_000_000, 100), []++ class Emb:+ def __init__(self):+ self.first_index = next(ids)+ self.text_alias = f"<$EMB_{self.first_index}$>"+ self.mm_length = 3+ self.embeddings = torch.zeros(3, 4, dtype=torch.half)+ self.deepstack_embeddings = None++ class Tower:+ def get_image_embeddings(self, *args, **kw):+ calls.append(1)+ return Emb()++ eng = object.__new__(serve.ResidentEngine)+ eng.emb_cache, eng.vision, eng.tokenizer = ImageEmbeddingCache(), Tower(), None+ return eng, calls+++class ImageCacheBudgetTests(unittest.TestCase):+ """--image-cache-mb / --image-cache-items, and the automatic budget behind them."""++ 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_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(0, 0).max_bytes, 0) # 0 = no bound+ self.assertEqual(serve.make_image_cache(0, 0).max_items, 0)+ self.assertEqual(serve.make_image_cache().max_bytes, 2 << 30) # engine default: 2 GiB++ def 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)+ self.assertEqual(cache.max_items, 0)+++class RequestLogTests(unittest.TestCase):+ """KYOJIN_REQLOG: off unless asked for; when on, one line per lifecycle event, numbers and names only."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.log_path = Path(self.tmp.name) / "requests.log"+ for key in ("KYOJIN_REQLOG", "KYOJIN_REQLOG_HEARTBEAT_S"):+ os.environ.pop(key, None)+ self.addCleanup(os.environ.pop, key, None)++ def lines(self) -> list[str]:+ return self.log_path.read_text(encoding="utf-8").splitlines() if self.log_path.exists() else []++ def events(self) -> list[tuple[str, dict]]:+ """(event name, fields) per line; the timestamp is field 0 and the event name field 1."""+ out = []+ for line in self.lines():+ parts = line.split(" ")+ fields = {}+ for item in parts[2:]:+ key, _, value = item.partition("=")+ fields[key] = value.strip('"')+ out.append((parts[1], fields))+ return out++ def names(self) -> list[str]:+ return [name for name, _ in self.events()]++ def test_off_by_default_and_a_request_writes_nothing(self):+ from serve_reqlog import ReqLog+ log = ReqLog.from_env()+ self.assertFalse(log.enabled)+ self.assertIsNone(log.path)+ self.assertIn("request log off", log.describe())+ log.log("req_start", req="r1") # disabled: a no-op, never an error+ self.assertEqual(log.lines(), [])++ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ app = serve.create_app(FakeEngine("hello"), "m", TEMPLATE)+ self.assertFalse(app["reqlog"].enabled)+ client = TestClient(TestServer(app))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": "hi"}]})+ status = response.status+ await response.read()+ await client.close()+ return status++ self.assertEqual(run(check()), 200)+ self.assertFalse(self.log_path.exists()) # nothing is created, nothing is written+ self.assertFalse(list(Path(self.tmp.name).iterdir()))++ def test_lifecycle_lines_share_one_id_and_never_hold_request_text(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ secret, reply = "PROMPT-SECRET-7f3a", "REPLY-SECRET-9b1c"+ engine = FakeEngine(reply)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ app = serve.create_app(engine, "m", TEMPLATE)+ self.assertTrue(app["reqlog"].enabled)+ client = TestClient(TestServer(app))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": secret}]})+ body = await response.json()+ await client.close()+ return body++ body = run(check())+ self.assertEqual(body["choices"][0]["message"]["content"], reply)+ events = dict(self.events())+ for want in ("req_start", "req_queued", "job_start", "job_first_token", "job_done", "req_done"):+ self.assertIn(want, events)+ ids = {fields["req"] for name, fields in self.events() if "req" in fields}+ self.assertEqual(len(ids), 1) # every line of the request carries the same id+ self.assertEqual(events["req_queued"]["queued_ahead"], "0")+ self.assertEqual(events["job_done"]["cache_n"], "8") # the engine's own cached_tokens+ self.assertEqual(events["job_done"]["cache_pct"], "40")+ self.assertIn(secret, " ".join(engine.prompts)) # the prompt really did carry the secret+ blob = "\n".join(self.lines())+ self.assertNotIn(secret, blob)+ self.assertNotIn(reply, blob)++ def test_stream_headers_first_content_and_done(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", TEMPLATE)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ await response.read()+ await client.close()++ run(check())+ names = self.names()+ for want in ("sse_headers", "sse_first_content", "sse_done", "req_done"):+ self.assertIn(want, names)+ self.assertLess(names.index("sse_headers"), names.index("sse_first_content"))+ self.assertLess(names.index("sse_first_content"), names.index("sse_done"))++ def test_refusals_are_logged_without_quoting_the_body(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", TEMPLATE)))+ await client.start_server()+ bad = await client.post("/v1/chat/completions", json={"model": "m"}) # no messages: 400+ broken = await client.post("/v1/chat/completions", data=b'{"model": "m", ',+ headers={"Content-Type": "application/json"}) # malformed JSON: 400+ await client.close()+ return bad.status, broken.status++ self.assertEqual(run(check()), (400, 400))+ refused = [fields for name, fields in self.events() if name == "req_refused"]+ self.assertEqual(len(refused), 2)+ self.assertEqual({f["status"] for f in refused}, {"400"})+ reasons = " ".join(f.get("reason", "") for f in refused)+ self.assertIn("JSONDecodeError(line=1", reasons) # reduced to line/column, not the body text+ self.assertNotIn("model", reasons)++ def test_image_request_logs_cache_hits_misses_and_budget(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ from PIL import Image+ from aiohttp.test_utils import TestClient, TestServer+ eng, _ = vision_engine()++ class VisionEngine(FakeEngine):+ supports_vision = True++ def image_tokens(self, image):+ return 3++ async def generate(self, prompt, images=None, img_stats=None, **kw):+ if images:+ serve.ResidentEngine._embed(eng, images, img_stats)+ async for piece in FakeEngine.generate(self, prompt, **kw):+ yield piece++ def uri(color):+ buf = io.BytesIO()+ Image.new("RGB", (8, 8), color).save(buf, "PNG")+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()++ body = {"model": "m", "messages": [{"role": "user", "content": [+ {"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": uri((255, 0, 0))}},+ {"type": "image_url", "image_url": {"url": uri((0, 0, 255))}}]}]}++ async def check():+ client = TestClient(TestServer(serve.create_app(VisionEngine("hello"), "m", IMAGE_TEMPLATE)))+ await client.start_server()+ for _ in range(2): # second send: both pictures are held+ response = await client.post("/v1/chat/completions", json=body)+ await response.read()+ await client.close()++ run(check())+ cache = [fields for name, fields in self.events() if name == "img_cache"]+ self.assertEqual(len(cache), 2)+ 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 start+ self.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]["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+ self.assertNotIn("data:image", "\n".join(self.lines())) # the image URL is never written++ def test_heartbeat_while_a_job_runs(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.05"+ from aiohttp.test_utils import TestClient, TestServer++ class Slow(FakeEngine):+ async def generate(self, prompt, **kwargs):+ await asyncio.sleep(0.3)+ async for piece in FakeEngine.generate(self, prompt, **kwargs):+ yield piece++ async def check():+ client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", TEMPLATE)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": "hi"}]})+ await response.read()+ await client.close()++ run(check())+ alive = [fields for name, fields in self.events() if name == "alive"]+ self.assertTrue(alive, "no heartbeat lines")+ self.assertTrue(all("elapsed_s" in f and "phase" in f for f in alive))+ self.assertTrue({f["phase"] for f in alive} <= {"parse", "queued", "prefill", "decode", "stream"})++ def test_v1_completions_is_logged_too(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", TEMPLATE)))+ await client.start_server()+ response = await client.post("/v1/completions", json={"model": "m", "prompt": "hi", "max_tokens": 4})+ await response.read()+ await client.close()+ return response.status++ self.assertEqual(run(check()), 200)+ queued = [fields for name, fields in self.events() if name == "req_queued"]+ self.assertEqual([f["path"] for f in queued], ["/v1/completions"])+ self.assertIn("job_done", self.names())+++if __name__ == "__main__":+ unittest.main()