Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

qwen36: render the template's preserve_thinking so standard clients get KV prefix reuse

JustVuggacf70442a3ac
diff --git a/c/openai_server.py b/c/openai_server.py
index dcdbc80a..221427b3 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -1402,7 +1402,7 @@ def render_chat_olmoe(messages, enable_thinking=False, reasoning_effort=None, to
def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, tools=None,
- tool_choice=None, add_generation_prompt=True):
+ tool_choice=None, add_generation_prompt=True, preserve_thinking=False):
"""Text-only subset of Qwen3.6's chat_template: <|im_start|>role\\n ...
<|im_end|>\\n frames, then the generation prompt. The official template
opens a mandatory <think> block after `<|im_start|>assistant\\n` — the
@@ -1415,11 +1415,32 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
assistant turn AFTER the last user query with its <think></think> block (an earlier one,
from history, has it stripped) -- so the open-turn shape is that think-form minus the
<|im_end|> terminator and with no cue, not the bare history form the loop emits otherwise.
- ChatML's per-turn terminator is why the marker has to be dropped explicitly, as on qwen38."""
+ ChatML's per-turn terminator is why the marker has to be dropped explicitly, as on qwen38.
+
+ preserve_thinking is the template's own kwarg of the same name (#1759): every past assistant
+ turn keeps its <think> block, `reasoning_content` inside it, empty when there is none. Qwen
+ trained Qwen3.6 on that form. Without it the template strips the block from every turn before
+ the last user query, so a turn generated after the pre-closed think header comes back without
+ the header it was fed, the resent history diverges from the engine's state at the first
+ assistant turn, and prefix reuse -- all or nothing on a recurrent state -- never engages."""
if not isinstance(messages, list) or not messages:
raise APIError(400, "`messages` must be a non-empty array.", "messages")
if tool_choice == "none":
tools = None
+ # The template's last_query_index: the last user turn that is a real query and not a
+ # tool result riding in as one. An assistant turn after it keeps its <think> block
+ # with or without preserve_thinking. With no query at all the template raises; here
+ # the index stays where the template starts it, at the last message.
+ last_query = len(messages) - 1
+ for index in range(len(messages) - 1, -1, -1):
+ message = messages[index]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ raw = message.get("content")
+ query = (content_text(raw, f"messages.{index}.content") if raw is not None else "").strip()
+ if not (query.startswith("<tool_response>") and query.endswith("</tool_response>")):
+ last_query = index
+ break
if (tools or tool_choice not in (None, "none")) and not _TOOL_FALLBACK:
raise APIError(400, "Tool use is not wired up for the qwen36 engine yet. "
"Set COLI_TOOL_FALLBACK=1 to opt into prompt-injected "
@@ -1456,6 +1477,18 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
parts.append("<|im_start|>user\n"
+ _fallback_tool_result(message, index) + "<|im_end|>\n")
continue
+ if role == "assistant":
+ # The template's reading of a past turn: `reasoning_content` when it is a
+ # string, otherwise whatever the content carries before a </think> (a client
+ # echoing the raw reply), which then leaves the content.
+ reasoning = message.get("reasoning_content")
+ if not isinstance(reasoning, str):
+ reasoning = ""
+ if "</think>" in text:
+ reasoning = text.split("</think>")[0].rstrip("\n").split("<think>")[-1].lstrip("\n")
+ text = text.split("</think>")[-1].lstrip("\n")
+ if preserve_thinking or index > last_query:
+ text = f"<think>\n{reasoning.strip()}\n</think>\n\n{text}"
if role == "assistant" and _TOOL_FALLBACK:
text += _fallback_tool_calls(message.get("tool_calls"), index)
parts.append(f"<|im_start|>{role}\n{text}<|im_end|>\n")
@@ -2569,7 +2602,8 @@ def resolve_generation_prompt(messages, body):
def render_chat_for_arch(messages, enable_thinking=False, reasoning_effort=None, tools=None,
- tool_choice=None, audio_out=None, add_generation_prompt=True):
+ tool_choice=None, audio_out=None, add_generation_prompt=True,
+ preserve_thinking=False):
"""Render a chat request with the active engine's native prompt contract.
`add_generation_prompt=False` (a continued assistant turn) is implemented for the families
@@ -2592,7 +2626,7 @@ def render_chat_for_arch(messages, enable_thinking=False, reasoning_effort=None,
tool_choice, add_generation_prompt)
if ARCH == "qwen36":
return render_chat_qwen(messages, enable_thinking, reasoning_effort, tools,
- tool_choice, add_generation_prompt)
+ tool_choice, add_generation_prompt, preserve_thinking)
if ARCH == "glm":
return render_chat(messages, enable_thinking, reasoning_effort, tools,
tool_choice, add_generation_prompt)
@@ -5209,6 +5243,15 @@ class APIHandler(BaseHTTPRequestHandler):
# while non-streaming happened to survive. Make the template's "unused"
# true end-to-end instead of trusting every path to opt out.
enable_thinking = False
+ # Qwen3.6's preserve_thinking (#1759), under the name Qwen's own API gives it. Off
+ # by default with thinking on: a standard client does not send the reasoning back,
+ # and the block would come back empty where the model did think. On by default with
+ # thinking off: there the block the history gets is the empty one the turn was
+ # actually generated after, so the resent history is the engine's state byte for
+ # byte and prefix reuse can engage. Only the qwen36 renderer reads it.
+ preserve_thinking = body.get("preserve_thinking", not enable_thinking)
+ if not isinstance(preserve_thinking, bool):
+ raise APIError(400, "`preserve_thinking` must be a boolean.", "preserve_thinking")
tools = body.get("tools") or body.get("functions") or None
tool_choice = body.get("tool_choice")
audio_clips = [] if ARCH == "inkling" else None
@@ -5245,7 +5288,8 @@ class APIHandler(BaseHTTPRequestHandler):
add_generation_prompt = resolve_generation_prompt(messages, body)
prompt = render_chat_for_arch(messages, enable_thinking, reasoning_effort,
tools, tool_choice, audio_out=audio_clips,
- add_generation_prompt=add_generation_prompt)
+ add_generation_prompt=add_generation_prompt,
+ preserve_thinking=preserve_thinking)
self.generation(body, prompt, request_id, True, tools, tool_choice,
enable_thinking=enable_thinking,
add_generation_prompt=add_generation_prompt,
@@ -5291,7 +5335,8 @@ class APIHandler(BaseHTTPRequestHandler):
prompt = render_chat_for_arch(messages, enable_thinking,
default_effort if enable_thinking else None,
tools, tool_choice,
- add_generation_prompt=add_generation_prompt)
+ add_generation_prompt=add_generation_prompt,
+ preserve_thinking=not enable_thinking)
self.anthropic_generation(translated, prompt, request_id, tools, enable_thinking,
add_generation_prompt)
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 8695bc9d..28e49d37 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -25,7 +25,7 @@ from openai_server import (APIError, APIHandler, APIServer, ClientCancelled,
parse_arch_tool_calls, parse_k3_tool_calls, parse_qwen38_tool_calls,
read_engine_turn, render_chat, render_chat_for_arch,
render_chat_glm53, render_chat_inkling, render_chat_kimi,
- render_chat_olmoe,
+ render_chat_olmoe, render_chat_qwen,
render_chat_qwen38, render_chat_v4, render_chat_dsv41,
_dsv4_tool_calls, serve,
resolve_generation_prompt, split_thinking_reply,
@@ -197,6 +197,39 @@ class TemplateTest(unittest.TestCase):
"G 1\n",
)
+ def test_qwen36_history_is_what_the_engine_was_fed(self):
+ """#1759: prefix reuse on qwen36 is all or nothing, because nothing rewinds the
+ DeltaNet state, so it engages only if the next turn's prompt begins with exactly
+ the text the engine read: the previous prompt plus what it generated. The
+ template's preserve_thinking gives a past turn the <think> block it was generated
+ after; its default strips the block, and the history diverges at the first
+ assistant turn of every conversation."""
+ first = [{"role": "user", "content": "Capital of France?"}]
+ follow = {"role": "user", "content": "And of Italy?"}
+
+ # Thinking off: the generation followed the pre-closed header.
+ fed = render_chat_qwen(first, enable_thinking=False) + "Paris."
+ history = first + [{"role": "assistant", "content": "Paris."}, follow]
+ self.assertTrue(render_chat_qwen(history, enable_thinking=False,
+ preserve_thinking=True).startswith(fed))
+ self.assertFalse(render_chat_qwen(history, enable_thinking=False).startswith(fed))
+
+ # Thinking on: the history matches only if the client sends the reasoning back,
+ # as reasoning_content or inside the content, the way the model wrote it.
+ fed = (render_chat_qwen(first, enable_thinking=True)
+ + "Easy one.\n</think>\n\nParis.")
+ for past in ({"role": "assistant", "content": "Paris.",
+ "reasoning_content": "Easy one."},
+ {"role": "assistant",
+ "content": "<think>\nEasy one.\n</think>\n\nParis."}):
+ with self.subTest(past=past):
+ prompt = render_chat_qwen(first + [past, follow], enable_thinking=True,
+ preserve_thinking=True)
+ self.assertTrue(prompt.startswith(fed))
+ # Without preserve_thinking the block leaves the history either way.
+ self.assertIn("<|im_start|>assistant\nParis.<|im_end|>",
+ render_chat_qwen(first + [past, follow], enable_thinking=True))
+
def test_kimi_renders_tool_declaration_and_choice(self):
tools = [{"type": "function", "function": {
"name": "get_weather", "parameters": {"type": "object"}}}]
@@ -2099,6 +2132,34 @@ class HTTPTest(unittest.TestCase):
self.addCleanup(caught.exception.close)
self.assertEqual(caught.exception.code, 400)
+ def test_qwen36_preserve_thinking_defaults_to_the_fed_history(self):
+ """#1759: with thinking off the past turn keeps the empty block it was generated
+ after, so a standard client's resent history matches the engine's state. With
+ thinking on the template default stays: a standard client does not send the
+ reasoning back, and an empty block would claim the model did not think. The
+ request key overrides either way."""
+ history = [{"role": "user", "content": "Capital of France?"},
+ {"role": "assistant", "content": "Paris."},
+ {"role": "user", "content": "And of Italy?"}]
+ kept = "<|im_start|>assistant\n<think>\n\n</think>\n\nParis.<|im_end|>"
+ bare = "<|im_start|>assistant\nParis.<|im_end|>"
+ cases = (({}, kept), ({"enable_thinking": True}, bare),
+ ({"preserve_thinking": False}, bare),
+ ({"enable_thinking": True, "preserve_thinking": True},
+ "<|im_start|>assistant\n<think>\n\n</think>\n\nParis.<|im_end|>"))
+ with patch("openai_server.ARCH", "qwen36"):
+ for extra, expected in cases:
+ with self.subTest(extra=extra):
+ with self.request("/v1/chat/completions", {
+ "model": "test-model", "messages": history, **extra}) as response:
+ self.assertEqual(response.status, 200)
+ self.assertIn(expected, self.engine.calls[-1][0])
+ with self.assertRaises(HTTPError) as caught:
+ self.request("/v1/chat/completions", {
+ "model": "test-model", "messages": history, "preserve_thinking": "yes"})
+ self.addCleanup(caught.exception.close)
+ self.assertEqual(caught.exception.code, 400)
+
def test_a_well_formed_forced_tool_choice_still_runs(self):
"""The read above must not change the shape clients actually send."""
with self.request("/v1/chat/completions", {
diff --git a/c/tests/test_qwen36_chat_template.py b/c/tests/test_qwen36_chat_template.py
index f3014f5d..a3ab3101 100644
--- a/c/tests/test_qwen36_chat_template.py
+++ b/c/tests/test_qwen36_chat_template.py
@@ -6,8 +6,8 @@ quella scelta si paga in un modo solo: la copia scritta a mano puo' scostarsi
dall'originale senza che nessuno se ne accorga, perche' il modello risponde
comunque. Qui il template vero viene reso con jinja2 e confrontato byte per byte
con quello che produce il gateway, senza strumenti (che il motore qwen36 non
-espone) e sui due rami del blocco di ragionamento, piu' il turno aperto della
-prosecuzione.
+espone) e sui due rami del blocco di ragionamento, per ciascuno con e senza
+preserve_thinking (#1759), piu' il turno aperto della prosecuzione.
Se manca il template o jinja2, il test si dichiara SALTATO invece di passare: un
test che non ha trovato il suo riferimento non ha verificato niente, e dirlo
@@ -41,12 +41,34 @@ CASES = {
{"role": "assistant", "content": "2"},
{"role": "user", "content": "e 2+2?"}],
},
+ # Il ragionamento rimandato dal client: il template lo scrive solo con
+ # preserve_thinking, altrimenti lo toglie.
+ "ragionamento in cronologia": {
+ "messages": [{"role": "user", "content": "1+1?"},
+ {"role": "assistant", "content": "2", "reasoning_content": "uno piu' uno"},
+ {"role": "user", "content": "e 2+2?"}],
+ },
+ # Un client che rimanda la risposta grezza: il template separa il blocco dal
+ # contenuto a </think>.
+ "risposta grezza in cronologia": {
+ "messages": [{"role": "user", "content": "1+1?"},
+ {"role": "assistant", "content": "<think>\nuno piu' uno\n</think>\n\n2"},
+ {"role": "user", "content": "e 2+2?"}],
+ },
+ # Un turno assistant DOPO l'ultima domanda tiene il blocco anche senza
+ # preserve_thinking (last_query_index del template).
+ "assistant dopo l'ultima domanda": {
+ "messages": [{"role": "user", "content": "1+1?"},
+ {"role": "assistant", "content": "2"}],
+ },
}
THINKING = (True, False)
+PRESERVE = (False, True)
-def reference(template_text, *, messages, enable_thinking=True, add_generation_prompt=True):
+def reference(template_text, *, messages, enable_thinking=True, add_generation_prompt=True,
+ preserve_thinking=False):
import jinja2
def raise_exception(message):
@@ -59,7 +81,7 @@ def reference(template_text, *, messages, enable_thinking=True, add_generation_p
environment.globals["raise_exception"] = raise_exception
rendered = environment.from_string(template_text)
return rendered.render(messages=messages, add_generation_prompt=add_generation_prompt,
- enable_thinking=enable_thinking)
+ enable_thinking=enable_thinking, preserve_thinking=preserve_thinking)
def show(label, ours, theirs):
@@ -98,17 +120,21 @@ def main() -> int:
failures = 0
for enable_thinking in THINKING:
- for label, case in CASES.items():
- name = f"{label} [thinking={enable_thinking}]"
- theirs = reference(template_text, messages=case["messages"],
- enable_thinking=enable_thinking)
- ours = openai_server.render_chat_qwen(case["messages"],
- enable_thinking=enable_thinking)
- if ours == theirs:
- print(f"ok {name}")
- else:
- show(name, ours, theirs)
- failures += 1
+ for preserve_thinking in PRESERVE:
+ for label, case in CASES.items():
+ name = (f"{label} [thinking={enable_thinking} "
+ f"preserve_thinking={preserve_thinking}]")
+ theirs = reference(template_text, messages=case["messages"],
+ enable_thinking=enable_thinking,
+ preserve_thinking=preserve_thinking)
+ ours = openai_server.render_chat_qwen(case["messages"],
+ enable_thinking=enable_thinking,
+ preserve_thinking=preserve_thinking)
+ if ours == theirs:
+ print(f"ok {name}")
+ else:
+ show(name, ours, theirs)
+ failures += 1
# Prosecuzione: l'ultimo turno assistant e' da CONTINUARE. Come qwen38, ChatML chiude
# ogni turno con <|im_end|> e il template non ha un ramo di continuazione, quindi la
diff --git a/docs/api.md b/docs/api.md
index 50034b49..33a627fd 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -75,6 +75,18 @@ sequences. The extension
`enable_thinking: true` enables GLM-5.2's reasoning block; the standard
`reasoning_effort` field also enables it unless set to `none`.
+On Qwen3.6 the extension `preserve_thinking` is the official template's kwarg of
+the same name: past assistant turns keep their `<think>` block, with the
+`reasoning_content` the client sends back, empty when it sends none. It
+defaults to `true` when thinking is off and to `false` when it is on. With
+thinking off, the empty block is the one each past turn was generated after,
+so a client that resends only `content` sends the history the engine already
+holds and the KV prefix is reused instead of prefilled again (#1759). With
+thinking on a standard client drops the reasoning, the history cannot match
+either way, and the template's default applies; a client that sends
+`reasoning_content` back can set `preserve_thinking: true` to get the reuse
+too. Both values render byte for byte like the official `chat_template.jinja`.
+
The server serves one generation at a time: the model stays in one persistent
process, so concurrent HTTP requests queue instead of loading duplicate model
copies. Tool calling depends on the active engine; see the support matrix below.