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: --image-cache-format stores cached picture embeddings in fewer bytes
MangetsuC1a888b8af358
diff --git a/exllamav3/modules/embedding.py b/exllamav3/modules/embedding.pyindex d3f85ac..2f777fd 100644--- a/exllamav3/modules/embedding.py+++ b/exllamav3/modules/embedding.py@@ -5,7 +5,7 @@ from torch import nnfrom ..model.config import Configfrom ..util.tensor import to2from . import Module-from ..tokenizer.mm_embedding import FIRST_MM_EMBEDDING_INDEX+from ..tokenizer.mm_embedding import FIRST_MM_EMBEDDING_INDEX, mm_rowsfrom ..model.model_tp_alloc import TPAllocationclass Embedding(Module):@@ -130,7 +130,9 @@ class Embedding(Module):continuefor i in range(bsz):indexed_ids_row = input_ids[i][im[i]] - ie.first_index- combined_emb[i][im[i]] = ie.embeddings[indexed_ids_row].to(out_dtype)+ # mm_rows() is the same gather when the rows are a plain tensor, and dequantizes 8 bit+ # rows on the device when a server stores them that way (see QuantizedMMRows)+ combined_emb[i][im[i]] = mm_rows(ie, indexed_ids_row, out_dtype, combined_emb.device)# Prepare deepstack embeddingsif ie.deepstack_embeddings is not None:diff --git a/exllamav3/tokenizer/mm_embedding.py b/exllamav3/tokenizer/mm_embedding.pyindex af9e571..78e4156 100644--- a/exllamav3/tokenizer/mm_embedding.py+++ b/exllamav3/tokenizer/mm_embedding.py@@ -119,6 +119,94 @@ class MMEmbedding:return self.token_list[self.align_lead - n_pad:]+# Packed storage modes for the picture cache of a model server, next to fp16: 8 bit is a quarter of the fp32+# rows and stays within half a step of the row's peak (measured 0.86 % relative error over four real pages).+MM_QUANT_MODES = ("q8",)+++class QuantizedMMRows:+ """One image's rows held 8 bit on the host, with a per-row fp16 scale.++ A server that keeps the embeddings of a whole conversation in host memory can store them this way+ instead of the fp32 rows the vision tower's merger emits (four bytes per value), which is what the+ picture cache spends its budget on: a quarter of the bytes. The rows go back to their working dtype when+ the model gathers them: `mm_rows` is the only place their values are read, and the scaling happens there,+ so the packed values cross the bus instead of fp32 and the algebra is one multiply per value.++ Setting `MMEmbedding.embeddings` to one of these does not touch the object's pseudo token ids, so a prompt+ spliced from a hit keeps matching the paged KV cache exactly as an unquantized one does. Only the values+ that reach the model change, by the rounding this class introduces: at most half a step, one part in 254+ of the row's peak.+ """++ __slots__ = ("q", "scale", "shape", "dtype", "nbytes")++ def __init__(self, q: torch.Tensor, scale: torch.Tensor, dtype: torch.dtype):+ self.q = q # uint8, (rows, hidden), offset by 128+ self.scale = scale # fp16, (rows, 1)+ self.shape = tuple(q.shape)+ self.dtype = dtype # what the rows were quantized from+ self.nbytes = int(q.numel()) + int(scale.numel()) * int(scale.element_size())++ def numel(self) -> int:+ return self.shape[0] * self.shape[1]++ def element_size(self) -> int:+ return 1++ def rows(self, index: torch.Tensor, out_dtype: torch.dtype | None = None,+ device: torch.device | None = None) -> torch.Tensor:+ """Rows `index` in `out_dtype` (default: the dtype the rows had). `index` may live anywhere: the+ gather is on the host where the rows are, the scaling where the result is wanted. The scale is applied+ in 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."""+ out_dtype = out_dtype or self.dtype+ index = index.to(self.q.device)+ values = self.q[index].to(out_dtype).sub_(128.0) # stored offset by half the range, so uint8+ scale = self.scale[index].to(out_dtype)+ if device is not None and device.type != "cpu":+ values, scale = values.to(device, non_blocking = True), scale.to(device, non_blocking = True)+ return values.mul_(scale)++ def __repr__(self) -> str: # keeps logs and errors readable+ rows, hidden = self.shape+ return f"QuantizedMMRows({rows}x{hidden} 8 bit, {self.nbytes / 2 ** 20:.1f} MiB)"+++def quantize_rows(tensor: torch.Tensor, mode: str = "fp32"):+ """The stored form of one image's rows for `mode`: fp32 (unchanged), fp16 (half the bytes) or `q8` (8 bit+ with one fp16 scale per row, a quarter).++ fp16 is not a lossy choice for a tower that computes in fp16: its fp32 output is an fp16 value widened, so+ storing it back as fp16 rounds nothing — measured on this pack over four real pages, where every value+ survives `x.half().float() == x` unchanged.++ Symmetric, offset-binary 8 bit: a value costs the same byte whatever its row looks like, and it comes back+ within half a step of where it was, i.e. one part in 254 of the row's peak."""+ if mode in ("fp32", "none", ""):+ return tensor+ if mode == "fp16":+ return tensor.half()+ if mode not in MM_QUANT_MODES:+ raise ValueError(f"unknown image embedding format {mode!r} (fp32, fp16 or {', '.join(MM_QUANT_MODES)})")+ x = tensor.detach()+ if x.dim() != 2:+ x = x.reshape(-1, x.shape[-1])+ scale = (x.abs().amax(dim = 1, keepdim = True) / 127.0).clamp_min(1e-8).to(torch.float16)+ code = torch.round(x / scale.to(x.dtype)).add_(128.0).clamp_(1, 255).to(torch.uint8)+ return QuantizedMMRows(code, scale, x.dtype)+++def mm_rows(emb: MMEmbedding, index: torch.Tensor, out_dtype: torch.dtype | None = None,+ device: torch.device | None = None) -> torch.Tensor:+ """Rows `index` of one image embedding in `out_dtype`, dequantizing when the rows are stored packed.+ A plain tensor takes the path it always did."""+ src = emb.embeddings+ if isinstance(src, QuantizedMMRows):+ return src.rows(index, out_dtype, device)+ return src[index].to(out_dtype) if out_dtype is not None else src[index]++def send_embeddings(producer, ies: list[MMEmbedding]):return {"method": "list",diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex c388d7b..d0eec6b 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -32,6 +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` | 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-format` | `fp32` | how the cached rows are stored: `fp32` as the vision merger emits them, `fp16` (half the bytes, **measured bit-exact on this pack**) or `q8` (8 bit with one fp16 scale per row, a quarter, 0.86 % error) || `--sessions` | `1` | requests decoded together through the one model (multi-user). `1` = one request at a time, others wait || `--row-budget` | `5` when `--sessions` > 1 | caps the verify rows per round by lowering the draft depth when several sessions are busy; `0` = off || `--num-draft` | `2` | draft tokens per speculative round; `0` = plain decode, no drafter |@@ -129,6 +130,16 @@ still runs from the first page to where the cache ended rather than collapsing t`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+re-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+merger's fp32 output is an fp16 value widened, so nothing is rounded and the saving is free — and `q8` loses+0.863 % (rms 1.3e-4, 41 dB).+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 defaultssince 1.5; a value already in the environment wins. Measured on this model: start to ready 771 s -> 65 s, first@@ -208,7 +219,7 @@ queue and the worker. Events, in the order a request that goes through produces| event | written when | useful fields ||---|---|---|-| `serve_start` | server ready, once | `ctx`, `cache_tokens`, `sessions`, `num_draft`, `row_budget`, `vision`, `conv_gemm`, `dense_tune`, `image_cache_mb`, `image_cache_items` |+| `serve_start` | server ready, once | `ctx`, `cache_tokens`, `sessions`, `num_draft`, `row_budget`, `vision`, `conv_gemm`, `dense_tune`, `image_cache_mb`, `image_cache_items`, `image_cache_format` || `req_start` | request arrives | `path`, `method`, `bytes` || `req_refused` | 400/404/... answer | `status`, `reason` (the server's own text; a JSON parse error is reduced to line/column) || `req_queued` | handed to the worker queue | `queued_ahead`, `prompt_tokens`, `messages`, `images`, `stream` |diff --git a/tools/glm/image_cache_glm.py b/tools/glm/image_cache_glm.pyindex e48315c..7a54b88 100644--- a/tools/glm/image_cache_glm.py+++ b/tools/glm/image_cache_glm.py@@ -46,11 +46,14 @@ def digest(raw: bytes) -> str:def embedding_nbytes(emb: Any) -> int:- """Host bytes of an MMEmbedding: its rows and its deepstack rows."""+ """Host bytes of an MMEmbedding: its rows and its deepstack rows, in whatever form they are stored.+ Quantized rows report their own size (int8 plus scales), so the budget counts what is really held."""total = 0for 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())+ if t is None:+ continue+ nbytes = getattr(t, "nbytes", None)+ total += int(nbytes) if nbytes is not None else int(t.numel()) * int(t.element_size())return totaldiff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 8b55a94..04a8066 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -115,6 +115,11 @@ IMAGE_CACHE_AUTO_MIN_MB = 512IMAGE_CACHE_AUTO_MAX_MB = 2048IMAGE_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.+IMAGE_CACHE_FORMATS = ("fp32", "fp16", "q8")+def physical_ram_bytes() -> int:"""Installed RAM, or 0 when the platform will not say."""@@ -464,7 +469,8 @@ class ResidentEngine:def __init__(self, model_path: str, max_history: int = 1, max_ctx: int = 131072, num_draft: int = 1,vision: bool = True, sessions: int = 1,- image_cache_bytes: int | None = None, image_cache_items: int = 0):+ image_cache_bytes: int | None = None, image_cache_items: int = 0,+ image_cache_format: str = "fp32"):import torchfrom exllamav3 import Cache, Config, Generator, Job, Model, Tokenizerfrom exllamav3.generator import generator as GM@@ -514,6 +520,7 @@ class ResidentEngine:else: # --num-draft 0: plain decode, no drafterself.draft_model = self.draft_cache = Noneself.vision = None+ self.image_cache_format = image_cache_formatself.emb_cache = make_image_cache(image_cache_bytes, image_cache_items, sessions)if vision:self.vision = self._load_vision()@@ -604,10 +611,16 @@ class ResidentEngine:cache = self.emb_cacheentries_before = len(cache)built: set[int] = set()+ mode = getattr(self, "image_cache_format", "fp32")def build(image):t0 = time.perf_counter()emb = self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=image)+ if mode != "fp32": # store the rows compressed; the ids and the text alias are untouched+ # imported here, not at module level: exllamav3 reads some of the speed defaults at import+ # time, and serve.py must not pull it in before SPEED_ENV is applied+ from exllamav3.tokenizer.mm_embedding import quantize_rows+ emb.embeddings = quantize_rows(emb.embeddings, mode)built.add(id(emb)) # tells a hit from a miss once get_many() hands the list back in prompt orderprint(f"serve: image {image.size[0]}x{image.size[1]} -> {emb.mm_length} tokens, tower {(time.perf_counter() - t0) * 1000:.0f} ms", flush=True)return emb@@ -1716,6 +1729,10 @@ def main() -> None:"Strix Halo: about 50 MiB per manga page, 1 MB per small crop")parser.add_argument("--image-cache-items", type=int, default=0,help="optional cap on how many pictures are held at once (0 = only the byte budget)")+ parser.add_argument("--image-cache-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)")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,@@ -1771,13 +1788,14 @@ def main() -> None: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,- image_cache_bytes=image_cache_bytes, image_cache_items=args.image_cache_items)+ image_cache_bytes=image_cache_bytes, image_cache_items=args.image_cache_items,+ image_cache_format=args.image_cache_format)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)+ f"{args.image_cache_format} rows, 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":@@ -1827,6 +1845,7 @@ def main() -> None:moe_fused=os.environ.get("EXL3_MOE_FUSED", "0"),image_cache_mb=round(emb_cache.max_bytes / 2 ** 20, 1) if emb_cache is not None else None,image_cache_items=getattr(emb_cache, "max_items", None),+ image_cache_format=getattr(engine, "image_cache_format", "fp32"),heartbeat_s=reqlog.heartbeat_s)sock = startup_health.finish() # the early listener's open socket: no refused connectionif sock is not None:diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex db152cd..b71dae4 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -73,7 +73,7 @@ def vision_engine():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.embeddings = torch.zeros(3, 64, dtype=torch.half)self.deepstack_embeddings = Noneclass Tower:@@ -116,6 +116,34 @@ class ImageCacheBudgetTests(unittest.TestCase):self.assertEqual(cache.max_bytes, 2048 << 20)self.assertEqual(cache.max_items, 0)+ def test_the_cli_format_list_covers_every_engine_mode(self):+ from exllamav3.tokenizer.mm_embedding import MM_QUANT_MODES+ self.assertEqual(set(serve.IMAGE_CACHE_FORMATS), {"fp32", "fp16"} | set(MM_QUANT_MODES))++ def test_embed_stores_the_rows_in_the_requested_format(self):+ # --image-cache-format: fp32 and fp16 leave a plain tensor, q8 keeps the rows 8 bit. Either way the+ # object, its pseudo token ids and its length are the ones the prompt cache is keyed on, and the cache+ # counts the bytes of the form it actually holds (3 rows x 64 half values = 384 B as they are).+ from PIL import Image+ from exllamav3.tokenizer.mm_embedding import QuantizedMMRows+ from image_cache_glm import embedding_nbytes+ eng, _ = vision_engine()+ img = Image.new("RGB", (8, 8))+ counts, packed = {}, {}+ for mode in serve.IMAGE_CACHE_FORMATS:+ eng.image_cache_format = mode+ eng.emb_cache.clear()+ emb = serve.ResidentEngine._embed(eng, [(img, f"key-{mode}")], None)[0]+ self.assertEqual(emb.mm_length, 3)+ self.assertEqual(emb.text_alias, f"<$EMB_{emb.first_index}$>") # ids and alias untouched+ self.assertEqual(int(emb.embeddings.numel()), 192) # logical values, not packed bytes+ packed[mode] = isinstance(emb.embeddings, QuantizedMMRows)+ counts[mode] = embedding_nbytes(emb)+ self.assertEqual(packed, {"fp32": False, "fp16": False, "q8": True})+ self.assertEqual(counts["fp32"], 384) # as the tower emitted them+ self.assertEqual(counts["fp16"], 384) # two bytes a value+ self.assertEqual(counts["q8"], 192 + 3 * 2) # one byte each + one scale per row+class RequestLogTests(unittest.TestCase):"""KYOJIN_REQLOG: off unless asked for; when on, one line per lifecycle event, numbers and names only."""