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
Hy4 server: a request without max_tokens gets the room left in the context window, a larger max_tokens is clipped instead of refused (issue #222)
YanissAmz84df96b090bb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b4aa3f..af76f7d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,15 @@Base draft graph of 2 steps plus a confidence-gated third step. Fires counter per request: depth chosen per round and rounds where the gate changed the depth.The gate's tail graph uses the same bucket helper as `HY4_GRAPH_BUCKET_REL`. See `doc/env_vars.md`.- Hy4-flash server fixes of issue #222, also released as 1.9.2.1: see the 1.9.2.1 section below (no hang after a refused request, named part errors, harmless parts accepted, `KYOJIN_IMAGE_PARTS` default `note`).+- Hy4-flash server reply budget (issue #222), also released as 1.9.2.2: see the 1.9.2.2 section below (`--default-max-tokens 0` = all the room left is the new default; a larger `max_tokens` is clipped, not a 400).++## 1.9.2.2++Hy4-flash server: a request without `max_tokens` is no longer cut at 1024 tokens, and a `max_tokens` larger than the context window can hold is clipped, not refused (issue #222: an agent client's context compaction ended with stop reason `length`).++- `--default-max-tokens 0` is the new default: a request with no `max_tokens` / `max_completion_tokens` may use all the room left in the context window (`-c` minus the prompt tokens, the draft rows and 2), like vLLM. A positive value keeps the old cap behaviour (the old default was `1024`). A negative value stops the start-up with a message.+- A `max_tokens` (or the positive default) larger than the room left is clipped to the room; the reply ends with `finish_reason: "length"` when the clipped budget is used. It was a 400 (`prompt (N tokens) + max_tokens (M) exceeds the context window`). A prompt that leaves no room for one token is still a 400, with a message that says so. Same on `/v1/chat/completions` and `/v1/completions`, streamed or not.+- New CPU tests: `tests/test_hy4_max_tokens.py`.## 1.9.2.1diff --git a/README.md b/README.mdindex 55df8e4..28bfab8 100644--- a/README.md+++ b/README.md@@ -85,7 +85,7 @@ curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/jso-d '{"messages": [{"role": "user", "content": "Say hello in five words."}]}'```-Hy4-flash thinks before it answers: the reasoning comes back in `reasoning_content` and the answer in `content`, so a small `max_tokens` can end inside the reasoning and leave `content` empty. For a direct answer add `"reasoning_effort": "no_think"` (or `"chat_template_kwargs": {"reasoning_effort": "no_think"}`), or leave room for the reasoning with a larger `max_tokens`:+Hy4-flash thinks before it answers: the reasoning comes back in `reasoning_content` and the answer in `content`, so a small `max_tokens` can end inside the reasoning and leave `content` empty. For a direct answer add `"reasoning_effort": "no_think"` (or `"chat_template_kwargs": {"reasoning_effort": "no_think"}`), or leave room for the reasoning with a larger `max_tokens`. A request without `max_tokens` may use all the room left in the context window (`--default-max-tokens 0`, the default; a positive value caps it), and a `max_tokens` larger than that room is clipped to it, not refused:```bashcurl http://localhost:8300/v1/chat/completions -H "Content-Type: application/json" \diff --git a/doc/hy4.md b/doc/hy4.mdindex d2c1d49..f892526 100644--- a/doc/hy4.md+++ b/doc/hy4.md@@ -81,6 +81,8 @@ Native Engram IO: `exllamav3/loader/engram_io.c` is compiled with `gcc` at first`--num-draft` is the number of MTP drafts per round (3 by default). Memory: the K buffers are sized by `-c` (about 0.1 MB per position); see Supported context for the measured totals.+`--default-max-tokens` is the reply budget of a request that sends no `max_tokens` / `max_completion_tokens`. `0` (the default since 1.9.2.2) means all the room left in the context window (`-c` minus the prompt, the draft rows and 2), so a long reasoning is not cut at 1024 tokens and a client that sets no limit (a compaction call, for example) gets a full answer. A positive value is a cap (1.9.2.1 and earlier: `1024`). A `max_tokens` (asked or defaulted) larger than the room left is clipped to the room, and the reply ends with `finish_reason: "length"` if it uses all of it; it is not a 400 any more. Only a prompt that leaves no room for one token is a 400. This holds for `/v1/chat/completions` and `/v1/completions`, streamed or not.+The start-up warm-up prompt is clamped to the context window (and skipped with one log line when the window is too small), so a small `-c` starts normally.## Supported contextdiff --git a/tests/test_hy4_max_tokens.py b/tests/test_hy4_max_tokens.pynew file mode 100644index 0000000..84c0d26--- /dev/null+++ b/tests/test_hy4_max_tokens.py@@ -0,0 +1,263 @@+"""Reply budget of the Hy4 server (issue #222: an agent client's context compaction ended with stop reason `length`).+A request without max_tokens gets all the room left in the context window (--default-max-tokens 0, the default); a positive default is a cap;+a max_tokens larger than the room is clipped to it (no 400); only a prompt with no room for one token is a 400. Chat and completions, streamed or not.+CPU test of tools/hy4/serve.py with a fake engine (no GPU, no model).+Run: python -m unittest tests/test_hy4_max_tokens.py (needs aiohttp + jinja2 + tokenizers)"""+import argparse+import asyncio+import json+import os+import sys+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tools", "hy4"))+sys.path.insert(0, HERE)+import serve as S # noqa: E402+import serve_core as C # noqa: E402+from test_hy4_serve_core import tiny_meta # noqa: E402++try:+ from aiohttp.test_utils import TestClient, TestServer+except ImportError: # pragma: no cover+ TestClient = None++CTX = 16384+DRAFT = 3+FILL = 97 # byte id of "a"+TMO = 20+CHAT = "/v1/chat/completions"+COMP = "/v1/completions"+++class FillEngine:+ """generates `fill` tokens of "a" (None = never stops) or max_new of them, whichever is smaller; ends with the EOS token when it stops by itself.+ Records the max_new it was given and refuses a call that would not fit the context window, as the real engine does."""++ def __init__(self, ctx, k, fill=None, eos=258):+ self.ctx, self.k, self.fill, self.eos, self.calls = ctx, k, fill, eos, []++ def generate(self, ids, max_new, on_tokens, speculative=True, cancel=lambda: False):+ assert len(ids) + max_new + self.k + 2 <= self.ctx, (len(ids), max_new, self.ctx)+ self.calls.append((len(ids), max_new))+ total = max_new if self.fill is None else min(self.fill, max_new)+ n, stop = 0, False+ while n < total and not stop:+ step = min(64, total - n)+ n += step+ stop = on_tokens([FILL] * step)+ if self.fill is not None and self.fill < max_new and not stop:+ on_tokens([self.eos])+ return {"prompt_tokens": len(ids), "prefill_s": 0.5, "prefill_trunk_s": 0.4, "prime_s": 0.1, "prime_mode": "fake", "decode_s": 0.25,+ "decode_tokens": n, "ttft_s": 0.5, "rounds": 1, "accept_hist": [0, 0, 0, 1], "tau": 1.0, "speculative": speculative}+++def make_state(default_max=0, ctx=CTX, fill=None):+ args = argparse.Namespace(model_id="Hy4-test", max_ctx=ctx, num_draft=DRAFT, default_max_tokens=default_max)+ st = S.State(args)+ st.vocab = C.Vocab(tiny_meta())+ st.engine = FillEngine(ctx, DRAFT, fill=fill)+ st.ready = True+ st.lock = asyncio.Lock()+ return st+++def long_text(n_tokens):+ """a text of exactly n_tokens tokens in the byte-level test vocabulary"""+ return "b" * n_tokens+++def chat_body(n_prompt, **kw):+ return dict(messages=[{"role": "user", "content": long_text(n_prompt)}], reasoning_effort="no_think", **kw)++[email protected](TestClient is None, "aiohttp not installed")+class MaxTokens(unittest.IsolatedAsyncioTestCase):+ async def start(self, **kw):+ self.st = make_state(**kw)+ self.client = TestClient(TestServer(S.build_app(self.st)))+ await self.client.start_server()+ return self.st++ async def asyncTearDown(self):+ await self.client.close()++ async def call(self, path, body):+ """-> (status, finish_reason, completion_tokens or None, error message or None); a streamed reply is read to [DONE]"""+ async def go():+ r = await self.client.post(path, json=body)+ raw = await r.read()+ return r.status, raw+ status, raw = await asyncio.wait_for(go(), TMO)+ if status != 200:+ return status, None, None, json.loads(raw)["error"]["message"]+ if not body.get("stream"):+ j = json.loads(raw)+ return status, j["choices"][0]["finish_reason"], j["usage"]["completion_tokens"], None+ chunks = [json.loads(l[6:]) for l in raw.decode().split("\n\n") if l.startswith("data: {")]+ finish = [c["choices"][0]["finish_reason"] for c in chunks if c["choices"] and c["choices"][0].get("finish_reason")]+ usage = [c["usage"]["completion_tokens"] for c in chunks if c.get("usage")]+ self.assertTrue(raw.rstrip().endswith(b"[DONE]"))+ return status, finish[-1], (usage[-1] if usage else None), None++ def prompt_len(self, body, path):+ """number of prompt tokens the server counts for this body"""+ if path == CHAT:+ r = C.parse_chat(body, 0)+ return len(self.st.vocab.encode(self.st.vocab.chat_prompt(r)[0]))+ return len(self.st.vocab.encode(body["prompt"]))++ def room(self, n):+ return CTX - n - DRAFT - 2++ def cases(self, n, **kw):+ """the same request on both endpoints, streamed and not"""+ for stream in (False, True):+ extra = dict(kw, stream=stream, stream_options={"include_usage": True}) if stream else dict(kw)+ yield CHAT, chat_body(n, **extra)+ yield COMP, dict(prompt=long_text(n), **extra)++ # -- no max_tokens: the whole room left+ async def test_no_max_tokens_long_prompt_gets_the_room(self):+ await self.start(default_max=0)+ for path, body in self.cases(6000):+ with self.subTest(path=path, stream=body.get("stream", False)):+ self.st.engine.calls.clear()+ status, finish, n_gen, err = await self.call(path, body)+ self.assertEqual(status, 200, err)+ n = self.prompt_len(body, path)+ self.assertGreater(n, 6000 - 1)+ self.assertEqual(self.st.engine.calls, [(n, self.room(n))])+ self.assertEqual(finish, "length") # the filler never stops: it used all the budget+ self.assertGreater(self.room(n), 1024)+ if n_gen is not None:+ self.assertEqual(n_gen, self.room(n))++ async def test_no_max_tokens_reply_shorter_than_room_stops(self):+ await self.start(default_max=0, fill=3000)+ for path, body in self.cases(6000):+ with self.subTest(path=path, stream=body.get("stream", False)):+ status, finish, n_gen, err = await self.call(path, body)+ self.assertEqual(status, 200, err)+ self.assertEqual(finish, "stop")+ if n_gen is not None:+ self.assertGreater(n_gen, 1024) # not cut at the old default++ async def test_no_max_tokens_short_prompt(self):+ await self.start(default_max=0)+ for path, body in self.cases(10):+ n = self.prompt_len(body, path)+ self.st.engine.calls.clear()+ status, finish, _, err = await self.call(path, body)+ self.assertEqual((status, finish), (200, "length"), err)+ self.assertEqual(self.st.engine.calls, [(n, self.room(n))])++ # -- explicit max_tokens larger than the room: clipped+ async def test_explicit_too_large_is_clipped_not_400(self):+ await self.start(default_max=0)+ for big in (100000, CTX, CTX - 100):+ for path, body in self.cases(6000, max_tokens=big):+ with self.subTest(big=big, path=path, stream=body.get("stream", False)):+ self.st.engine.calls.clear()+ status, finish, _, err = await self.call(path, body)+ self.assertEqual(status, 200, err)+ n = self.prompt_len(body, path)+ self.assertEqual(self.st.engine.calls, [(n, min(big, self.room(n)))])+ self.assertEqual(finish, "length")++ async def test_max_completion_tokens_alias_is_clipped_too(self):+ await self.start(default_max=0)+ status, finish, _, err = await self.call(CHAT, chat_body(6000, max_completion_tokens=100000))+ self.assertEqual((status, finish), (200, "length"), err)+ n = self.prompt_len(chat_body(6000), CHAT)+ self.assertEqual(self.st.engine.calls, [(n, self.room(n))])+ self.st.engine.calls.clear()+ status, _, _, err = await self.call(CHAT, chat_body(6000, max_completion_tokens=40, max_tokens=100000)) # the newer name wins+ self.assertEqual(status, 200, err)+ self.assertEqual(self.st.engine.calls, [(n, 40)])++ # -- explicit small: unchanged+ async def test_explicit_small_is_unchanged(self):+ await self.start(default_max=0)+ for path, body in self.cases(6000, max_tokens=50):+ with self.subTest(path=path, stream=body.get("stream", False)):+ self.st.engine.calls.clear()+ status, finish, n_gen, err = await self.call(path, body)+ self.assertEqual((status, finish), (200, "length"), err)+ self.assertEqual(self.st.engine.calls[0][1], 50)+ if n_gen is not None:+ self.assertEqual(n_gen, 50)++ # -- --default-max-tokens N > 0 keeps the cap+ async def test_positive_default_is_a_cap(self):+ await self.start(default_max=1024)+ for path, body in self.cases(6000):+ with self.subTest(path=path, stream=body.get("stream", False)):+ self.st.engine.calls.clear()+ status, finish, n_gen, err = await self.call(path, body)+ self.assertEqual((status, finish), (200, "length"), err)+ self.assertEqual(self.st.engine.calls[0][1], 1024)+ if n_gen is not None:+ self.assertEqual(n_gen, 1024)+ # an explicit value is still honoured above the cap (up to the room), and a cap larger than the room is clipped+ self.st.engine.calls.clear()+ status, _, _, err = await self.call(CHAT, chat_body(6000, max_tokens=3000))+ self.assertEqual(status, 200, err)+ self.assertEqual(self.st.engine.calls[0][1], 3000)+ self.st.engine.calls.clear()+ self.st.args.default_max_tokens = 50000+ status, _, _, err = await self.call(CHAT, chat_body(6000))+ n = self.prompt_len(chat_body(6000), CHAT)+ self.assertEqual((status, self.st.engine.calls), (200, [(n, self.room(n))]), err)++ # -- a prompt that does not fit is a 400, with or without max_tokens+ async def test_prompt_that_does_not_fit_is_400(self):+ await self.start(default_max=0)+ for n_prompt in (CTX + 500, CTX, CTX - 3, CTX - DRAFT - 2):+ for extra in ({}, {"max_tokens": 10}):+ for path, body in self.cases(n_prompt, **extra):+ with self.subTest(n=n_prompt, extra=extra, path=path, stream=body.get("stream", False)):+ status, _, _, err = await self.call(path, body)+ self.assertEqual(status, 400, err)+ self.assertIn("does not fit the context window", err)+ self.assertIn(str(CTX), err)+ self.assertEqual(self.st.engine.calls, []) # a refused request never reached the engine+ status, finish, _, err = await self.call(CHAT, chat_body(10, max_tokens=5)) # and the server answers the next one+ self.assertEqual((status, finish), (200, "length"), err)++ async def test_one_token_of_room_is_served(self):+ await self.start(default_max=0)+ body = dict(prompt=long_text(CTX - DRAFT - 3))+ status, finish, _, err = await self.call(COMP, body)+ self.assertEqual((status, finish), (200, "length"), err)+ self.assertEqual(self.st.engine.calls, [(CTX - DRAFT - 3, 1)])++[email protected](TestClient is None, "aiohttp not installed")+class Flag(unittest.TestCase):+ def test_flag_default_is_zero_and_negative_is_refused(self):+ import io+ from contextlib import redirect_stderr+ with unittest.mock.patch.object(S, "apply_env", side_effect=SystemExit("stop here")), unittest.mock.patch.object(S, "check_kernels"):+ with self.assertRaises(SystemExit) as cm:+ S.main(["--model", "x.gguf"])+ self.assertEqual(str(cm.exception), "stop here")+ err = io.StringIO()+ with redirect_stderr(err), self.assertRaises(SystemExit) as cm:+ S.main(["--model", "x.gguf", "--default-max-tokens", "-5"])+ self.assertEqual(cm.exception.code, 2)+ self.assertIn("--default-max-tokens", err.getvalue())++ def test_parse_default_zero_means_no_budget_yet(self):+ self.assertIsNone(C.parse_chat({"messages": [{"role": "user", "content": "x"}]}, 0)["max_tokens"])+ self.assertIsNone(C.parse_completion({"prompt": "x"}, 300, 0)["max_tokens"])+ self.assertEqual(C.parse_chat({"messages": [{"role": "user", "content": "x"}], "max_tokens": 7}, 0)["max_tokens"], 7)+ self.assertEqual(C.parse_chat({"messages": [{"role": "user", "content": "x"}]}, 512)["max_tokens"], 512)+ with self.assertRaises(C.RequestError):+ C.parse_chat({"messages": [{"role": "user", "content": "x"}], "max_tokens": 0}, 0)+++import unittest.mock # noqa: E402++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_hy4_request_error.py b/tests/test_hy4_request_error.pyindex 99c8708..9943653 100644--- a/tests/test_hy4_request_error.py+++ b/tests/test_hy4_request_error.py@@ -51,9 +51,7 @@ def bad_cases():("bad_stop", chat, {"messages": [USER], "stop": 5}),("json_format", chat, {"messages": [USER], "response_format": {"type": "json_object"}}),("oversize_prompt", chat, {"messages": [{"role": "user", "content": "x " * 20000}], "reasoning_effort": "no_think"}),- ("oversize_max_tokens", chat, {"messages": [USER], "max_tokens": 999999}),("completion_empty", "/v1/completions", {"prompt": ""}),- ("completion_oversize", "/v1/completions", {"prompt": "x", "max_tokens": 99999}),]out = []for name, path, body in cases:diff --git a/tests/test_hy4_serve_http.py b/tests/test_hy4_serve_http.pyindex c4d51b8..e223b78 100644--- a/tests/test_hy4_serve_http.py+++ b/tests/test_hy4_serve_http.py@@ -119,7 +119,7 @@ class Http(unittest.IsolatedAsyncioTestCase):async def test_errors(self):for path, body, status in (("/v1/chat/completions", {"messages": []}, 400), ("/v1/chat/completions", {"messages": [{"role": "user", "content": "x"}], "tools": [1]}, 400),- ("/v1/completions", {"prompt": ""}, 400), ("/v1/completions", {"prompt": "x", "max_tokens": 99999}, 400)):+ ("/v1/completions", {"prompt": ""}, 400)):r = await self.client.post(path, json=body)j = await r.json()self.assertEqual(r.status, status, j)diff --git a/tools/hy4/serve.py b/tools/hy4/serve.pyindex e22a942..36f14f9 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -177,9 +177,16 @@ def build_app(st: State):r["in_think"] = not r["prefill"] and r["effort"] != "no_think" and bool(v.think_begin) and text.rstrip().endswith(v.think_begin)return r, ids- def check_len(n, max_new):- if n + max_new + args.num_draft + 2 > args.max_ctx:- raise C.RequestError(f"prompt ({n} tokens) + max_tokens ({max_new}) exceeds the context window ({args.max_ctx})", 400, "context_length_exceeded")+ def fit_budget(n, r):+ """Set r["max_tokens"] to the reply budget the context window allows for an n-token prompt. A request without max_tokens (and --default-max-tokens 0)+ gets all the room left; a larger budget (asked or defaulted) is clipped to the room, and the reply ends with finish_reason `length` if it uses it.+ Only a prompt that leaves no room for one token is a 400."""+ room = args.max_ctx - n - args.num_draft - 2+ if room < 1:+ raise C.RequestError(f"prompt ({n} tokens) does not fit the context window ({args.max_ctx}): no room left to reply; shorten the prompt or start the server with a larger -c",+ 400, "context_length_exceeded")+ want = r["max_tokens"]+ r["max_tokens"] = room if want is None else min(want, room)async def run_job_mu(ids, r, in_think, request):"""--slots > 1: the request joins the scheduler (own slot, batched decode with the other sessions); same events as run_job"""@@ -327,7 +334,7 @@ def build_app(st: State):try:need_ready()r, ids = prompt_for_chat(await read_body(request))- check_len(len(ids), r["max_tokens"])+ fit_budget(len(ids), r)rid, created = C.new_id("chatcmpl"), int(time.time())m = args.model_idif not r["stream"]:@@ -377,7 +384,7 @@ def build_app(st: State):need_ready()r = C.parse_completion(await read_body(request), st.vocab.size, args.default_max_tokens)ids = r["prompt_ids"] if r["prompt_ids"] is not None else st.vocab.encode(r["prompt"])- check_len(len(ids), r["max_tokens"])+ fit_budget(len(ids), r)rid, created, m = C.new_id("cmpl"), int(time.time()), args.model_idif not r["stream"]:text, stats, finish, n_gen = [], None, "length", 0@@ -506,10 +513,14 @@ def main(argv=None):ap.add_argument("--num-draft", type=int, default=3, help="MTP draft tokens per round (verify T = k + 1 rows)")ap.add_argument("--prefill-chunk", type=int, default=8192)ap.add_argument("--draft-fill-rows", type=int, default=0, help="fill the draft head's cache for the last N prompt rows only (0 = the whole prompt)")- ap.add_argument("--default-max-tokens", type=int, default=1024)+ ap.add_argument("--default-max-tokens", type=int, default=0,+ help="reply budget of a request without max_tokens: 0 (default) = all the room left in the context window (-c minus the prompt); N > 0 = at most N tokens. "+ "A max_tokens larger than the room left is clipped to it (finish_reason length), never refused")ap.add_argument("--slots", type=int, default=1, help="concurrent sessions decoded in ONE batched step (1 = the single-request engine behind the lock)")ap.add_argument("--sched-chunk", type=int, default=1024, help="prefill rows per scheduler turn with --slots > 1 (a decode round of the other sessions runs between chunks)")args = ap.parse_args(argv)+ if args.default_max_tokens < 0:+ ap.error("--default-max-tokens must be 0 (all the room left in the context window) or a positive number of tokens")apply_env(args.max_ctx, args.model, args.slots)check_kernels()st = State(args)diff --git a/tools/hy4/serve_core.py b/tools/hy4/serve_core.pyindex 6a17c7f..61d10dc 100644--- a/tools/hy4/serve_core.py+++ b/tools/hy4/serve_core.py@@ -246,7 +246,8 @@ def _common(body: dict, default_max: int) -> dict:mt = body.get("max_completion_tokens") # the newer name wins; an explicit null falls back to max_tokensif mt is None:mt = body.get("max_tokens")- max_tokens = default_max if mt is None else _as_int({"max_tokens": mt}, "max_tokens", default_max, 1)+ # None = the request names no budget and the server has no cap (--default-max-tokens 0): the server then gives the whole room left in the context window+ max_tokens = (default_max if default_max > 0 else None) if mt is None else _as_int({"max_tokens": mt}, "max_tokens", default_max, 1)for k in ("temperature", "top_p", "presence_penalty", "frequency_penalty"):v = body.get(k)if v is not None and (isinstance(v, bool) or not isinstance(v, (int, float))):