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.

Reply budget: one exact page-aware rule (usable cache = ctx rounded down to a page, minus prompt, 1 and the speculative window); clean 400 context length exceeded; /v1/completions honours speculative:false

YanissAmzb4e33d64082d
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index aacc47c..5604219 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -201,7 +201,7 @@ def reply_room(engine: Any, prompt_tokens: int) -> int | None:
ctx = getattr(engine, "ctx", None)
if not ctx:
return None
- room = ctx - prompt_tokens - 1 - getattr(engine, "num_draft", 0)
+ room = ctx // 256 * 256 - prompt_tokens - 1 - getattr(engine, "num_draft", 0) # page table = ctx // 256 pages of 256 tokens
if room < 1:
raise web.HTTPBadRequest(reason=f"prompt is {prompt_tokens} tokens, the server context is {ctx}")
return room
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 58f49b3..360535d 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -65,6 +65,23 @@ class BadRequest(Exception):
pass
+PAGE_TOKENS = 256 # the K/V cache is allocated in pages of this many tokens (exllamav3.generator.pagetable.PAGE_SIZE)
+
+
+def reply_room(ctx: int, prompt_tokens: int, draft: int = 0) -> int:
+ """Largest max_new_tokens the generator accepts for a prompt, or less than 1 when none fits.
+ Job.prepare reserves prompt + max_new_tokens + 1 + num_draft_tokens slots (the default requeue budget: the whole reply, one
+ token and one speculative window) and asks for ceil(that / 256) pages, while the page table holds ctx // 256 pages, so
+ the usable cache is ctx rounded DOWN to a page and the window is part of the reserve. Anything above this value ends in
+ "Job requires N pages (only N-1 available)"."""
+ return ctx // PAGE_TOKENS * PAGE_TOKENS - prompt_tokens - 1 - draft
+
+
+def draft_window(engine: Any, speculative: bool = True) -> int:
+ """Draft tokens the generator reserves per window for a request: the engine's ndt when it speculates, else 0."""
+ return int(getattr(engine, "ndt", 0)) if speculative and getattr(engine, "draft_model", None) is not None else 0
+
+
# ---------------------------------------------------------------------------- parsing of the model output
@@ -740,9 +757,9 @@ class QwenEngine:
ids, embs = await loop.run_in_executor(None, self._encode, prompt, images or [])
ctx = getattr(self, "ctx", None)
if ctx: # the chat handler counted a picture as one token; its embeddings take many
- room = ctx - int(ids.numel()) - 1
+ room = reply_room(ctx, int(ids.numel()), int(getattr(self.generator, "num_draft_tokens", 0)))
if room < 1:
- raise BadRequest(f"prompt is {int(ids.numel())} tokens, the server context is {ctx}")
+ raise BadRequest(f"context length exceeded: prompt is {int(ids.numel())} tokens, the server context is {ctx}")
max_tokens = min(max_tokens, room)
if self.slot_store is not None:
self.slot_store.note_prompt(prompt, ids)
@@ -969,9 +986,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
max_tokens = body.get("max_tokens")
if max_tokens is not None and (not isinstance(max_tokens, int) or isinstance(max_tokens, bool) or max_tokens < 1):
raise BadRequest("max_tokens must be a positive integer")
- room = (ctx - prompt_tokens - 1) if ctx else default_max_tokens
+ room = reply_room(ctx, prompt_tokens, draft_window(engine, body.get("speculative", True) is not False)) if ctx else default_max_tokens
if room < 1:
- raise BadRequest(f"prompt is {prompt_tokens} tokens, the server context is {ctx}")
+ raise BadRequest(f"context length exceeded: prompt is {prompt_tokens} tokens, the server context is {ctx}")
max_tokens = min(max_tokens or default_max_tokens, room)
seed = body.get("seed")
if seed is not None and (not isinstance(seed, int) or isinstance(seed, bool)):
@@ -1162,9 +1179,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
raise BadRequest("stop must be a string or a list of strings")
ctx = getattr(engine, "ctx", None)
if ctx:
- room = ctx - engine.count_tokens(prompt) - 1
+ room = reply_room(ctx, engine.count_tokens(prompt), draft_window(engine))
if room < 1:
- raise BadRequest(f"prompt is longer than the server context ({ctx})")
+ raise BadRequest(f"context length exceeded: prompt is longer than the server context ({ctx})")
n_predict = min(n_predict, room)
job = {"prompt": prompt, "max_tokens": n_predict,
"sampling": sampling_from({k: body.get(k) for k in ("temperature", "top_p", "top_k", "min_p")}, defaults),
@@ -1231,11 +1248,11 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
prompt_tokens = engine.count_tokens(prompt)
ctx = getattr(engine, "ctx", None)
if ctx:
- room = ctx - prompt_tokens - 1
+ room = reply_room(ctx, prompt_tokens, draft_window(engine, body.get("speculative", True) is not False))
if room < 1:
- raise BadRequest(f"prompt is {prompt_tokens} tokens, the server context is {ctx}")
+ raise BadRequest(f"context length exceeded: prompt is {prompt_tokens} tokens, the server context is {ctx}")
max_tokens = min(max_tokens, room)
- job = {"prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": True, "seed": seed,
+ job = {"prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": body.get("speculative", True) is not False, "seed": seed,
"sampling": sampling_from(body, defaults), "cache_prompt": body.get("cache_prompt", True) is not False,
"loop_guard": body.get("loop_guard"), "cancel": asyncio.Event()}
except json.JSONDecodeError as exc:
diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.py
index ab379d1..6189286 100644
--- a/tools/qwen/test_serve.py
+++ b/tools/qwen/test_serve.py
@@ -443,6 +443,70 @@ class HttpTests(unittest.TestCase):
self.assertEqual(ev[-1]["choices"][0]["finish_reason"], "error")
+class ReplyRoomTests(unittest.TestCase):
+ """The reply budget must never make Job.prepare ask for more pages than the page table holds."""
+
+ @staticmethod
+ def pages_needed(x, new_tokens, draft):
+ """Job.prepare for one sequence without an explicit requeue budget: max_rq = new + 1 + draft; pagetable.Sequence.prepare."""
+ max_len = x + new_tokens + 1 + draft
+ return (max_len + 255) // 256
+
+ def test_room_is_exactly_the_largest_that_fits(self):
+ for ctx in (4096, 4097, 4351, 131072, 272384, 98305):
+ pages = ctx // 256 # PageTable.max_pages = cache.max_num_tokens // PAGE_SIZE
+ for draft in (0, 1, 3, 4):
+ for x in (1, 255, 256, 257, 1000, ctx - 300, ctx - 5, ctx - 4):
+ room = serve.reply_room(ctx, x, draft)
+ if room < 1:
+ self.assertGreater(self.pages_needed(x, 1, draft), pages, (ctx, draft, x))
+ continue
+ self.assertLessEqual(self.pages_needed(x, room, draft), pages, (ctx, draft, x)) # fits
+ self.assertGreater(self.pages_needed(x, room + 1, draft), pages, (ctx, draft, x)) # one more does not
+
+ def test_old_rule_overflowed_at_the_page_boundary(self):
+ ctx, x, draft = 131072, 1000, 3
+ old = ctx - x - 1
+ self.assertGreater(self.pages_needed(x, old, draft), ctx // 256)
+ self.assertEqual(serve.reply_room(ctx, x, draft), old - draft)
+ self.assertEqual(serve.reply_room(ctx, x, 0), old) # no speculation: nothing lost
+
+ def test_draft_window_only_when_speculating(self):
+ class E:
+ ndt, draft_model = 3, object()
+ self.assertEqual(serve.draft_window(E()), 3)
+ self.assertEqual(serve.draft_window(E(), False), 0)
+ self.assertEqual(serve.draft_window(FakeEngine("x")), 0)
+
+ def test_http_clip_and_400(self):
+ class E(FakeEngine):
+ ctx, ndt, draft_model = 4096, 3, object()
+ eng = E("x")
+ words = lambda n: "w " * n
+
+ async def fn(client):
+ out = []
+ for n, mt in ((100, 100000), (4096 - 4 - 3, 10), (4096, 10)):
+ r = await client.post("/v1/completions", json={"model": "m", "prompt": words(n), "max_tokens": mt})
+ out.append((r.status, await r.json()))
+ return out
+ res = with_client(eng, fn)
+ self.assertEqual(res[0][0], 200)
+ self.assertEqual(eng.calls[0][1]["max_tokens"], 4096 - eng.count_tokens(words(100)) - 1 - 3)
+ self.assertEqual(res[2][0], 400)
+ self.assertEqual(res[2][1]["error"]["type"], "invalid_request_error")
+ self.assertIn("context length exceeded", res[2][1]["error"]["message"])
+
+ def test_completions_honours_speculative_false(self):
+ eng = FakeEngine("x")
+
+ async def fn(client):
+ await client.post("/v1/completions", json={"model": "m", "prompt": "hi", "speculative": False})
+ await client.post("/v1/completions", json={"model": "m", "prompt": "hi"})
+ with_client(eng, fn)
+ self.assertEqual([c[1]["speculative"] for c in eng.calls], [False, True])
+
+
class MiscTests(unittest.TestCase):
def test_sse_framing_and_stop_text(self):
self.assertEqual(serve.sse({"a": 1}), b'data: {"a":1}\n\n')