Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Merge remote-tracking branch 'upstream/main' into glm_multi_image

MangetsuC11c1273f8d68
diff --cc tools/glm/serve.py
index 9d66645,e7eea4c..e9d5609
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@@ -108,112 -124,26 +134,130 @@@ SPEED_ENV =
# min(1, p / q) rule (exllamav3/generator/spec_sample.py): same output distribution, greedy untouched. One load, T 1 top_p
# 0.95, 15 prompts x 3 seeds: prose +5.2 % decode, no measured change on chat / code / structured. 0 = argmax drafts.
"EXL3_SPEC_SAMPLED": "1",
+ # 14/10: prefill producers write GEMM-padded rows (KDA o_proj input, mHC norm outputs) and the shared expert is
+ # added in the routed-MoE reduce epilogue: no pad copies, no separate widen + fp32 add. Bitwise: first-token and restored-
+ # prompt logits equal on vs off (3 x 8K + 1 x 32K, one load, ABBA). 8K prefill +3.7..+6.2 % (these four + the async
+ # stash, which alone shows no gain and stays off), 32K +0.3 % (shared fuse) / +2.2 % (pads). 0 = off.
+ "EXL3_NC2_SHARED_FUSE": "1",
+ "EXL3_NC2_KDA_OPAD": "1",
+ "EXL3_NC2_HC_YPAD": "1",
+ "EXL3_NC2_HC_YPAD_MLP": "1",
+ # 15/10: silu_mul, the MLA unfold and the KDA prefill norm write their GEMM input at the padded
+ # pitch; attention / MLA o_proj / the ablit projection keep fp16 output where the residual reads it. Bitwise (one load,
+ # ABBA, on top of the four above: first-token and restored-prompt logits equal, 3 x 8K + 1 x 32K); prefill +0.3 % at 8K (iGPU
+ # heat), +0.8 % at 32K. 0 = off.
+ "EXL3_NC2_SILU_PAD": "1",
+ "EXL3_NC2_MLA_OPAD": "1",
+ "EXL3_NC2_ATTN_F16": "1",
+ "EXL3_NC2_ABLIT_F16": "1",
+ "EXL3_NC2_MLA_OPROJ_F16": "1",
+ "EXL3_NC2_KDA_NPAD": "1",
}
+# 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
+# Count cap on top of the byte budget, as upstream's shared cache defaults to it (0 = no limit). For big pages
+# the byte budget binds first; for small ones this keeps the entry count bounded.
+IMAGE_CACHE_ITEMS_DEFAULT = 32
+# How the cached rows are stored (--image-cache-format). fp32 is what the vision merger emits; fp16 is exactly
+# the same values (the tower computes in fp16) and q8 rounds at one part in 254 of the row's peak. Kept here
+# rather than imported from the engine, which serve.py must not import before SPEED_ENV is applied.
+IMAGE_CACHE_FORMATS = ("fp32", "fp16", "q8")
+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.
+IMAGE_CACHE_DIR_LOCK_S = 300.0
+
+
+def make_image_cache(image_cache_bytes: int | None = None, image_cache_items: int = IMAGE_CACHE_ITEMS_DEFAULT,
+ sessions: int = 1, policy: str | None = None) -> ImageEmbeddingCache:
+ """The picture cache of the process (--image-cache-mb / --image-cache-items).
+
+ One cache for the whole server, shared by every session exactly like the KV pool `-c` sizes, with the
+ eviction policy of the shared cache in tools/strix_halo/image_cache.py: the default gives up the head of a
+ prompt a client keeps re-sending (what the servers always did), and `KYOJIN_IMAGE_CACHE_POLICY=tail` gives up
+ its tail instead. The policy remembers one prompt order per concurrent request plus one, so a conversation is
+ not forgotten between two of its own turns when another session slips in between.
+ """
+ return ImageEmbeddingCache(max_items=image_cache_items, max_orders=max(2, sessions),
+ **({} if image_cache_bytes is None else {"max_bytes": image_cache_bytes}),
+ **({} if 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, 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`
+ 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)),
+ env_fingerprint=env_fingerprint)
+
+
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.