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 serve: stream text as soon as it cannot be part of a marker
YanissAmz5cc38bbc4173
diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex f62bd9a..615a448 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -513,6 +513,18 @@ def guard_stats(hit: dict, n_new: int) -> dict:return {"eos_reason": "loop_guard", "new_tokens": n_new, "loop_guard": hit}+def held_tail(text: str, markers: list[str]) -> int:+ """Characters at the end of `text` that could still become one of `markers` (a proper prefix of one). A stream holds back only+ these: holding a marker-length tail delayed the first visible text by several tokens, which under load is several seconds."""+ best = 0+ for m in markers:+ for k in range(min(len(m) - 1, len(text)), best, -1):+ if text.endswith(m[:k]):+ best = k+ break+ return best++def opens_thinking(prompt: str) -> bool:"""The GLM generation prompt ends in <think>, so the model output starts inside the block."""return prompt.rstrip().endswith("<think>")@@ -1665,7 +1677,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:# Reasoning and prose stream as they decode. Tool calls are parsed only from complete# XML, so everything from <tool_call> on is held and sent once at the end.text, done, mode = prefix, len(prefix), "reasoning" if prefix else "content"- hold = max([len("</think>"), len(TOOL_OPEN)] + [len(x) for x in body["_stop"]]) - 1+ holds = ["</think>", "<think>", TOOL_OPEN] + [x for x in body["_stop"] if x]visible: list[float] = [] # set at the first frame with text in it: the client's first sign of lifeasync def flush(final: bool) -> None:@@ -1673,7 +1685,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:while mode != "tool":tags = ["</think>"] if mode == "reasoning" else ["<think>", TOOL_OPEN]hits = [(text.find(t, done), t) for t in tags if text.find(t, done) >= 0]- end = min(hits)[0] if hits else (len(text) if final else max(done, len(text) - hold))+ end = min(hits)[0] if hits else (len(text) if final else max(done, len(text) - held_tail(text, holds)))piece = stop_text(text[done:end], body["_stop"])[0]if piece:if not visible:diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex 9f08bd4..2152b39 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -333,6 +333,34 @@ class ServeTests(unittest.TestCase):self.assertEqual([len(m) for m in msgs], [1, 1, 1])self.assertEqual([m[0]["index"] for m in msgs], [0, 1, 2])+ def test_held_tail_is_only_a_possible_marker_prefix(self):+ marks = ["</think>", "<think>", serve.TOOL_OPEN, "STOP"]+ self.assertEqual(serve.held_tail("plain words", marks), 0)+ self.assertEqual(serve.held_tail("abc <tool_ca", marks), len("<tool_ca"))+ self.assertEqual(serve.held_tail("abc <", marks), 1)+ self.assertEqual(serve.held_tail("abc ST", marks), 2)+ self.assertEqual(serve.held_tail("abc </think", marks), len("</think"))+ self.assertEqual(serve.held_tail("<", marks), 1)+ self.assertEqual(serve.held_tail("", marks), 0)++ def test_stream_first_text_is_not_held_back_by_a_marker_length(self):+ from aiohttp.test_utils import TestClient, TestServer+ engine = FakeEngine('plan it</think>Sure.<tool_call>get_weather<arg_key>city</arg_key><arg_value>Paris</arg_value></tool_call>')+ app = serve.create_app(engine, "m", self.template + "<think>")++ async def check():+ client = TestClient(TestServer(app))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ raw = (await response.read()).decode()+ await client.close()+ return raw++ chunks = [json.loads(l[6:]) for l in run(check()).split("\n") if l.startswith("data: {")]+ reasoning = [c["choices"][0]["delta"]["reasoning_content"] for c in chunks if "reasoning_content" in c["choices"][0]["delta"]]+ self.assertEqual(reasoning[0], "pla") # the first 3-character engine chunk goes out at once+def test_stream_open_think_and_tool_call(self):from aiohttp.test_utils import TestClient, TestServerengine = FakeEngine('plan it</think>Sure.<tool_call>get_weather<arg_key>city</arg_key>'diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex 0478da0..08beb9e 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -743,7 +743,7 @@ class SSEKeepAliveTests(unittest.TestCase):body = run(check())self.assertTrue([line for line in body.split(b"\n") if line.startswith(b":")], body[:400])- self.assertLess(body.index(b": waiting"), body.index(b"hello")) # before the first token+ self.assertLess(body.index(b": waiting"), body.index(b'"content":"hel')) # before the first tokenself.assertTrue(body.rstrip().endswith(b"data: [DONE]")) # the stream still ends the OpenAI waydef test_a_ping_covers_a_tool_call_the_server_holds_back(self):@@ -1044,7 +1044,7 @@ class SSEKeepAliveTests(unittest.TestCase):body = run(check())self.assertEqual([line for line in body.split(b"\n") if line.startswith(b":")], [])- self.assertIn(b"hello", body)+ self.assertIn(b'"content":"hel', body)if __name__ == "__main__":