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.

Hy4 server: OpenAI-compatible backend (chat + completions, SSE) on the graph + MTP decode path and the prefill fast path; GGUF chat template and tokenizer; CPU tests

YanissAmzb45977075695
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 58e77f7..042a205 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -734,18 +734,21 @@ class Hy4Forward:
with self.tm.t("head"):
return self._head(x, all_pos)
- def _head(self, x, all_pos=False):
+ def head_state(self, xl):
+ """xl [R, hc, n_embd] -> [R, n_embd]: the trunk state the output head reads (hyper-head mix + output norm), no vocabulary GEMM"""
fn, base, scale = self.hh
- xl = x if all_pos else x[-1:]
R = xl.shape[0]
if _HCF is not None and self.hook is None and _HCF.ok(xl, self.hh, self.hc):
- h = _HCF.site(xl, self.hh, self.out_norm, self.eps, self.hc_eps, self.magnitude)[1]
- else:
- mix = rms(xl.reshape(R, -1), self.eps) @ fn.T
- pre = torch.sigmoid(mix * scale[0] + base) + self.hc_eps
- col = (xl * pre[:, :, None]).sum(1)
- self._hk("hc_head", -1, col)
- h = rms(col, self.eps) * self.out_norm
+ return _HCF.site(xl, self.hh, self.out_norm, self.eps, self.hc_eps, self.magnitude)[1]
+ mix = rms(xl.reshape(R, -1), self.eps) @ fn.T
+ pre = torch.sigmoid(mix * scale[0] + base) + self.hc_eps
+ col = (xl * pre[:, :, None]).sum(1)
+ self._hk("hc_head", -1, col)
+ return rms(col, self.eps) * self.out_norm
+
+ def _head(self, x, all_pos=False):
+ xl = x if all_pos else x[-1:]
+ h = self.head_state(xl)
self._h = h # the trunk state the output head reads (MTP draft input)
if self.head_cpu:
h = h.cpu()
diff --git a/tests/data/hy4_chat_template.jinja b/tests/data/hy4_chat_template.jinja
new file mode 100644
index 0000000..22ec3c8
--- /dev/null
+++ b/tests/data/hy4_chat_template.jinja
@@ -0,0 +1,355 @@
+{#- ----------‑‑‑ special token variables ‑‑‑---------- -#}
+{%- set HYTK = ':6124c78e' %}
+{%- set hy_start_token = '<|hy_start{}|>'.format(HYTK) %}
+{%- set hy_middle_token = '<|hy_middle{}|>'.format(HYTK) %}
+{%- set hy_end_token = '<|hy_end{}|>'.format(HYTK) %}
+{%- set image_start_token = '<|hy_image▁start{}|>'.format(HYTK) %}
+{%- set image_pad_token = '<|hy_image▁pad{}|>'.format(HYTK) %}
+{%- set image_end_token = '<|hy_image▁end{}|>'.format(HYTK) %}
+{%- set video_start_token = '<|hy_video▁start{}|>'.format(HYTK) %}
+{%- set video_pad_token = '<|hy_video▁pad{}|>'.format(HYTK) %}
+{%- set video_end_token = '<|hy_video▁end{}|>'.format(HYTK) %}
+{%- set think_begin_token = '<think{}>'.format(HYTK) %}
+{%- set think_end_token = '</think{}>'.format(HYTK) %}
+{%- set toolcalls_begin_token = '<tool_calls{}>'.format(HYTK) %}
+{%- set toolcalls_end_token = '</tool_calls{}>'.format(HYTK) %}
+{%- set toolcall_begin_token = '<tool_call{}>'.format(HYTK) %}
+{%- set toolcall_end_token = '</tool_call{}>'.format(HYTK) %}
+{%- set argkey_begin_token = '<arg_key{}>'.format(HYTK) %}
+{%- set argkey_end_token = '</arg_key{}>'.format(HYTK) %}
+{%- set argvalue_begin_token = '<arg_value{}>'.format(HYTK) %}
+{%- set argvalue_end_token = '</arg_value{}>'.format(HYTK) %}
+{%- set toolresponse_begin_token = '<tool_response{}>'.format(HYTK) %}
+{%- set toolresponse_end_token = '</tool_response{}>'.format(HYTK) %}
+{%- set reasoning_mode_token = '<|reasoning_mode{}|>'.format(HYTK) %}
+
+{#- ----------‑‑‑ hyperparameters variables ‑‑‑---------- -#}
+{%- if not add_generation_prompt is defined %}
+ {%- set add_generation_prompt = false %}
+{%- endif %}
+{%- if not preserved_thinking is defined %}
+ {%- if not tools %}
+ {%- set preserved_thinking = false %}
+ {%- else %}
+ {%- set preserved_thinking = true %}
+ {%- endif %}
+{%- endif %}
+
+{%- if not reasoning_effort is defined %}
+ {%- set reasoning_effort = 'high' %}
+{%- elif reasoning_effort not in ['max', 'high', 'low', 'no_think'] %}
+ {%- if reasoning_effort is none %}
+ {{- raise_exception('reasoning_effort error : None, should be no_think/low/high/max') }}
+ {%- else %}
+ {{- raise_exception('reasoning_effort error : ' + reasoning_effort + ', should be no_think/low/high/max') }}
+ {%- endif %}
+{%- endif %}
+
+{%- if fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry' %}
+ {%- set reasoning_effort = 'high' %}
+ {%- set add_generation_prompt = false %}
+{%- endif %}
+{%- if not raw_last_assistant is defined %}
+ {%- set raw_last_assistant = false %}
+{%- endif %}
+{%- if not add_vision_id is defined %}
+ {%- set add_vision_id = false %}
+{%- endif %}
+{%- set image_count = namespace(value=0) %}
+{%- set video_count = namespace(value=0) %}
+
+{%- macro tool_to_json(tool) -%}
+ {%- set ns_tool = namespace(first=true) -%}
+ {{- '{' -}}
+ {%- for k, v in tool.items() -%}
+ {%- if k != 'defer_loading' and k != 'strict' -%}
+ {%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%}
+ {%- set ns_tool.first = false -%}
+ {{- '"' ~ k ~ '": ' ~ (v | tojson(ensure_ascii=False)) -}}
+ {%- endif -%}
+ {%- endfor -%}
+ {{- '}' -}}
+{%- endmacro -%}
+
+{%- macro render_content(content, do_vision_count=true, is_system_content=false) -%}
+ {%- if content is string -%}
+ {{- content -}}
+ {%- elif content is iterable and content is not mapping -%}
+ {%- for item in content -%}
+ {%- if item is mapping and item.type == 'text' -%}
+ {{- item.text -}}
+ {%- elif item is mapping and ('image' in item or 'image_url' in item or item.type in ['image', 'image_url']) -%}
+ {%- if is_system_content -%}
+ {{- raise_exception('System message cannot contain images.') -}}
+ {%- endif -%}
+ {%- if do_vision_count -%}
+ {%- set image_count.value = image_count.value + 1 -%}
+ {%- endif -%}
+ {%- if add_vision_id -%}
+ {{- 'Picture ' ~ image_count.value ~ ': ' -}}
+ {%- endif -%}
+ {{- image_start_token ~ image_pad_token ~ image_end_token -}}
+ {%- elif item is mapping and ('video' in item or 'video_url' in item or item.type in ['video', 'video_url']) -%}
+ {%- if is_system_content -%}
+ {{- raise_exception('System message cannot contain videos.') -}}
+ {%- endif -%}
+ {%- if do_vision_count -%}
+ {%- set video_count.value = video_count.value + 1 -%}
+ {%- endif -%}
+ {%- if add_vision_id -%}
+ {{- 'Video ' ~ video_count.value ~ ': ' -}}
+ {%- endif -%}
+ {{- video_start_token ~ video_pad_token ~ video_end_token -}}
+ {%- elif item is string -%}
+ {{- item -}}
+ {%- else -%}
+ {{- item | string -}}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- elif content is none -%}
+ {{- '' -}}
+ {%- else -%}
+ {{- content | string -}}
+ {%- endif -%}
+{%- endmacro -%}
+
+{%- macro render_tools_prompt() -%}
+ {{- '# Tools\n\nYou may call one or more functions to assist with the user query.' -}}
+ {{- '\n\nYou are provided with function signatures within <tools></tools> XML tags:' -}}
+ {{- '\n<tools>\n' -}}
+ {%- set tool_ns = namespace(first=true) -%}
+ {%- for tool in tools -%}
+ {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%}
+ {%- if t.defer_loading is not defined or not t.defer_loading -%}
+ {%- if not tool_ns.first -%}{{- '\n' -}}{%- endif -%}
+ {%- set tool_ns.first = false -%}
+ {{- tool_to_json(t) -}}
+ {%- endif -%}
+ {%- endfor -%}
+ {{- '\n</tools>\n\n' -}}
+ {{- 'For function call returns, you should first print ' ~ toolcalls_begin_token -}}
+ {{- '\nFor each function call, you should return object like:\n' -}}
+ {{- toolcall_begin_token ~ '{function-name}' -}}
+ {{- argkey_begin_token ~ '{arg-key-1}' ~ argkey_end_token -}}
+ {{- argvalue_begin_token ~ '{arg-value-1}' ~ argvalue_end_token -}}
+ {{- argkey_begin_token ~ '{arg-key-2}' ~ argkey_end_token -}}
+ {{- argvalue_begin_token ~ '{arg-value-2}' ~ argvalue_end_token -}}
+ {{- '...' -}}
+ {{- toolcall_end_token -}}
+ {{- '\nAt the end of function call returns, you should print ' ~ toolcalls_end_token -}}
+{%- endmacro -%}
+
+{#- adjacent tool_search_output parts share one <tools> block, so a tool search result has the same shape as the tools prompt -#}
+{%- macro render_tool_response(message) -%}
+ {%- set content = message['content'] -%}
+ {{- toolresponse_begin_token -}}
+ {%- if content is string -%}
+ {{- content -}}
+ {%- elif content is iterable and content is not mapping -%}
+ {%- set tools_ns = namespace(open=false) -%}
+ {%- for item in content -%}
+ {%- set is_search_output = item is mapping and item.type is defined and item.type == 'tool_search_output' -%}
+ {%- if is_search_output and not tools_ns.open -%}
+ {{- '<tools>\n' -}}
+ {%- set tools_ns.open = true -%}
+ {%- elif not is_search_output and tools_ns.open -%}
+ {{- '</tools>' -}}
+ {%- set tools_ns.open = false -%}
+ {%- endif -%}
+ {%- if is_search_output -%}
+ {%- if item.tools is defined and item.tools is iterable -%}
+ {%- for tool in item.tools -%}
+ {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%}
+ {{- tool_to_json(t) ~ '\n' -}}
+ {%- endfor -%}
+ {%- endif -%}
+ {%- elif item is mapping and item.output is defined -%}
+ {{- render_content(item.output) -}}
+ {%- else -%}
+ {{- render_content([item]) -}}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- if tools_ns.open -%}
+ {{- '</tools>' -}}
+ {%- endif -%}
+ {%- else -%}
+ {{- render_content(content) -}}
+ {%- endif -%}
+ {{- toolresponse_end_token -}}
+{%- endmacro -%}
+
+{#- consecutive tool messages are clustered into a single tool message whose content is the list of the original tool messages; the result is written to merged_ns.messages (a macro cannot return a list) -#}
+{%- set merged_ns = namespace(messages=[]) %}
+{%- macro merge_tool_responses(messages) -%}
+ {%- set merge_ns = namespace(result=[], cluster=[]) -%}
+ {%- for message in messages -%}
+ {%- if message['role'] == 'tool' -%}
+ {%- set merge_ns.cluster = merge_ns.cluster + [message] -%}
+ {%- else -%}
+ {%- if merge_ns.cluster -%}
+ {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%}
+ {%- set merge_ns.cluster = [] -%}
+ {%- endif -%}
+ {%- set merge_ns.result = merge_ns.result + [message] -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- if merge_ns.cluster -%}
+ {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%}
+ {%- endif -%}
+ {%- set merged_ns.messages = merge_ns.result -%}
+{%- endmacro -%}
+
+{#- render one tool cluster, reordered to follow the tool_call order of the preceding assistant turn; any missing / ambiguous id falls back to the original tool message order for the whole cluster -#}
+{%- macro render_tool_responses(tool_messages, tool_call_ids) -%}
+ {%- set order_ns = namespace(ordered=[], matched=true) -%}
+ {%- if tool_call_ids and tool_call_ids | length == tool_messages | length -%}
+ {%- for tool_call_id in tool_call_ids -%}
+ {%- set hit_ns = namespace(count=0, message=none) -%}
+ {%- for tool_message in tool_messages -%}
+ {%- set message_id = tool_message['tool_call_id'] if tool_message['tool_call_id'] is defined else tool_message['id'] -%}
+ {%- if message_id is defined and message_id == tool_call_id -%}
+ {%- set hit_ns.count = hit_ns.count + 1 -%}
+ {%- set hit_ns.message = tool_message -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- if hit_ns.count == 1 -%}
+ {%- set order_ns.ordered = order_ns.ordered + [hit_ns.message] -%}
+ {%- else -%}
+ {%- set order_ns.matched = false -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- else -%}
+ {%- set order_ns.matched = false -%}
+ {%- endif -%}
+ {%- for tool_message in (order_ns.ordered if order_ns.matched else tool_messages) -%}
+ {{- render_tool_response(tool_message) -}}
+ {%- endfor -%}
+{%- endmacro -%}
+
+{%- set _ = merge_tool_responses(messages) %}
+{%- set normed_messages = merged_ns.messages %}
+
+{%- set ns = namespace(last_user_index=-1, has_leading_system=false) %}
+{%- if normed_messages and normed_messages[0].role == 'system' %}
+ {%- set ns.has_leading_system = true %}
+{%- endif %}
+{%- for message in normed_messages %}
+ {%- if message['role'] == 'user' %}
+ {%- set ns.last_user_index = loop.index0 %}
+ {%- endif %}
+{%- endfor %}
+
+{#- no leading system: synthesize one for tools and/or reasoning_mode -#}
+{%- if not ns.has_leading_system %}
+ {{- hy_start_token ~ 'system' ~ hy_middle_token -}}
+ {%- if tools %}
+ {{- render_tools_prompt() -}}
+ {%- endif %}
+ {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}}
+ {{- hy_end_token -}}
+{%- endif %}
+
+{%- set last_ns = namespace(last_is_assistant=false) %}
+{%- set prev_ns = namespace(tool_call_ids=[]) %}
+{%- for message in normed_messages %}
+ {%- if message['role'] == 'system' %}
+ {{- hy_start_token ~ 'system' ~ hy_middle_token -}}
+ {#- tools / reasoning_mode only attach to the leading system (messages[0]) -#}
+ {%- if loop.first %}
+ {%- if tools %}
+ {{- render_tools_prompt() -}}
+ {%- endif %}
+ {%- set content = render_content(message['content']) -%}
+ {%- if tools and content -%}
+ {{- '\n\n' -}}
+ {%- endif -%}
+ {{- content -}}
+ {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}}
+ {%- else %}
+ {{- render_content(message['content']) -}}
+ {%- endif %}
+ {{- hy_end_token -}}
+ {%- elif message['role'] == 'user' %}
+ {{- hy_start_token ~ 'user' ~ hy_middle_token -}}
+ {{- render_content(message['content']) -}}
+ {{- hy_end_token -}}
+ {%- elif message['role'] == 'assistant' %}
+ {%- set content_body = render_content(message['content']) -%}
+ {#- 'reasoning' takes precedence, fall back to 'reasoning_content' when it is empty -#}
+ {%- set reasoning_text = '' %}
+ {%- if message['reasoning'] is defined and message['reasoning'] is string and message['reasoning'] %}
+ {%- set reasoning_text = message['reasoning'] %}
+ {%- elif message['reasoning_content'] is defined and message['reasoning_content'] is string and message['reasoning_content'] %}
+ {%- set reasoning_text = message['reasoning_content'] %}
+ {%- endif %}
+ {#- no_think overrides preserved_thinking: history is always emitted with empty think tags -#}
+ {%- if reasoning_effort != 'no_think' and (preserved_thinking or loop.index0 > ns.last_user_index) and reasoning_text %}
+ {%- set content = think_begin_token ~ reasoning_text ~ think_end_token ~ content_body %}
+ {%- else %}
+ {%- set content = think_begin_token ~ think_end_token ~ content_body %}
+ {%- endif %}
+ {{- hy_start_token ~ 'assistant' ~ hy_middle_token -}}
+ {%- if message['tool_calls'] is defined and message['tool_calls'] %}
+ {#- remember the tool_call ids of this turn to order the following tool responses; an incomplete id set means "do not reorder" -#}
+ {%- set ids_ns = namespace(ids=[], complete=true) %}
+ {%- for tool in message['tool_calls'] %}
+ {%- set tool_call_id = tool['id'] if tool['id'] is defined and tool['id'] else tool['tool_call_id'] %}
+ {%- if tool_call_id is defined and tool_call_id %}
+ {%- set ids_ns.ids = ids_ns.ids + [tool_call_id] %}
+ {%- else %}
+ {%- set ids_ns.complete = false %}
+ {%- endif %}
+ {%- endfor %}
+ {%- set prev_ns.tool_call_ids = ids_ns.ids if ids_ns.complete else [] %}
+ {{- content -}}
+ {{- toolcalls_begin_token -}}
+ {%- for tool in message['tool_calls'] -%}
+ {%- set func = tool['function'] if tool is mapping and 'function' in tool else tool -%}
+ {%- set arguments = func['arguments'] -%}
+ {{- toolcall_begin_token ~ func['name'] -}}
+ {%- for key, value in arguments.items() -%}
+ {{- argkey_begin_token ~ key ~ argkey_end_token -}}
+ {%- if value is not string -%}
+ {%- set value = value | tojson(ensure_ascii=False) -%}
+ {%- endif -%}
+ {{- argvalue_begin_token ~ value ~ argvalue_end_token -}}
+ {%- endfor -%}
+ {{- toolcall_end_token -}}
+ {%- endfor -%}
+ {{- toolcalls_end_token -}}
+ {%- else %}
+ {%- if loop.last and raw_last_assistant %}
+ {{- content_body -}}
+ {%- else %}
+ {{- content -}}
+ {%- endif %}
+ {%- endif %}
+ {#- continuation / prefill: last assistant is still open, do not close with hy_end -#}
+ {%- if not (loop.last and raw_last_assistant) and not (loop.last and fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry') %}
+ {{- hy_end_token -}}
+ {%- endif %}
+ {%- elif message['role'] == 'tool' %}
+ {{- hy_start_token ~ 'tool' ~ hy_middle_token -}}
+ {{- render_tool_responses(message['content'], prev_ns.tool_call_ids) -}}
+ {{- hy_end_token -}}
+ {%- else %}
+ {{- hy_start_token ~ message['role'] ~ hy_middle_token -}}
+ {{- render_content(message['content']) -}}
+ {{- hy_end_token -}}
+ {%- endif %}
+ {%- if message['role'] != 'assistant' or not (message['tool_calls'] is defined and message['tool_calls']) %}
+ {%- set prev_ns.tool_call_ids = [] %}
+ {%- endif %}
+ {%- if loop.last and message['role'] == 'assistant' %}
+ {%- set last_ns.last_is_assistant = true %}
+ {%- endif %}
+{%- endfor %}
+{%- if add_generation_prompt %}
+ {%- if not last_ns.last_is_assistant %}
+ {%- if reasoning_effort == 'no_think' %}
+ {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token ~ think_end_token -}}
+ {%- else %}
+ {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token -}}
+ {%- endif %}
+ {%- endif %}
+{%- endif %}
diff --git a/tests/test_hy4_serve_core.py b/tests/test_hy4_serve_core.py
new file mode 100644
index 0000000..374c360
--- /dev/null
+++ b/tests/test_hy4_serve_core.py
@@ -0,0 +1,202 @@
+"""CPU tests of the Hy4 server helpers (tools/hy4/serve_core.py): request parsing, chat template, tokenizer special tokens, streaming output.
+Run: python -m unittest tests/test_hy4_serve_core.py (needs jinja2 + tokenizers; no GPU, no model)
+Optional ground-truth test against a real GGUF: set HY4_TEST_GGUF=<first shard> and HY4_TEST_ORACLE=<dir with p1_short_en/index.json + p1_short_en.txt>."""
+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"))
+import serve_core as C # noqa: E402
+
+with open(os.path.join(HERE, "data", "hy4_chat_template.jinja"), encoding="utf-8") as _f:
+ TEMPLATE = _f.read()
+TK = ":6124c78e"
+
+
+def _bytes_to_unicode():
+ bs = list(range(33, 127)) + list(range(161, 173)) + list(range(174, 256))
+ cs, n = bs[:], 0
+ for b in range(256):
+ if b not in bs:
+ bs.append(b)
+ cs.append(256 + n)
+ n += 1
+ return dict(zip(bs, map(chr, cs)))
+
+
+def tiny_meta():
+ """a byte-level vocabulary (no merges) + the Hy4 special tokens, enough to test the special-token handling and UTF-8 round trips"""
+ b2u = _bytes_to_unicode()
+ toks = [b2u[b] for b in range(256)]
+ types = [1] * 256
+ specials = [f"<|hy_start{TK}|>", f"<|hy_middle{TK}|>", f"<|hy_end{TK}|>", f"<think{TK}>", f"</think{TK}>", f"<|reasoning_mode{TK}|>"]
+ toks += specials
+ types += [3] * len(specials)
+ return {"tokenizer.ggml.tokens": toks, "tokenizer.ggml.merges": [], "tokenizer.ggml.token_type": types, "tokenizer.ggml.eos_token_id": 256 + 2,
+ "tokenizer.chat_template": TEMPLATE}
+
+
+class Core(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.v = C.Vocab(tiny_meta())
+ cls.ids = {t: i for i, t in enumerate(cls.v.tokens)}
+
+ # -- template
+ def test_template_default_effort_ends_in_open_think(self):
+ r = C.parse_chat({"messages": [{"role": "user", "content": "Bonjour"}]})
+ text = self.v.template.render(r["messages"], None, True, reasoning_effort=r["effort"])
+ self.assertEqual(r["effort"], "high")
+ self.assertTrue(text.startswith(f"<|hy_start{TK}|>system"))
+ self.assertIn(f"<|hy_start{TK}|>user<|hy_middle{TK}|>Bonjour<|hy_end{TK}|>", text)
+ self.assertTrue(text.endswith(f"<|hy_start{TK}|>assistant<|hy_middle{TK}|><think{TK}>"))
+
+ def test_template_no_think_closes_the_think_block(self):
+ r = C.parse_chat({"messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}], "reasoning_effort": "none"})
+ text = self.v.template.render(r["messages"], None, True, reasoning_effort=r["effort"])
+ self.assertEqual(r["effort"], "no_think")
+ self.assertIn("Be brief.", text)
+ self.assertTrue(text.endswith(f"<|hy_middle{TK}|><think{TK}></think{TK}>"))
+
+ def test_template_multi_turn_keeps_history(self):
+ msgs = [{"role": "user", "content": "a"}, {"role": "assistant", "content": "b"}, {"role": "user", "content": "c"}]
+ text = self.v.template.render(C.parse_chat({"messages": msgs, "reasoning_effort": "low"})["messages"], None, True, reasoning_effort="low")
+ self.assertLess(text.index(">a<"), text.index("b"))
+ self.assertLess(text.index("b"), text.rindex(">c<"))
+
+ def test_template_error_is_a_request_error(self):
+ with self.assertRaises(C.RequestError):
+ self.v.template.render([{"role": "user", "content": "x"}], None, True, reasoning_effort="bogus")
+
+ # -- parsing
+ def test_effort_names(self):
+ for given, want in (("medium", "high"), ("max", "max"), ("minimal", "low"), ("no_think", "no_think")):
+ self.assertEqual(C.parse_effort({"reasoning_effort": given}), want)
+ self.assertEqual(C.parse_effort({"chat_template_kwargs": {"reasoning_effort": "low"}}), "low")
+ self.assertEqual(C.parse_effort({"chat_template_kwargs": {"enable_thinking": False}}), "high") # no effort given: template default
+ with self.assertRaises(C.RequestError):
+ C.parse_effort({"reasoning_effort": "turbo"})
+
+ def test_chat_request_errors(self):
+ bad = [{}, {"messages": []}, {"messages": [{"role": "user", "content": "x"}], "n": 2},
+ {"messages": [{"role": "assistant", "content": "x"}]}, {"messages": [{"role": "robot", "content": "x"}]},
+ {"messages": [{"role": "user", "content": "x"}], "tools": [{"type": "function"}]},
+ {"messages": [{"role": "user", "content": "x"}], "max_tokens": 0},
+ {"messages": [{"role": "user", "content": "x"}], "stop": ["a"] * 9},
+ {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "x"}}]}]},
+ {"messages": [{"role": "user", "content": "x"}, {"role": "system", "content": "late"}]}]
+ for b in bad:
+ with self.assertRaises(C.RequestError, msg=str(b)):
+ C.parse_chat(b)
+
+ def test_chat_request_fields(self):
+ r = C.parse_chat({"messages": [{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]}], "max_completion_tokens": 7,
+ "stream": True, "stop": "END", "stream_options": {"include_usage": True}, "temperature": 0.7, "speculative": False}, 99)
+ self.assertEqual((r["max_tokens"], r["stream"], r["stop"], r["include_usage"], r["speculative"], r["sampling_ignored"]), (7, True, ["END"], True, False, True))
+ self.assertEqual(r["messages"][0]["content"], "ab")
+ self.assertEqual(C.parse_chat({"messages": [{"role": "user", "content": "x"}]}, 99)["max_tokens"], 99)
+
+ def test_completion_prompts(self):
+ self.assertEqual(C.parse_completion({"prompt": "hi"}, 100)["prompt"], "hi")
+ self.assertEqual(C.parse_completion({"prompt": [1, 2, 3]}, 100)["prompt_ids"], [1, 2, 3])
+ self.assertEqual(C.parse_completion({"prompt": [[1, 2]]}, 100)["prompt_ids"], [1, 2])
+ self.assertEqual(C.parse_completion({"prompt": ["hi"]}, 100)["prompt"], "hi")
+ for b in ({}, {"prompt": ""}, {"prompt": [1, 200]}, {"prompt": ["a", "b"]}, {"prompt": 5}):
+ with self.assertRaises(C.RequestError, msg=str(b)):
+ C.parse_completion(b, 100)
+
+ # -- tokenizer
+ def test_special_markers_are_single_ids(self):
+ text = self.v.template.render([{"role": "user", "content": "héllo 漢字 😀"}], None, True, reasoning_effort="high")
+ ids = self.v.encode(text)
+ self.assertEqual(ids[0], self.ids[f"<|hy_start{TK}|>"])
+ self.assertEqual(ids[-1], self.ids[f"<think{TK}>"])
+ self.assertEqual(ids.count(self.ids[f"<|hy_end{TK}|>"]), 2) # system turn + user turn
+ self.assertEqual(self.v.decode(ids), text)
+
+ def test_unicode_round_trip(self):
+ for s in ("ça va ?", "漢字かな", "emoji 😀🙂 end", "tab\tnewline\n spaces", "Straße"):
+ self.assertEqual(self.v.decode(self.v.encode(s)), s)
+
+ def test_think_markers_found_from_vocab(self):
+ self.assertEqual((self.v.think_begin, self.v.think_end, self.v.eos_id), (f"<think{TK}>", f"</think{TK}>", self.ids[f"<|hy_end{TK}|>"]))
+
+ # -- output side
+ def test_incremental_decoder_never_splits_a_character(self):
+ s = "a😀é漢b"
+ ids = self.v.encode(s)
+ d, parts = C.IncrementalDecoder(self.v), []
+ for t in ids:
+ parts.append(d.push([t]))
+ parts.append(d.flush())
+ self.assertNotIn("�", "".join(parts))
+ self.assertTrue(all(p == "" or p.encode("utf-8") for p in parts))
+ self.assertEqual("".join(parts), s)
+
+ def _run(self, text, in_think, stops=(), step=1, eos=False):
+ ids = self.v.encode(text) + ([self.v.eos_id] + self.v.encode("junk") if eos else [])
+ o = C.OutputStream(self.v, in_think=in_think, stops=list(stops))
+ got = []
+ for i in range(0, len(ids), step):
+ got += o.push(ids[i:i + step])
+ got += o.finish()
+ agg = {"reasoning": "", "content": ""}
+ for ch, tx in got:
+ agg[ch] += tx
+ return agg, o
+
+ def test_think_split_with_marker_across_rounds(self):
+ txt = f"let me think é</think{TK}>The answer."
+ for step in (1, 2, 3, 5, 100):
+ agg, o = self._run(txt, True, step=step)
+ self.assertEqual(agg, {"reasoning": "let me think é", "content": "The answer."}, step)
+ self.assertIsNone(o.finish_reason)
+
+ def test_no_think_is_all_content(self):
+ agg, _ = self._run("plain answer", False)
+ self.assertEqual(agg, {"reasoning": "", "content": "plain answer"})
+
+ def test_eos_stops_and_drops_the_rest(self):
+ agg, o = self._run("done.", False, step=2, eos=True)
+ self.assertEqual(agg["content"], "done.")
+ self.assertEqual(o.finish_reason, "stop")
+ self.assertEqual(o.n_tokens, len(self.v.encode("done.")))
+
+ def test_stop_string_cuts_and_holds_back_partial_matches(self):
+ for step in (1, 3, 50):
+ agg, o = self._run("one two STOP three", False, stops=["STOP"], step=step)
+ self.assertEqual(agg["content"], "one two ", step)
+ self.assertEqual(o.finish_reason, "stop")
+ agg, o = self._run("ends with ST", False, stops=["STOP"], step=1) # a held-back partial match is released at the end
+ self.assertEqual(agg["content"], "ends with ST")
+ self.assertIsNone(o.finish_reason)
+
+ def test_response_bodies(self):
+ b = C.chat_response("id", "m", 1, "hi", "why", "stop", {"total_tokens": 3})
+ self.assertEqual(b["choices"][0]["message"], {"role": "assistant", "content": "hi", "reasoning_content": "why"})
+ self.assertEqual(C.chat_chunk("id", "m", 1, {"content": "x"})["choices"][0]["delta"], {"content": "x"})
+ self.assertEqual(C.error_body("bad")["error"]["message"], "bad")
+
+
[email protected](os.environ.get("HY4_TEST_GGUF") and os.environ.get("HY4_TEST_ORACLE"), "set HY4_TEST_GGUF and HY4_TEST_ORACLE for the ground-truth test")
+class GroundTruth(unittest.TestCase):
+ def test_prompt_ids_match_the_reference_runtime(self):
+ tree = os.environ.get("HY4_TEST_TREE", os.path.dirname(HERE))
+ import types
+ for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n)
+ m.__path__ = [os.path.join(tree, "exllamav3", s)]
+ sys.modules[n] = m
+ from exllamav3.loader.gguf_collection import GGUFCollection
+ v = C.Vocab(GGUFCollection(os.environ["HY4_TEST_GGUF"]).meta)
+ d = os.environ["HY4_TEST_ORACLE"]
+ want = json.load(open(os.path.join(d, "p1_short_en", "index.json")))["prompt_ids"]
+ with open(os.path.join(d, "..", "prompts", "p1_short_en.txt"), encoding="utf-8") as f:
+ text = f.read()
+ self.assertEqual(v.encode(text.rstrip("\n")), want)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_hy4_serve_http.py b/tests/test_hy4_serve_http.py
new file mode 100644
index 0000000..c4d51b8
--- /dev/null
+++ b/tests/test_hy4_serve_http.py
@@ -0,0 +1,141 @@
+"""HTTP-level CPU test of tools/hy4/serve.py with a fake engine (no GPU, no model): routes, streaming, error bodies, queueing.
+Run: python -m unittest tests/test_hy4_serve_http.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
+
+
+class FakeEngine:
+ """replies with a fixed text, 3 tokens per round, like the speculative loop"""
+
+ def __init__(self, vocab, reply):
+ self.ids = vocab.encode(reply)
+ self.calls = []
+
+ def generate(self, ids, max_new, on_tokens, speculative=True, cancel=lambda: False):
+ self.calls.append((list(ids), max_new, speculative))
+ out, n = self.ids, 0
+ stop = on_tokens(out[:1])
+ n = 1
+ rounds = 0
+ while n < max_new and not stop and n < len(out):
+ new = out[n:n + 3][:max_new - n]
+ n += len(new)
+ rounds += 1
+ stop = on_tokens(new)
+ 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 - 1, "ttft_s": 0.5, "rounds": rounds, "accept_hist": [0, 0, 0, rounds], "tau": (n - 1) / max(rounds, 1), "speculative": speculative}
+
+
+def make_state(reply, ctx=4096):
+ args = argparse.Namespace(model_id="Hy4-test", max_ctx=ctx, num_draft=3, default_max_tokens=64)
+ st = S.State(args)
+ st.vocab = C.Vocab(tiny_meta())
+ st.engine = FakeEngine(st.vocab, reply)
+ st.ready = True
+ return st
+
+
[email protected](TestClient is None, "aiohttp not installed")
+class Http(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self):
+ self.st = make_state("Bonjour le monde")
+ self.st.lock = asyncio.Lock()
+ self.client = TestClient(TestServer(S.build_app(self.st)))
+ await self.client.start_server()
+
+ async def asyncTearDown(self):
+ await self.client.close()
+
+ async def test_health_models(self):
+ r = await self.client.get("/health")
+ self.assertEqual((r.status, (await r.json())["status"]), (200, "ok"))
+ self.st.ready = False
+ r = await self.client.get("/health")
+ self.assertEqual(r.status, 503)
+ self.st.ready = True
+ m = await (await self.client.get("/v1/models")).json()
+ self.assertEqual(m["data"][0]["id"], "Hy4-test")
+
+ async def test_chat_non_stream(self):
+ r = await self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "salut"}], "max_tokens": 50, "reasoning_effort": "no_think"})
+ j = await r.json()
+ self.assertEqual(r.status, 200, j)
+ self.assertEqual(j["choices"][0]["message"]["content"], "Bonjour le monde")
+ self.assertEqual(j["choices"][0]["finish_reason"], "length")
+ self.assertEqual(j["usage"]["completion_tokens"], len(self.st.engine.ids))
+ self.assertAlmostEqual(j["timings"]["prompt_per_second"], j["usage"]["prompt_tokens"] / 0.5)
+ ids = self.st.engine.calls[0][0]
+ self.assertEqual(ids[0], 256) # <|hy_start...|> is one id
+
+ async def test_chat_default_effort_splits_reasoning(self):
+ self.st.engine = FakeEngine(self.st.vocab, "pense</think:6124c78e>Reponse")
+ r = await self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "q"}], "max_tokens": 50})
+ j = await r.json()
+ self.assertEqual((j["choices"][0]["message"]["reasoning_content"], j["choices"][0]["message"]["content"]), ("pense", "Reponse"))
+
+ async def test_chat_stream(self):
+ r = await self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "q"}], "max_tokens": 50, "stream": True,
+ "reasoning_effort": "no_think", "stream_options": {"include_usage": True}})
+ self.assertEqual(r.status, 200)
+ raw = (await r.read()).decode()
+ events = [e[6:] for e in raw.split("\n\n") if e.startswith("data: ")]
+ self.assertEqual(events[-1], "[DONE]")
+ chunks = [json.loads(e) for e in events[:-1]]
+ self.assertEqual(chunks[0]["choices"][0]["delta"]["role"], "assistant")
+ text = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks if c["choices"])
+ self.assertEqual(text, "Bonjour le monde")
+ self.assertEqual([c["choices"][0]["finish_reason"] for c in chunks if c["choices"]][-1], "length")
+ self.assertIn("usage", chunks[-1])
+
+ async def test_completion_text_and_ids(self):
+ r = await self.client.post("/v1/completions", json={"prompt": "Il etait", "max_tokens": 4, "speculative": False})
+ j = await r.json()
+ self.assertEqual((r.status, j["choices"][0]["text"], j["choices"][0]["finish_reason"]), (200, "Bonj", "length"))
+ self.assertFalse(self.st.engine.calls[-1][2])
+ r = await self.client.post("/v1/completions", json={"prompt": [65, 66], "max_tokens": 2})
+ self.assertEqual(r.status, 200)
+ self.assertEqual(self.st.engine.calls[-1][0], [65, 66])
+
+ async def test_stop_string(self):
+ r = await self.client.post("/v1/completions", json={"prompt": "x", "max_tokens": 50, "stop": ["le"]})
+ j = await r.json()
+ self.assertEqual((j["choices"][0]["text"], j["choices"][0]["finish_reason"]), ("Bonjour ", "stop"))
+
+ 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)):
+ r = await self.client.post(path, json=body)
+ j = await r.json()
+ self.assertEqual(r.status, status, j)
+ self.assertIn("error", j)
+ r = await self.client.post("/v1/completions", data="not json")
+ self.assertEqual(r.status, 400)
+ self.st.ready = False
+ r = await self.client.post("/v1/completions", json={"prompt": "x"})
+ self.assertEqual(r.status, 503)
+
+ async def test_tokenize_and_template(self):
+ j = await (await self.client.post("/tokenize", json={"content": "ab"})).json()
+ self.assertEqual(j["tokens"], [97, 98])
+ j = await (await self.client.post("/apply-template", json={"messages": [{"role": "user", "content": "q"}], "reasoning_effort": "no_think"})).json()
+ self.assertTrue(j["prompt"].endswith("</think:6124c78e>"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/hy4/engine.py b/tools/hy4/engine.py
new file mode 100644
index 0000000..0d157a3
--- /dev/null
+++ b/tools/hy4/engine.py
@@ -0,0 +1,224 @@
+"""Hy4-flash resident engine for the served path: ONE model in memory, one request at a time.
+
+ prefill chunked (default 8192 rows) through the prefill fast path (fused dequant GEMM MoE / dense, banded fp16 MLA, GEMM indexer scores, Engram row
+ prefetch); the trunk states of every prompt row also fill the MTP draft head's cache in batches
+ decode HIP-graph trunk step + MTP draft chain graph + one T = k + 1 row verify graph per round (greedy speculative decoding: the stream equals
+ plain greedy decoding of the trunk) or, per request, the plain graph step
+
+The decode kernels (attn_eager, ref_fused, head_bf16, mla_bgemv, kv_fused, router_gemv) and the prefill kernels are two flag sets of the same
+modules: `phase("prefill")` switches the decode set off, `phase("decode")` restores it. Graphs are only ever captured in the decode phase.
+Every flag is read from the environment when the loader modules are imported: set the environment (serve.SHIPPED_ENV) BEFORE `Hy4Engine.load`.
+"""
+from __future__ import annotations
+
+import os
+import sys
+import time
+import types
+from typing import Callable
+
+CHUNK_DEFAULT = 8192
+PRIME_ROWS = 512 # rows per batched MTP draft-cache fill call
+
+
+def _stub_package(tree: str):
+ """import loader modules by path without importing the whole exllamav3 package (as the bench harnesses do)"""
+ for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n)
+ m.__path__ = [os.path.join(tree, "exllamav3", s)]
+ sys.modules[n] = m
+
+
+class Hy4Engine:
+ def __init__(self, tree: str, gguf: str, ctx: int = 16384, k: int = 3, chunk: int = CHUNK_DEFAULT, prime_rows: int = 0):
+ self.tree, self.gguf, self.k, self.chunk = tree, gguf, k, chunk
+ self.ctx = ctx
+ self.prime_rows = prime_rows # 0 = fill the draft cache for the whole prompt; N = the last N rows only (cheaper, lower acceptance)
+ self.ready = False
+ self.meta = None
+ self.last_stats: dict = {}
+
+ # ------------------------------------------------------------------------------------------ load
+ def load(self, progress: Callable[[str], None] = lambda s: None):
+ import torch
+ self.torch = torch
+ cap = int(os.environ.get("HY4_NOSYNC_CAP", "0"))
+ if cap < self.ctx + 64:
+ raise RuntimeError(f"HY4_NOSYNC_CAP={cap} must be set (before import) to at least ctx + 64 = {self.ctx + 64}")
+ _stub_package(self.tree)
+ from exllamav3.loader.gguf_collection import GGUFCollection
+ from exllamav3.loader import hy4_forward as hf
+ from exllamav3.loader import mla_hy4 as mh
+ from exllamav3.loader import step_graph as SG
+ from exllamav3.loader import mtp_head as MH
+ self.hf, self.mh, self.SG, self.MH = hf, mh, SG, MH
+ self._decode_flags()
+ self.phase("prefill") # the prefill kernels are selected at layer load time too (as in the prefill harness)
+ t0 = time.time()
+ progress("opening the GGUF")
+ g = GGUFCollection(self.gguf)
+ self.g, self.meta = g, g.meta
+ self.dev = torch.device("cuda")
+ progress("loading layers")
+ M = hf.Hy4Forward(g, device="cuda", cache_weights=True, hook=None)
+ for i in range(M.n_layers):
+ M._layer(i)
+ torch.cuda.synchronize()
+ self.M = M
+ progress("graph decoder + draft head")
+ self.GR = SG.GraphDecoder(M)
+ self.GR.prepare() # static K / indexer / Engram buffers at the full context size: addresses never change after this
+ self.MT = MH.Hy4MTP(M)
+ self.MG = MH.MTPGraph(self.MT, self.k)
+ torch.cuda.synchronize()
+ self.load_s = time.time() - t0
+ self.ready = True
+ progress(f"ready: {M.n_layers} layers, {M.stats.get('resident_gib')} GiB resident experts, {self.load_s:.0f} s")
+
+ def _decode_flags(self):
+ """remember the decode-set switches the environment selected at import"""
+ L = self.SG.__name__.rsplit(".", 1)[0]
+ import importlib
+ self._dec = []
+ for mod, attrs in (("attn_eager", ("ENABLED", "RMS")), ("ref_fused", ("ENABLED",)), ("head_bf16", ("ENABLED",)), ("mla_bgemv", ("ENABLED",)),
+ ("kv_fused", ("ENABLED",)), ("router_gemv", ("ENABLED",))):
+ m = importlib.import_module(f"{L}.{mod}")
+ for a in attrs:
+ self._dec.append((m, a, getattr(m, a)))
+
+ def phase(self, name: str):
+ """prefill: decode kernels off, prefill kernels on (the configuration the prefill numbers were measured in); decode: decode kernels restored"""
+ pre = name == "prefill"
+ for m, a, v in self._dec:
+ setattr(m, a, False if pre else v)
+ hf, mh = self.hf, self.mh
+ hf.PF_MOE = hf.PF_DENSE = hf.PF_IX = True
+ hf.PF_MOE_I8 = hf.PF_MOE_REF = hf.PF_DENSE_I8 = hf.PF_ROUTER = hf.PF_DIAG = False
+ mh.PF_ATTN, mh.PF_ATTN_FLASH = True, False # (rows <= 16 never take the prefill branches)
+
+ # ------------------------------------------------------------------------------------------ request state
+ def reset(self):
+ M, GR = self.M, self.GR
+ M.n, M.tokens, M._x, M._eng_pf = 0, [], None, {}
+ M.kc = [None] * M.n_layers
+ for ix in getattr(M, "ixf", {}).values():
+ ix.n, ix.P, ix.vg = 0, 0, None
+ for ix in M.ix.values():
+ ix.reset()
+ GR.reset() # zeroes the static K / indexer buffers in place (captured graphs keep their addresses)
+ self.MT.reset()
+
+ # ------------------------------------------------------------------------------------------ prefill
+ def prefill(self, ids: list[int]):
+ """-> (first token y, trunk state [1, D] of the last prompt row). Also fills the draft head's cache."""
+ torch, M = self.torch, self.M
+ n = len(ids)
+ self.phase("prefill")
+ M.prefetch_engram(ids, self.chunk)
+ states, lg = [], None
+ for s in range(0, n, self.chunk):
+ e = min(n, s + self.chunk)
+ lg = M.step(ids[s:e])
+ states.append(M.head_state(M._x))
+ M._x = None
+ torch.cuda.synchronize()
+ y = int(torch.argmax(lg))
+ H = torch.cat(states) if len(states) > 1 else states[0]
+ hcur = H[-1:].clone()
+ t = time.time()
+ self.last_stats["prefill_trunk_s"] = t - self._t0
+ self._prime_draft(ids, H)
+ torch.cuda.synchronize()
+ self.last_stats["prime_s"] = time.time() - t
+ return y, hcur
+
+ def _prime_draft(self, ids: list[int], H):
+ """draft head cache rows for the prompt: pair (token j+1, trunk state h_j) at head position j, for j = 0 .. n-2 (the batched form of what the
+ bench harness does one position at a time with MT.chain(.., k=1))"""
+ torch, MT = self.torch, self.MT
+ n = len(ids)
+ lo = 0 if self.prime_rows <= 0 else max(0, n - 1 - self.prime_rows)
+ tok = torch.tensor(ids, dtype=torch.long, device=self.dev)
+ ar = MT.ar
+ s = lo
+ try:
+ while s < n - 1:
+ e = min(n - 1, s + PRIME_ROWS)
+ MT.step(tok[s + 1:e + 1], H[s:e], ar[s:e], ((e + 3) // 4) * 4)
+ s = e
+ self.last_stats["prime_mode"] = "batched" if lo == 0 else f"batched tail {n - 1 - lo}"
+ except Exception as ex: # noqa: BLE001 - the draft only affects speed, never the output: fall back to the last 128 rows one by one
+ print(f"draft cache fill failed ({type(ex).__name__}: {ex}); falling back to a short per-row fill", flush=True)
+ torch.cuda.synchronize()
+ MT.reset()
+ for j in range(max(0, n - 129), n - 1):
+ MT.chain(tok[j + 1:j + 2], H[j:j + 1], j, 1)
+ self.last_stats["prime_mode"] = "per-row tail 128 (batched failed)"
+
+ # ------------------------------------------------------------------------------------------ generate
+ def generate(self, ids: list[int], max_new: int, on_tokens: Callable[[list[int]], bool], speculative: bool = True,
+ cancel: Callable[[], bool] = lambda: False) -> dict:
+ """Run one request. on_tokens(list of new token ids) is called once per prefill (first token) / decode round and returns True to stop
+ (EOS or a stop string seen by the caller). Returns the stats dict."""
+ if not self.ready:
+ raise RuntimeError("model not loaded")
+ n = len(ids)
+ if n + max_new + self.k + 2 > self.ctx:
+ raise ValueError("context")
+ torch, GR, MG = self.torch, self.GR, self.MG
+ st = self.last_stats = {"prompt_tokens": n, "speculative": speculative, "k": self.k}
+ self._t0 = t0 = time.perf_counter()
+ self.reset()
+ y, hcur = self.prefill(ids)
+ self.phase("decode")
+ t1 = time.perf_counter()
+ st["prefill_s"] = t1 - t0
+ out_n, rounds, hist = 0, 0, [0] * (self.k + 1)
+ stop = False
+ # first token: it comes from the prefill logits
+ stop = on_tokens([y])
+ out_n = 1
+ st["ttft_s"] = time.perf_counter() - t0
+ tdec = time.perf_counter()
+ if speculative:
+ k = self.k
+ pc = time.perf_counter
+ tm = [0.0, 0.0, 0.0]
+ while out_n < max_new and not stop and not cancel():
+ j = GR.fw.n - 1
+ ta = pc()
+ d = MG.run(y, hcur, j).tolist()
+ tb = pc()
+ toks = [y] + d
+ _lg, amv, _x, hv = GR.step_rows(toks)
+ tc = pc()
+ amh = amv.tolist()
+ td = pc()
+ tm[0] += tb - ta
+ tm[1] += tc - tb
+ tm[2] += td - tc
+ acc = 0
+ while acc < k and d[acc] == amh[acc]:
+ acc += 1
+ new = toks[1:acc + 1] + [amh[acc]] # toks[0] = y was already emitted; the verified drafts + the trunk's own next token
+ GR.rewind(j + 2 + acc)
+ y, hcur = amh[acc], hv[acc:acc + 1]
+ hist[acc] += 1
+ rounds += 1
+ room = max_new - out_n
+ if len(new) > room:
+ new = new[:room]
+ out_n += len(new)
+ stop = on_tokens(new)
+ st["round_ms"] = [x / max(rounds, 1) * 1000 for x in tm]
+ else:
+ while out_n < max_new and not stop and not cancel():
+ lg = GR.step(y)
+ y = int(torch.argmax(lg))
+ out_n += 1
+ stop = on_tokens([y])
+ torch.cuda.synchronize()
+ t2 = time.perf_counter()
+ st.update(decode_s=t2 - tdec, decode_tokens=out_n - 1, total_s=t2 - t0, rounds=rounds, accept_hist=hist,
+ tau=(out_n - 1) / rounds if rounds else None, generated=out_n, cancelled=bool(cancel()))
+ return st
diff --git a/tools/hy4/hy4_pretokenizer.json b/tools/hy4/hy4_pretokenizer.json
new file mode 100644
index 0000000..b7e8e69
--- /dev/null
+++ b/tools/hy4/hy4_pretokenizer.json
@@ -0,0 +1,50 @@
+{
+ "pre_tokenizer": {
+ "type": "Sequence",
+ "pretokenizers": [
+ {
+ "type": "Split",
+ "pattern": {
+ "Regex": "\\p{N}{1,3}"
+ },
+ "behavior": "Isolated",
+ "invert": false
+ },
+ {
+ "type": "Split",
+ "pattern": {
+ "Regex": "[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+"
+ },
+ "behavior": "Isolated",
+ "invert": false
+ },
+ {
+ "type": "Split",
+ "pattern": {
+ "Regex": "[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\r\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| ?[\\p{P}\\p{S}]+[\r\n]*|\\s*[\r\n]+|\\s+(?!\\S)|\\s+"
+ },
+ "behavior": "Isolated",
+ "invert": false
+ },
+ {
+ "type": "ByteLevel",
+ "add_prefix_space": false,
+ "trim_offsets": true,
+ "use_regex": false
+ }
+ ]
+ },
+ "decoder": {
+ "type": "ByteLevel",
+ "add_prefix_space": true,
+ "trim_offsets": true,
+ "use_regex": true
+ },
+ "post_processor": {
+ "type": "ByteLevel",
+ "add_prefix_space": true,
+ "trim_offsets": false,
+ "use_regex": true
+ },
+ "normalizer": null
+}
diff --git a/tools/hy4/serve.py b/tools/hy4/serve.py
new file mode 100644
index 0000000..2d05c03
--- /dev/null
+++ b/tools/hy4/serve.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+"""OpenAI-compatible server for Hy4-flash (GGUF Q3_K) on one resident model: /v1/chat/completions, /v1/completions (both with SSE streaming),
+/v1/models, /health, /tokenize, /apply-template.
+
+ python tools/hy4/serve.py --model /path/Hy4-flash-Q3_K-00001-of-00002.gguf --port 8300 [-c 16384] [--num-draft 3]
+
+Prefill runs the prefill fast path; decode runs the HIP-graph step with MTP speculative decoding (greedy; the stream equals plain greedy decoding of the
+trunk). Sampling parameters are accepted and ignored. One request is served at a time (one resident model); others queue.
+The shipped kernel flag set is SHIPPED_ENV below; every entry can be overridden from the environment. Run it inside the strix env wrapper
+(tools/strix_halo/env.sh) and a GPU lock / memory cap of your choice: the server takes neither.
+"""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import sys
+import threading
+import time
+import traceback
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+TREE = os.path.dirname(os.path.dirname(HERE))
+sys.path.insert(0, HERE)
+sys.path.insert(0, os.path.dirname(HERE))
+
+import serve_core as C # noqa: E402
+import serve_compat # noqa: E402
+
+# The flag set of the measured Hy4 decode (graph + MTP draft fast path + MoE expert-major order) and prefill (fused dequant GEMMs, banded fp16 MLA) numbers.
+SHIPPED_ENV = {
+ "HY4_HEAD_CPU": "0", "HY4_EXPERT_RESIDENT_GB": "72", "HY4_ENGRAM_GPU": "1", "HY4_ATTN_GROUPED": "1", "HY4_INDEXER_FUSED": "1",
+ "HY4_NOSYNC": "1", # static-buffer step (needed by the graph)
+ "HY4_HC_FUSED": "1", "HY4_HEAD_BF16": "1", "HY4_MLA_BG": "1", "HY4_ATTN_EAGER": "2", "HY4_KV_FUSED": "1",
+ "HY4_REF_FUSED": "1", "HY4_REF_ROUTER": "1", "HY4_REF_MLA": "1", "HY4_ROUTER_GEMV": "1", "HY4_MOE_SORT": "1", # decode set
+ "HY4_MTP_FAST": "1", "HY4_MTP_HEAD": "q8", # draft head
+ "HY4_PREFILL_MOE": "1", "HY4_PREFILL_DENSE": "1", "HY4_PREFILL_ATTN": "1", "HY4_PREFILL_IX": "1", "HY4_ENGRAM_PREFETCH": "1",
+ "HY4_PF_F16": "1", "HY4_MOE_NFIRST": "1", "KEEPCACHE": "1", # prefill set
+}
+
+
+def apply_env(ctx: int) -> None:
+ for k, v in SHIPPED_ENV.items():
+ os.environ.setdefault(k, v)
+ os.environ.setdefault("HY4_NOSYNC_CAP", str(((ctx + 64 + 511) // 512) * 512)) # K buffers / token history: fixed for the life of the process
+
+
+class State:
+ def __init__(self, args):
+ self.args = args
+ self.engine = None
+ self.vocab = None
+ self.ready = False
+ self.error: str | None = None
+ self.stage = "starting"
+ self.lock: asyncio.Lock | None = None
+ self.served = 0
+
+
+def _err(status: int, message: str, code: str = "invalid_request_error"):
+ from aiohttp import web
+ return web.json_response(C.error_body(message, code), status=status)
+
+
+def build_app(st: State):
+ from aiohttp import web
+ args = st.args
+
+ async def health(_req):
+ if st.error:
+ return web.json_response({"status": "error", "error": st.error}, status=500)
+ if not st.ready:
+ return web.json_response({"status": "loading", "stage": st.stage}, status=503)
+ return web.json_response({"status": "ok"})
+
+ async def models(_req):
+ return web.json_response({"object": "list", "data": [{"id": args.model_id, "object": "model", "created": int(time.time()), "owned_by": "kyojin",
+ "max_model_len": args.max_ctx}]})
+
+ def need_ready():
+ if not st.ready:
+ raise C.RequestError("model is loading" if not st.error else st.error, 503, "unavailable")
+
+ async def read_body(req):
+ try:
+ return await req.json()
+ except Exception:
+ raise C.RequestError("the body is not valid JSON")
+
+ def prompt_for_chat(body):
+ r = C.parse_chat(body, args.default_max_tokens)
+ text = st.vocab.template.render(r["messages"], None, True, reasoning_effort=r["effort"])
+ ids = st.vocab.encode(text)
+ v = st.vocab
+ r["in_think"] = 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")
+
+ async def run_job(ids, r, in_think, request):
+ """async generator of ("delta", channel, text) events, then ("end", stats, finish_reason, n_generated)"""
+ loop = asyncio.get_running_loop()
+ q: asyncio.Queue = asyncio.Queue()
+ out = C.OutputStream(st.vocab, in_think=in_think, stops=r["stop"])
+ cancel = threading.Event()
+ res: dict = {}
+
+ def on_tokens(toks):
+ for ch, tx in out.push(toks):
+ loop.call_soon_threadsafe(q.put_nowait, ("delta", ch, tx))
+ return out.done
+
+ def work():
+ try:
+ res["stats"] = st.engine.generate(ids, r["max_tokens"], on_tokens, speculative=r["speculative"], cancel=cancel.is_set)
+ except Exception as e: # noqa: BLE001
+ traceback.print_exc()
+ res["error"] = f"{type(e).__name__}: {e}"
+ finally:
+ for ch, tx in out.finish():
+ loop.call_soon_threadsafe(q.put_nowait, ("delta", ch, tx))
+ loop.call_soon_threadsafe(q.put_nowait, ("end",))
+
+ async with st.lock:
+ fut = loop.run_in_executor(None, work)
+ try:
+ while True:
+ ev = await q.get()
+ if ev[0] == "end":
+ break
+ yield ev
+ finally:
+ cancel.set()
+ await fut
+ if "error" in res:
+ raise RuntimeError(res["error"])
+ stats = res["stats"]
+ finish = out.finish_reason or "length"
+ st.served += 1
+ n_gen = out.n_tokens
+ pf, dc = stats["prefill_s"], stats["decode_s"]
+ print(f"req {st.served}: prompt {stats['prompt_tokens']} tok prefill {pf:.2f} s ({stats['prompt_tokens'] / pf:.0f} tok/s; trunk {stats.get('prefill_trunk_s', 0):.2f} s, "
+ f"draft fill {stats.get('prime_s', 0):.2f} s {stats.get('prime_mode')}) | decode {stats['decode_tokens']} tok {dc:.2f} s = "
+ f"{stats['decode_tokens'] / dc if dc else 0:.2f} tok/s spec={stats['speculative']} rounds {stats['rounds']} tau {stats['tau']} hist {stats['accept_hist']} | {finish}",
+ flush=True)
+ yield ("end", stats, finish, n_gen)
+
+ def timings(stats):
+ n, dec_n = stats["prompt_tokens"], stats["decode_tokens"]
+ return serve_compat.timings(n, 0, stats["prefill_s"], stats["decode_s"], dec_n, speculative=stats["speculative"], rounds=stats["rounds"],
+ tau=stats["tau"], accept_hist=stats["accept_hist"], ttft_ms=stats["ttft_s"] * 1000,
+ prefill_trunk_ms=stats.get("prefill_trunk_s", 0) * 1000, draft_fill_ms=stats.get("prime_s", 0) * 1000)
+
+ async def sse(request, gen_chunks):
+ resp = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})
+ await resp.prepare(request)
+ async for chunk in gen_chunks:
+ await resp.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n")
+ await resp.write(b"data: [DONE]\n\n")
+ return resp
+
+ async def chat(request):
+ try:
+ need_ready()
+ r, ids = prompt_for_chat(await read_body(request))
+ check_len(len(ids), r["max_tokens"])
+ rid, created = C.new_id("chatcmpl"), int(time.time())
+ m = args.model_id
+ if not r["stream"]:
+ content, reasoning, stats, finish, n_gen = [], [], None, "length", 0
+ async for ev in run_job(ids, r, r["in_think"], request):
+ if ev[0] == "delta":
+ (reasoning if ev[1] == "reasoning" else content).append(ev[2])
+ else:
+ _, stats, finish, n_gen = ev
+ return web.json_response(C.chat_response(rid, m, created, "".join(content), "".join(reasoning), finish,
+ serve_compat.usage(len(ids), n_gen), timings=timings(stats), system_fingerprint="hy4-strix-graph-mtp"))
+
+ async def chunks():
+ yield C.chat_chunk(rid, m, created, {"role": "assistant", "content": ""})
+ async for ev in run_job(ids, r, r["in_think"], request):
+ if ev[0] == "delta":
+ yield C.chat_chunk(rid, m, created, {"reasoning_content" if ev[1] == "reasoning" else "content": ev[2]})
+ else:
+ _, stats, finish, n_gen = ev
+ yield C.chat_chunk(rid, m, created, {}, finish, timings=timings(stats))
+ if r["include_usage"]:
+ yield {"id": rid, "object": "chat.completion.chunk", "created": created, "model": m, "choices": [],
+ "usage": serve_compat.usage(len(ids), n_gen)}
+ return await sse(request, chunks())
+ except C.RequestError as e:
+ return _err(e.status, str(e), e.code)
+ except RuntimeError as e:
+ return _err(500, str(e), "server_error")
+
+ async def completions(request):
+ try:
+ 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"])
+ rid, created, m = C.new_id("cmpl"), int(time.time()), args.model_id
+ if not r["stream"]:
+ text, stats, finish, n_gen = [], None, "length", 0
+ async for ev in run_job(ids, r, False, request):
+ if ev[0] == "delta":
+ text.append(ev[2])
+ else:
+ _, stats, finish, n_gen = ev
+ body = C.completion_chunk(rid, m, created, "".join(text), finish)
+ body.update(usage=serve_compat.usage(len(ids), n_gen), timings=timings(stats))
+ return web.json_response(body)
+
+ async def chunks():
+ async for ev in run_job(ids, r, False, request):
+ if ev[0] == "delta":
+ yield C.completion_chunk(rid, m, created, ev[2])
+ else:
+ _, stats, finish, n_gen = ev
+ yield C.completion_chunk(rid, m, created, "", finish, timings=timings(stats))
+ if r["include_usage"]:
+ yield {"id": rid, "object": "text_completion", "created": created, "model": m, "choices": [], "usage": serve_compat.usage(len(ids), n_gen)}
+ return await sse(request, chunks())
+ except C.RequestError as e:
+ return _err(e.status, str(e), e.code)
+ except RuntimeError as e:
+ return _err(500, str(e), "server_error")
+
+ async def tokenize(request):
+ try:
+ need_ready()
+ body = await read_body(request)
+ if "messages" in body:
+ _, ids = prompt_for_chat(body)
+ else:
+ ids = st.vocab.encode(str(body.get("content", body.get("prompt", ""))))
+ return web.json_response(serve_compat.tokenize_reply(ids, args.max_ctx))
+ except C.RequestError as e:
+ return _err(e.status, str(e), e.code)
+
+ async def apply_template(request):
+ try:
+ need_ready()
+ r = C.parse_chat(await read_body(request), args.default_max_tokens)
+ return web.json_response({"prompt": st.vocab.template.render(r["messages"], None, True, reasoning_effort=r["effort"])})
+ except C.RequestError as e:
+ return _err(e.status, str(e), e.code)
+
+ app = web.Application(client_max_size=64 * 1024 * 1024)
+ app.router.add_get("/health", health)
+ app.router.add_get("/v1/models", models)
+ app.router.add_post("/v1/chat/completions", chat)
+ app.router.add_post("/v1/completions", completions)
+ app.router.add_post("/tokenize", tokenize)
+ app.router.add_post("/apply-template", apply_template)
+ return app
+
+
+def load_in_background(st: State):
+ def work():
+ try:
+ from engine import Hy4Engine
+ a = st.args
+ eng = Hy4Engine(TREE, a.model, ctx=a.max_ctx, k=a.num_draft, chunk=a.prefill_chunk, prime_rows=a.draft_fill_rows)
+
+ def progress(s):
+ st.stage = s
+ print("load:", s, flush=True)
+ eng.load(progress)
+ st.stage = "tokenizer"
+ st.vocab = C.Vocab(eng.meta)
+ st.engine = eng
+ st.ready = True
+ print(f"ready on {a.host}:{a.port} model-id {a.model_id} ctx {a.max_ctx} k={a.num_draft}", flush=True)
+ except Exception as e: # noqa: BLE001
+ traceback.print_exc()
+ st.error = f"{type(e).__name__}: {e}"
+ threading.Thread(target=work, name="hy4-load", daemon=True).start()
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("--model", required=True, help="first shard of the Hy4-flash GGUF")
+ ap.add_argument("--model-id", default="Hy4-flash")
+ ap.add_argument("--host", default="127.0.0.1")
+ ap.add_argument("--port", type=int, default=8300)
+ ap.add_argument("-c", "--max-ctx", type=int, default=16384, help="context window: static buffers are sized for it (K rows 0.1 MB per position)")
+ 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)
+ args = ap.parse_args(argv)
+ apply_env(args.max_ctx)
+ st = State(args)
+ app = build_app(st)
+
+ async def on_start(_app):
+ st.lock = asyncio.Lock()
+ load_in_background(st)
+ app.on_startup.append(on_start)
+ from aiohttp import web
+ web.run_app(app, host=args.host, port=args.port, print=None, access_log=None)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/hy4/serve_core.py b/tools/hy4/serve_core.py
new file mode 100644
index 0000000..4dd4ee6
--- /dev/null
+++ b/tools/hy4/serve_core.py
@@ -0,0 +1,354 @@
+"""Pure-Python helpers of the Hy4 OpenAI-compatible server (no torch, no engine import: unit-testable on any machine).
+
+ * request parsing for POST /v1/chat/completions and /v1/completions (RequestError = HTTP 400)
+ * the chat template: the Jinja source stored in the GGUF (tokenizer.chat_template), rendered like the reference runtimes do
+ * the tokenizer, rebuilt from the GGUF vocabulary + merges (special tokens spelled exactly as in the GGUF)
+ * the output side: incremental detokenisation (UTF-8 safe), stop strings, EOS, reasoning / content split
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import time
+import uuid
+from typing import Any, Iterable
+
+import jinja2
+from jinja2.ext import loopcontrols
+from jinja2.sandbox import ImmutableSandboxedEnvironment
+
+PRETOK_JSON = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hy4_pretokenizer.json")
+
+# OpenAI-style effort names -> the values the template accepts (max / high / low / no_think)
+EFFORT_MAP = {"max": "max", "xhigh": "max", "high": "high", "medium": "high", "low": "low", "minimal": "low",
+ "no_think": "no_think", "none": "no_think", "off": "no_think"}
+DEFAULT_EFFORT = "high"
+
+
+class RequestError(ValueError):
+ """The request is malformed or cannot be served: the server answers `status` with an OpenAI error body."""
+
+ def __init__(self, message: str, status: int = 400, code: str = "invalid_request_error"):
+ super().__init__(message)
+ self.status, self.code = status, code
+
+
+# ------------------------------------------------------------------------------------------------ chat template
+def _tojson(value: Any, ensure_ascii: bool = True, indent: int | None = None, sort_keys: bool = False, separators=None) -> str:
+ return json.dumps(value, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys, separators=separators)
+
+
+def _raise_exception(message: str):
+ raise jinja2.exceptions.TemplateError(message)
+
+
+class ChatTemplate:
+ """The GGUF chat template. Same environment as the reference runtimes: sandboxed, trim_blocks + lstrip_blocks, a tojson that takes
+ ensure_ascii, raise_exception, loop controls."""
+
+ def __init__(self, source: str):
+ env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=[loopcontrols])
+ env.filters["tojson"] = _tojson
+ env.globals["raise_exception"] = _raise_exception
+ env.globals["strftime_now"] = lambda fmt: time.strftime(fmt)
+ self.source = source
+ self.tpl = env.from_string(source)
+
+ def render(self, messages: list[dict], tools: list | None = None, add_generation_prompt: bool = True, **kwargs: Any) -> str:
+ try:
+ return self.tpl.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs)
+ except jinja2.exceptions.TemplateError as e:
+ raise RequestError(f"chat template: {e}") from e
+
+
+# ------------------------------------------------------------------------------------------------ tokenizer
+def build_tokenizer(tokens: list[str], merges: list[str], token_types: list[int], pretok_path: str = PRETOK_JSON):
+ """tokenizers.Tokenizer for the byte-level BPE of the GGUF (tokenizer.ggml.model = gpt2, pre = hy_v4). Normal tokens (type 1) and merges come from the
+ GGUF; every other token (control / user-defined) is registered as a special token under its GGUF spelling, so the template's
+ `<|hy_start:...|>` markers encode to ONE id. The pre-tokenizer regexes are not stored in a GGUF: they come from hy4_pretokenizer.json."""
+ from tokenizers import Tokenizer
+ with open(pretok_path, encoding="utf-8") as f:
+ extra = json.load(f)
+ vocab = {t: i for i, t in enumerate(tokens) if token_types[i] == 1}
+ spec = [{"id": i, "content": t, "single_word": False, "lstrip": False, "rstrip": False, "normalized": False, "special": True}
+ for i, t in enumerate(tokens) if token_types[i] != 1]
+ doc = {"version": "1.0", "truncation": None, "padding": None, "added_tokens": spec, "normalizer": extra["normalizer"],
+ "pre_tokenizer": extra["pre_tokenizer"], "post_processor": extra["post_processor"], "decoder": extra["decoder"],
+ "model": {"type": "BPE", "dropout": None, "unk_token": None, "continuing_subword_prefix": None, "end_of_word_suffix": None,
+ "fuse_unk": False, "byte_fallback": False, "ignore_merges": False, "vocab": vocab,
+ "merges": [m if isinstance(m, str) else " ".join(m) for m in merges]}}
+ return Tokenizer.from_str(json.dumps(doc))
+
+
+class Vocab:
+ """tokenizer + the ids / markers the server needs, all derived from the GGUF metadata dict."""
+
+ def __init__(self, meta: dict, pretok_path: str = PRETOK_JSON):
+ toks = list(meta["tokenizer.ggml.tokens"])
+ self.tokens = toks
+ self.tok = build_tokenizer(toks, list(meta["tokenizer.ggml.merges"]), list(meta["tokenizer.ggml.token_type"]), pretok_path)
+ self.size = len(toks)
+ self.eos_id = int(meta["tokenizer.ggml.eos_token_id"])
+ self.eos_ids = {self.eos_id}
+ self.template = ChatTemplate(meta["tokenizer.chat_template"])
+ self.think_begin = next((t for t in toks if t.startswith("<think")), None)
+ self.think_end = next((t for t in toks if t.startswith("</think")), None)
+
+ def encode(self, text: str) -> list[int]:
+ return self.tok.encode(text, add_special_tokens=False).ids
+
+ def decode(self, ids: list[int]) -> str:
+ return self.tok.decode(ids, skip_special_tokens=False)
+
+
+# ------------------------------------------------------------------------------------------------ request parsing
+def _as_int(body: dict, key: str, default: int | None, lo: int = 0) -> int | None:
+ v = body.get(key, default)
+ if v is None:
+ return default
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or int(v) != v or int(v) < lo:
+ raise RequestError(f"{key} must be an integer >= {lo}")
+ return int(v)
+
+
+def _stops(body: dict) -> list[str]:
+ s = body.get("stop")
+ if s is None:
+ return []
+ if isinstance(s, str):
+ s = [s]
+ if not isinstance(s, list) or len(s) > 8 or not all(isinstance(x, str) and x for x in s):
+ raise RequestError("stop must be a non-empty string or a list of at most 8 non-empty strings")
+ return list(s)
+
+
+def _common(body: dict, default_max: int) -> dict:
+ if not isinstance(body, dict):
+ raise RequestError("the body must be a JSON object")
+ if _as_int(body, "n", 1, 1) != 1:
+ raise RequestError("n must be 1")
+ mt = body.get("max_completion_tokens", body.get("max_tokens"))
+ max_tokens = default_max 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))):
+ raise RequestError(f"{k} must be a number")
+ return {"max_tokens": max_tokens, "stream": bool(body.get("stream", False)), "stop": _stops(body),
+ "include_usage": bool((body.get("stream_options") or {}).get("include_usage", False)),
+ # the speculative decoder is greedy: sampling parameters are accepted and ignored; reported back in the reply
+ "sampling_ignored": body.get("temperature") not in (None, 0, 0.0),
+ "speculative": body.get("speculative", True) is not False}
+
+
+def parse_effort(body: dict) -> str:
+ kw = body.get("chat_template_kwargs") or {}
+ if not isinstance(kw, dict):
+ raise RequestError("chat_template_kwargs must be an object")
+ v = kw.get("reasoning_effort", body.get("reasoning_effort"))
+ if v is None:
+ return DEFAULT_EFFORT
+ if kw.get("enable_thinking") is False and "reasoning_effort" not in kw and body.get("reasoning_effort") is None:
+ return "no_think"
+ if not isinstance(v, str) or v not in EFFORT_MAP:
+ raise RequestError(f"reasoning_effort must be one of {sorted(EFFORT_MAP)}")
+ return EFFORT_MAP[v]
+
+
+def _content_text(c: Any) -> str:
+ """OpenAI content (string, or a list of {type: text} parts) -> text"""
+ if c is None:
+ return ""
+ if isinstance(c, str):
+ return c
+ if isinstance(c, list):
+ out = []
+ for p in c:
+ if isinstance(p, str):
+ out.append(p)
+ elif isinstance(p, dict) and p.get("type") == "text" and isinstance(p.get("text"), str):
+ out.append(p["text"])
+ else:
+ raise RequestError("only text content parts are supported (no images / audio)")
+ return "".join(out)
+ raise RequestError("message content must be a string or a list of text parts")
+
+
+def parse_chat(body: dict, default_max: int = 1024) -> dict:
+ """-> {messages, effort, max_tokens, stream, stop, include_usage, speculative, ...}. Raises RequestError."""
+ req = _common(body, default_max)
+ if body.get("tools") or body.get("functions") or body.get("tool_choice") not in (None, "none"):
+ raise RequestError("tool calling is not supported by this backend yet")
+ msgs = body.get("messages")
+ if not isinstance(msgs, list) or not msgs:
+ raise RequestError("messages must be a non-empty list")
+ out = []
+ for i, m in enumerate(msgs):
+ if not isinstance(m, dict) or m.get("role") not in ("system", "developer", "user", "assistant"):
+ raise RequestError(f"messages[{i}]: role must be system, user or assistant")
+ role = "system" if m["role"] == "developer" else m["role"]
+ if role == "system" and i != 0:
+ raise RequestError(f"messages[{i}]: a system message is only allowed first")
+ item = {"role": role, "content": _content_text(m.get("content"))}
+ rc = m.get("reasoning_content", m.get("reasoning"))
+ if role == "assistant" and isinstance(rc, str) and rc:
+ item["reasoning_content"] = rc
+ out.append(item)
+ if out[-1]["role"] == "assistant":
+ raise RequestError("the last message must come from the user")
+ req.update(messages=out, effort=parse_effort(body))
+ return req
+
+
+def parse_completion(body: dict, vocab_size: int | None, default_max: int = 256) -> dict:
+ """-> {prompt: str | None, prompt_ids: list[int] | None, ...}"""
+ req = _common(body, default_max)
+ p = body.get("prompt")
+ if isinstance(p, list) and len(p) == 1 and isinstance(p[0], (str, list)):
+ p = p[0]
+ if isinstance(p, str):
+ req.update(prompt=p, prompt_ids=None)
+ elif isinstance(p, list) and p and all(isinstance(x, int) and not isinstance(x, bool) for x in p):
+ for x in p:
+ if x < 0 or (vocab_size is not None and x >= vocab_size):
+ raise RequestError(f"prompt token id {x} is outside the vocabulary")
+ req.update(prompt=None, prompt_ids=list(p))
+ else:
+ raise RequestError("prompt must be a string or a list of token ids (one prompt per request)")
+ if req["prompt"] == "":
+ raise RequestError("prompt is empty")
+ return req
+
+
+# ------------------------------------------------------------------------------------------------ output side
+class IncrementalDecoder:
+ """token ids -> text deltas that never end in half a UTF-8 character (the standard prefix / read offset scheme)."""
+
+ def __init__(self, vocab: Vocab):
+ self.v, self.ids, self.prefix, self.read = vocab, [], 0, 0
+
+ def push(self, ids: Iterable[int]) -> str:
+ self.ids.extend(ids)
+ old = self.v.decode(self.ids[self.prefix:self.read])
+ new = self.v.decode(self.ids[self.prefix:])
+ if len(new) > len(old) and not new.endswith("�"):
+ self.prefix, self.read = self.read, len(self.ids)
+ return new[len(old):]
+ return ""
+
+ def flush(self) -> str:
+ old = self.v.decode(self.ids[self.prefix:self.read])
+ new = self.v.decode(self.ids[self.prefix:])
+ self.prefix = self.read = len(self.ids)
+ return new[len(old):] if len(new) > len(old) else ""
+
+
+def _hold(text: str, markers: list[str]) -> int:
+ """length of the longest suffix of `text` that is a proper prefix of one of the markers (must wait for more text)"""
+ best = 0
+ for m in markers:
+ for n in range(min(len(m) - 1, len(text)), best, -1):
+ if text.endswith(m[:n]):
+ best = n
+ break
+ return best
+
+
+class OutputStream:
+ """Per request: token ids in, (channel, text) deltas out, channel = "reasoning" | "content".
+ in_think: the prompt ended inside an open think block, so the text starts as reasoning until `think_end`.
+ Stops on an EOS id (dropped) or a stop string (cut; only searched in the content channel)."""
+
+ def __init__(self, vocab: Vocab, in_think: bool = False, stops: list[str] | None = None):
+ self.v = vocab
+ self.dec = IncrementalDecoder(vocab)
+ self.in_think = bool(in_think and vocab.think_end)
+ self.stops = stops or []
+ self.buf = ""
+ self.done = False
+ self.finish_reason: str | None = None
+ self.n_tokens = 0 # generated tokens counted (EOS and anything after it excluded)
+
+ def _drain(self, final: bool) -> list[tuple[str, str]]:
+ out: list[tuple[str, str]] = []
+ while True:
+ if self.in_think:
+ i = self.buf.find(self.v.think_end)
+ if i >= 0:
+ if i:
+ out.append(("reasoning", self.buf[:i]))
+ self.buf = self.buf[i + len(self.v.think_end):]
+ self.in_think = False
+ continue
+ k = 0 if final else _hold(self.buf, [self.v.think_end])
+ if len(self.buf) > k:
+ out.append(("reasoning", self.buf[:len(self.buf) - k]))
+ self.buf = self.buf[len(self.buf) - k:]
+ break
+ cut = min((j for j in (self.buf.find(s) for s in self.stops) if j >= 0), default=-1)
+ if cut >= 0:
+ if cut:
+ out.append(("content", self.buf[:cut]))
+ self.buf, self.done, self.finish_reason = "", True, "stop"
+ break
+ k = 0 if final else _hold(self.buf, self.stops)
+ if len(self.buf) > k:
+ out.append(("content", self.buf[:len(self.buf) - k]))
+ self.buf = self.buf[len(self.buf) - k:]
+ break
+ return out
+
+ def push(self, ids: list[int]) -> list[tuple[str, str]]:
+ """feed the tokens of one decode round; returns the deltas that are safe to send. `done` turns True on EOS or a stop string."""
+ if self.done:
+ return []
+ take, eos = [], False
+ for t in ids:
+ if t in self.v.eos_ids:
+ eos = True
+ break
+ take.append(t)
+ self.n_tokens += len(take)
+ self.buf += self.dec.push(take)
+ if eos:
+ self.buf += self.dec.flush()
+ out = self._drain(final=eos)
+ if eos:
+ self.done, self.finish_reason = True, "stop"
+ return out
+
+ def finish(self) -> list[tuple[str, str]]:
+ """flush at the end of the stream when it ended on the length limit (nothing is left after EOS or a stop string)"""
+ if self.done:
+ return []
+ self.buf += self.dec.flush()
+ out = self._drain(final=True)
+ self.buf = ""
+ return out
+
+
+# ------------------------------------------------------------------------------------------------ response bodies
+def new_id(prefix: str) -> str:
+ return f"{prefix}-{uuid.uuid4().hex[:24]}"
+
+
+def chat_chunk(rid: str, model: str, created: int, delta: dict, finish: str | None = None, **extra: Any) -> dict:
+ return {"id": rid, "object": "chat.completion.chunk", "created": created, "model": model,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], **extra}
+
+
+def chat_response(rid: str, model: str, created: int, content: str, reasoning: str, finish: str, usage: dict, **extra: Any) -> dict:
+ msg: dict[str, Any] = {"role": "assistant", "content": content}
+ if reasoning:
+ msg["reasoning_content"] = reasoning
+ return {"id": rid, "object": "chat.completion", "created": created, "model": model,
+ "choices": [{"index": 0, "message": msg, "finish_reason": finish}], "usage": usage, **extra}
+
+
+def completion_chunk(rid: str, model: str, created: int, text: str, finish: str | None = None, **extra: Any) -> dict:
+ return {"id": rid, "object": "text_completion", "created": created, "model": model,
+ "choices": [{"index": 0, "text": text, "finish_reason": finish, "logprobs": None}], **extra}
+
+
+def error_body(message: str, code: str = "invalid_request_error") -> dict:
+ return {"error": {"message": message, "type": code, "code": code}}