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 and MiMo servers: clamp the reply budget to the room left in the context
YanissAmz2dd36d75ad56
diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 48e04f1..4026e12 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -200,8 +200,21 @@ def token_limit(body: dict[str, Any], default: int = 4096) -> int:for key in ("max_completion_tokens", "max_tokens"):value = body.get(key)if isinstance(value, int) and not isinstance(value, bool) and value >= 1:- return value- return default+ return min(value, body.get("_room") or value)+ return min(default, body.get("_room") or default)+++def reply_room(engine: Any, prompt_tokens: int) -> int | None:+ """Tokens a reply may still use: server context minus prompt, one slot and the speculative window.+ None when the engine does not report a context (fake engines). A prompt with no room is refused,+ as the cache cannot hold it (the engine would otherwise fail the job with an assertion)."""+ ctx = getattr(engine, "ctx", None)+ if not ctx:+ return None+ room = ctx - prompt_tokens - 1 - getattr(engine, "num_draft", 0)+ if room < 1:+ raise web.HTTPBadRequest(reason=f"prompt is {prompt_tokens} tokens, the server context is {ctx}")+ return roomdef sse(data: dict[str, Any], event: str | None = None) -> bytes:@@ -225,11 +238,13 @@ class ResidentEngine:torch.set_grad_enabled(False)self.torch = torchself.Job = Job+ self.num_draft = num_draftself.config = Config.from_directory(model_path)self.model = Model.from_config(self.config)self.tokenizer = Tokenizer.from_config(self.config)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 = ctxself.cache = Cache(self.model, max_num_tokens=ctx + 4096,max_history=max_history)self.model.load(device="cuda:0", progressbar=False)@@ -460,6 +475,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:body["_stop"] = [stops] if isinstance(stops, str) else list(stops)prompt = render_prompt(template, body["messages"], body.get("tools"), **template_kwargs(body))prompt_tokens = engine.count_tokens(prompt)+ body["_room"] = reply_room(engine, prompt_tokens)body["_prompt"] = promptfor key in ("temperature", "top_p"):if body.get(key) is None:@@ -606,6 +622,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:if n_predict <= 0:n_predict = 128n_predict = min(n_predict, 8192)+ room = reply_room(engine, engine.count_tokens(prompt))+ if room:+ n_predict = min(n_predict, room)stops = body.get("stop", [])job = {"_prompt": prompt, "max_tokens": n_predict,"temperature": float(body.get("temperature", 0.0)),diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex 04aae1e..dd0de16 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -104,6 +104,40 @@ class ServeTests(unittest.TestCase):self.assertEqual(engine.kwargs["max_tokens"], 4)self.assertEqual(body["choices"][0]["finish_reason"], "length")+ def test_reply_budget_is_clamped_to_the_context_room(self):+ from aiohttp.test_utils import TestClient, TestServer++ class Spy(FakeEngine):+ ctx = 20+ num_draft = 1++ async def generate(self, prompt: str, **kwargs):+ self.kwargs = kwargs+ async for piece in super().generate(prompt, **kwargs):+ yield piece++ engine = Spy("one two")++ async def post(content, **extra):+ client = TestClient(TestServer(serve.create_app(engine, "m", self.template)))+ await client.start_server()+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": content}], **extra})+ status = r.status+ await r.read()+ await client.close()+ return status++ # room = ctx - prompt - 1 slot - 1 draft token+ self.assertEqual(run(post("a b c d", max_completion_tokens=32768)), 200)+ used = engine.count_tokens(engine.prompts[-1])+ self.assertEqual(engine.kwargs["max_tokens"], 20 - used - 1 - 1)+ self.assertEqual(run(post("a b c d", max_tokens=3)), 200)+ self.assertEqual(engine.kwargs["max_tokens"], 3)+ engine.kwargs = None+ self.assertEqual(run(post(" ".join("w" * 30))), 400)+ self.assertIsNone(engine.kwargs)+def test_template_rendering(self):out = serve.render_prompt(self.template, [{"role": "user", "content": "hi"}], [{"type": "function"}])self.assertEqual(out, "<|im_start|>user: hi<|im_end|>TOOLS=1")diff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex 24afb7a..12482a5 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -150,8 +150,21 @@ def token_limit(body: dict[str, Any], default: int = 4096) -> int:for key in ("max_completion_tokens", "max_tokens"):value = body.get(key)if isinstance(value, int) and not isinstance(value, bool) and value >= 1:- return value- return default+ return min(value, body.get("_room") or value)+ return min(default, body.get("_room") or default)+++def reply_room(engine: Any, prompt_tokens: int) -> int | None:+ """Tokens a reply may still use: server context minus prompt, one slot and the speculative window.+ None when the engine does not report a context (fake engines). A prompt with no room is refused,+ as the cache cannot hold it (the engine would otherwise fail the job with an assertion)."""+ ctx = getattr(engine, "ctx", None)+ if not ctx:+ return None+ room = ctx - prompt_tokens - 1 - getattr(engine, "num_draft", 0)+ if room < 1:+ raise web.HTTPBadRequest(reason=f"prompt is {prompt_tokens} tokens, the server context is {ctx}")+ return roomdef sse(data: dict[str, Any], event: str | None = None) -> bytes:@@ -220,6 +233,8 @@ class ResidentEngine:elif self.generator.draft_calibrator is not None:self.load_prior(self.generator.draft_calibrator)self.Job = Job+ self.ctx = ctx or config_max_position(self.config)+ self.num_draft = self.ndtdef count_tokens(self, text: str) -> int:return int(self.tokenizer.encode(text, encode_special_tokens=True).numel())@@ -344,6 +359,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:body["_reset_gate"] = bool(getattr(app["engine"], "reset_gate_per_request", False))prompt = render_prompt(template, body["messages"], body.get("tools"))prompt_tokens = engine.count_tokens(prompt)+ body["_room"] = reply_room(engine, prompt_tokens)body["_prompt"] = promptfor key in ("temperature", "top_p"): # absent or explicit null -> lane defaultif body.get(key) is None:@@ -494,6 +510,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:if n_predict <= 0:n_predict = 128n_predict = min(n_predict, 8192)+ room = reply_room(engine, engine.count_tokens(prompt))+ if room:+ n_predict = min(n_predict, room)stops = body.get("stop", [])job = {"_prompt": prompt, "max_tokens": n_predict,"temperature": float(body.get("temperature", SERVE_DEFAULTS["temperature"])),diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.pyindex c805f2c..09a50ca 100644--- a/tools/mimo/test_serve.py+++ b/tools/mimo/test_serve.py@@ -47,6 +47,40 @@ TEMPLATE = ("{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|iclass ServeTests(unittest.TestCase):+ def test_reply_budget_is_clamped_to_the_context_room(self):+ from aiohttp.test_utils import TestClient, TestServer++ class Spy(FakeEngine):+ ctx = 20+ num_draft = 1++ async def generate(self, prompt: str, **kwargs):+ self.kwargs = kwargs+ async for piece in super().generate(prompt, **kwargs):+ yield piece++ engine = Spy("one two")++ async def post(content, **extra):+ client = TestClient(TestServer(serve.create_app(engine, "m", TEMPLATE)))+ await client.start_server()+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": content}], **extra})+ status = r.status+ await r.read()+ await client.close()+ return status++ # room = ctx - prompt - 1 slot - 1 draft token+ self.assertEqual(run(post("a b c d", max_completion_tokens=32768)), 200)+ used = engine.count_tokens(engine.prompts[-1])+ self.assertEqual(engine.kwargs["max_tokens"], 20 - used - 1 - 1)+ self.assertEqual(run(post("a b c d", max_tokens=3)), 200)+ self.assertEqual(engine.kwargs["max_tokens"], 3)+ engine.kwargs = None+ self.assertEqual(run(post(" ".join("w" * 30))), 400)+ self.assertIsNone(engine.kwargs)+def test_template_rendering(self):out = serve.render_prompt(TEMPLATE, [{"role": "user", "content": "hi"}],[{"type": "function"}])