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.

Serving: incremental prompt encode cache shared by the GLM and Qwen servers

YanissAmz90ddc363937d
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 0c9c7eb..9615b5b 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -25,6 +25,7 @@ from jinja2.sandbox import ImmutableSandboxedEnvironment
sys.path.append(str(Path(__file__).resolve().parent.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)
+from l21_prompt_encode_cache import PromptEncodeCache # noqa: E402 (incremental prompt encode)
# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py
from serve_metrics import Metrics
from image_cache import ImageEmbeddingCache, digest
@@ -477,6 +478,10 @@ class ResidentEngine:
self.config = Config.from_directory(model_path)
self.model = Model.from_config(self.config)
self.tokenizer = Tokenizer.from_config(self.config)
+ if os.environ.get("KYO_TOKCACHE", "8") == "0":
+ self.pec = None
+ else:
+ self.pec = PromptEncodeCache(self.tokenizer, n=int(os.environ.get("KYO_TOKCACHE", "8") or 0), cut=["<|system|>", "<|user|>", "<|assistant|>", "<|observation|>"], check=os.environ.get("KYO_TOKCACHE_CHECK") == "1", log=lambda m: print(f"serve: {m}", flush=True))
max_position = int(self.config.config_dict.get("max_position_embeddings") or self.config.config_dict.get("text_config", {}).get("max_position_embeddings") or 32768)
ctx = min(max_position, max_ctx)
self.ctx = ctx
@@ -608,6 +613,13 @@ class ResidentEngine:
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, encode_special_tokens=True).numel())
+ def prompt_ids(self, prompt: str):
+ if self.pec and self.pec.n:
+ return self.pec.encode(prompt)[0]
+ ids = self.tokenizer.encode(prompt, encode_special_tokens=True)
+ ids = ids[0] if isinstance(ids, tuple) else ids
+ return ids.reshape(-1)
+
def encode_ids(self, text: str, add_special_tokens: bool = False) -> list[int]:
"""POST /tokenize: the ids of text (special-token text is encoded as the special token; add_special_tokens adds BOS)."""
return [int(t) for t in self.tokenizer.encode(text, add_bos=add_special_tokens, encode_special_tokens=True).flatten().tolist()]
@@ -646,7 +658,7 @@ class ResidentEngine:
room = reply_room(self, int(ids.numel()))
max_tokens = min(max_tokens, room) if room else max_tokens
else:
- ids = self.tokenizer.encode(prompt, encode_special_tokens=True)
+ ids = self.prompt_ids(prompt).reshape(1, -1)
if getattr(self, "slot_store", None) is not None:
self.slot_store.note_prompt(prompt, ids)
self.last_stats = {}
@@ -1159,7 +1171,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise web.HTTPBadRequest(reason="image parts and image placeholders do not match (the chat template must write one image placeholder per image part)")
images = [load_image(u) for u in urls]
body["_images"] = images or None
- prompt_tokens = engine.count_tokens(prompt) + sum(engine.image_tokens(im) - 1 for im, _ in images)
+ prompt_tokens = int(engine.prompt_ids(prompt).numel()) + sum(engine.image_tokens(im) - 1 for im, _ in images)
body["_prompt_tokens"] = prompt_tokens
body["_room"] = reply_room(engine, prompt_tokens)
body["_prompt"] = prompt
diff --git a/tools/l21_prompt_encode_cache.py b/tools/l21_prompt_encode_cache.py
new file mode 100644
index 0000000..866322a
--- /dev/null
+++ b/tools/l21_prompt_encode_cache.py
@@ -0,0 +1,78 @@
+# Incremental prompt encoding for chat servers (model-agnostic, Python only, portable HIP / CUDA / Metal).
+# Clients (Hermes, OpenAI-style) re-send the whole conversation every turn; a full encode costs ~1.3 ms of CPU per 1K tokens
+# (90 ms at 66K, 166 ms at 128K, Qwen3.8 tokenizer). PromptEncodeCache keeps the last n (prompt, ids) pairs; a prompt that shares a text
+# prefix with one of them encodes only from the last turn-start special token (cut: one string or a list, e.g. '<|im_start|>' for
+# ChatML, ['<|system|>', '<|user|>', '<|assistant|>', '<|observation|>'] for GLM) inside the shared part. The tokenizer splits its input
+# at special tokens and encodes the pieces independently, so the ids equal the full encode's. A self-test at construction (split ==
+# full on a rendered 2-turn conversation, or on a synthetic text without render) disables the cache where that fails; check=True also
+# compares every request with the full encode (debug).
+#
+# pec = PromptEncodeCache(tokenizer, n=8, cut="<|im_start|>", render=lambda msgs: render_prompt(template, msgs, None))
+# ids, hit = pec.encode(prompt) # ids: 1-D LongTensor (CPU), same as tokenizer.encode(prompt, add_bos=False, encode_special_tokens=True)
+#
+# Not for prompts with image embeddings (encode those in full). Thread-safe (one lock).
+import re, threading
+import torch
+
+
+class PromptEncodeCache:
+
+ def __init__(self, tokenizer, n: int = 8, cut="<|im_start|>", render=None, check: bool = False, log=print):
+ cuts = [cut] if isinstance(cut, str) else list(cut)
+ self.tokenizer, self.n, self.check, self.log = tokenizer, n, check, log
+ self.e = [] # [text, ids, marker char starts, marker token positions], most recent first
+ self.lock = threading.Lock()
+ mids = [self.full(c) for c in cuts]
+ if not cuts or any(m.numel() != 1 for m in mids):
+ log(f"prompt encode cache off: {cuts!r} not one token each"); self.n = 0; return
+ self.mids = torch.tensor([int(m[0]) for m in mids])
+ self.cut_re = re.compile("|".join(re.escape(c) for c in sorted(cuts, key=len, reverse=True)))
+ msgs = [{"role": "system", "content": "S x"}, {"role": "user", "content": "Hi there, how are you?"},
+ {"role": "assistant", "content": "Fine. And you?"}, {"role": "user", "content": "Tell me about pages."}]
+ try:
+ if render is not None: p1, p2 = render(msgs[:2]), render(msgs)
+ else:
+ p1 = "Sys x " + cuts[-1] + " Hi there, how are you?\n" + cuts[0] + " ok"
+ p2 = p1[:-3] + " Fine. And you?\n" + cuts[-1] + " Tell me about pages.\n" + cuts[0]
+ self.encode(p1); ids, hit = self.encode(p2)
+ ok = hit and torch.equal(ids, self.full(p2))
+ except Exception as ex:
+ ok = False; log(f"prompt encode cache self-test error: {ex}")
+ if not ok:
+ log("prompt encode cache off: self-test failed"); self.n = 0
+ self.e = []
+
+ def full(self, p: str) -> torch.Tensor:
+ ids = self.tokenizer.encode(p, add_bos=False, encode_special_tokens=True)
+ ids = ids[0] if isinstance(ids, tuple) else ids
+ return ids.reshape(-1).cpu()
+
+ def encode(self, p: str):
+ if not self.n:
+ return self.full(p), False
+ with self.lock:
+ best = None
+ for i, (t, ids, cs, ts) in enumerate(self.e):
+ lo, hi = -1, len(cs) - 1 # last marker whose start lies inside the shared text: binary search over the markers
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if cs[mid] <= len(p) and p[:cs[mid]] == t[:cs[mid]]: lo = mid
+ else: hi = mid - 1
+ if lo >= 0 and cs[lo] > 0 and (best is None or cs[lo] > best[1]):
+ best = (i, cs[lo], ts[lo], lo == len(cs) - 1) # last item: p extends this entry (same conversation)
+ if best is not None:
+ i, c, tpos, _ = best
+ ids = torch.cat([self.e[i][1][:tpos], self.full(p[c:])])
+ if self.check and not torch.equal(ids, self.full(p)):
+ self.log("prompt encode cache MISMATCH, full encode used"); ids, best = self.full(p), None
+ else:
+ ids = self.full(p)
+ self._add(p, ids, best[0] if best is not None and best[3] else None)
+ return ids, best is not None
+
+ def _add(self, p, ids, drop=None):
+ cs = [m.start() for m in self.cut_re.finditer(p)]
+ ts = torch.isin(ids, self.mids).nonzero().reshape(-1).tolist()
+ if len(cs) == len(ts):
+ if drop is not None: self.e.pop(drop)
+ self.e.insert(0, [p, ids, cs, ts]); del self.e[self.n:]
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 2fd373a..6f92f16 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -42,6 +42,7 @@ sys.path.append(str(HERE.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
import image_cache # noqa: E402 (shared bounded LRU of image embeddings; symlink to tools/strix_halo)
import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)
+from l21_prompt_encode_cache import PromptEncodeCache # noqa: E402 (incremental prompt encode)
def _load_mimo():
@@ -743,6 +744,10 @@ class QwenEngine:
self.sessions = sessions
self.config = Config.from_directory(model_path)
self.tokenizer = Tokenizer.from_config(self.config)
+ if os.environ.get("KYO_TOKCACHE", "8") == "0":
+ self.pec = None
+ else:
+ self.pec = PromptEncodeCache(self.tokenizer, n=int(os.environ.get("KYO_TOKCACHE", "8") or 0), cut="<|im_start|>", check=os.environ.get("KYO_TOKCACHE_CHECK") == "1", log=lambda m: print(f"qserve: {m}", flush=True))
self.eos = list(self.config.eos_token_id_list)
self.model = Model.from_config(self.config)
# cache_bits 0 (default) = the fp16 K/V pages; 8 (--cache-bits 8) = packed int8 K/V pages (2.6 GiB less at 256K), indexer
@@ -854,6 +859,13 @@ class QwenEngine:
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, add_bos=False, encode_special_tokens=True).numel())
+ def prompt_ids(self, prompt: str):
+ if self.pec and self.pec.n:
+ return self.pec.encode(prompt)[0]
+ ids = self.tokenizer.encode(prompt, add_bos=False, encode_special_tokens=True)
+ ids = ids[0] if isinstance(ids, tuple) else ids
+ return ids.reshape(-1)
+
def encode_ids(self, text: str, add_special_tokens: bool = False) -> list[int]:
"""POST /tokenize: the ids of text (special-token text is encoded as the special token; add_special_tokens adds BOS)."""
return [int(t) for t in self.tokenizer.encode(text, add_bos=add_special_tokens, encode_special_tokens=True).flatten().tolist()]
@@ -890,7 +902,7 @@ class QwenEngine:
for emb in embs:
prompt = prompt.replace(IMAGE_PAD, emb.text_alias, 1)
kw = {"embeddings": embs} if embs else {}
- ids = self.tokenizer.encode(prompt, add_bos=False, encode_special_tokens=True, **kw)
+ ids = self.prompt_ids(prompt).reshape(1, -1) if not embs else self.tokenizer.encode(prompt, add_bos=False, encode_special_tokens=True, **kw)
return ids, embs
def _close_ids(self) -> tuple[int | None, list[int]]:
@@ -1472,7 +1484,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
stops = [stops] if isinstance(stops, str) else list(stops)
if not all(isinstance(s, str) for s in stops):
raise BadRequest("stop must be a string or a list of strings")
- prompt_tokens = engine.count_tokens(prompt)
+ prompt_tokens = int(engine.prompt_ids(prompt).numel())
ctx = getattr(engine, "ctx", None)
max_tokens = body.get("max_completion_tokens")
if max_tokens is None: