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
Serve defaults: model-card sampling and a medium thinking effort on all three servers
YanissAmz2bfd26e6604c
diff --git a/doc/models.md b/doc/models.mdindex b17017c..fd41555 100644--- a/doc/models.md+++ b/doc/models.md@@ -15,7 +15,9 @@ hf download yamz-labs/GLM-5.3-Flash-EXL3-Yamz --local-dir ./glm-packpython tools/glm/serve.py --model ./glm-pack --port 8000 -c 131072 --num-draft 2```-GLM reasons at maximum effort by default. With a small `max_tokens`, the reasoning can use the whole budget: `content` is then empty and `finish_reason` is `length`. Send `"reasoning_effort": "low"` in the request (or start the server with `--default-reasoning-effort low`), or allow at least 1000 tokens. The server defaults to greedy sampling when a request gives no temperature; set the sampling values of the model card in your client, or with `--default-temperature` and `--default-top-p`.+All three servers answer a request that sets nothing with the sampling its model card recommends (read from the pack's `generation_config.json`: temperature 1.0, top_p 0.95, plus top_k 20 for Qwen) and with thinking effort `medium`. Medium is our own level: each model's chat template with one added instruction that ties the depth of the reasoning to the difficulty of the task. Without it, GLM reasons at its maximum level and can spend a very long time on an open request. A request can still send `temperature`, `top_p` and `reasoning_effort` (`low`, `high`, `max` for GLM; `low`, `xhigh` for Qwen), and `--default-temperature`, `--default-top-p`, `--default-reasoning-effort` change the server defaults. `--chat-template <pack>/chat_template.jinja` serves the model's unchanged template.++With a small `max_tokens`, the reasoning can use the whole budget: `content` is then empty and `finish_reason` is `length`. Allow at least 1000 tokens, or send `"reasoning_effort": "low"`.GLM: the pack ships `mtp_eh_proj.st`, an unquantized MTP `eh_proj` (64 MiB). The server loads it automatically from the model folder; it raises draft acceptance and decode speed (26.7 -> 31.6 tok/s greedy on the card protocol). Details in `tools/glm/SERVE.md`.diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 5e4c91b..16fd813 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -25,9 +25,9 @@ call, a streamed call, a tool call, and two 400-token benchmark calls.| `--model-id` | `glm-5.3-exl3` | id reported by `/v1/models` and echoed in every response || `--host` | `127.0.0.1` | bind address || `--port` | `8000` | port (smoke script uses 18080) |-| `--chat-template` | the model's `chat_template.jinja` | Jinja template file; `tools/lanes/assets/glm53-template-medium.jinja` is the one the lane uses |-| `--default-temperature` / `--default-top-p` | `0.0` / `1.0` | used when a request omits the field (explicit null too). The lane passes `1.0` / `0.95`: greedy defaults loop on agent clients |-| `--default-reasoning-effort` | none | template `reasoning_effort` when a request omits it (the lane passes `medium`) |+| `--chat-template` | `tools/lanes/assets/glm53-template-medium.jinja` | Jinja template file. The default is the model's template with a `medium` effort level added; `<model>/chat_template.jinja` is the unchanged one |+| `--default-temperature` / `--default-top-p` | from `generation_config.json` (`1.0` / `0.95`) | used when a request omits the field (explicit null too). Greedy defaults loop on agent clients that send no sampling |+| `--default-reasoning-effort` | `medium` | template `reasoning_effort` when a request omits it: `low`, `medium`, `high` or `max` || `--max-history` | `1` | recurrent history slots; must equal draft tokens (1 for MTP). Each extra slot costs ~2.15 GiB |Env vars the server sets for itself via `os.environ.setdefault` (so an external valuediff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 6702ddf..37b3e4f 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -114,7 +114,20 @@ TOOL_CLOSE = "</tool_call>"# Server-side defaults for fields a client leaves out (set from the CLI in main()).# The engine's own default stays greedy; the lane passes the model card's sampling.-SERVE_DEFAULTS: dict[str, Any] = {"temperature": 0.0, "top_p": 1.0, "reasoning_effort": None}+# Used when a request omits the field. main() replaces the sampling values with the pack's+# generation_config.json (the model card's recommendation); command-line flags win over both.+SERVE_DEFAULTS: dict[str, Any] = {"temperature": 1.0, "top_p": 0.95, "reasoning_effort": "medium"}+# The model's template (levels low, high, max) with a medium level added: the model's "high" plus one instruction line.+DEFAULT_TEMPLATE = Path(__file__).resolve().parent.parent / "lanes" / "assets" / "glm53-template-medium.jinja"+++def pack_sampling(model_dir: str) -> dict[str, float]:+ """temperature / top_p of the pack's generation_config.json, when it has them."""+ gc = Path(model_dir).expanduser() / "generation_config.json"+ if not gc.is_file():+ return {}+ cfg = json.loads(gc.read_text())+ return {k: float(cfg[k]) for k in ("temperature", "top_p") if cfg.get(k) is not None}def template_kwargs(body: dict[str, Any]) -> dict[str, Any]:@@ -836,15 +849,21 @@ def main() -> None:parser.add_argument("-c", "--max-ctx", type=int, default=131072, help="context window (capped by max_position_embeddings)")parser.add_argument("--slot-save-path", default="~/cache/llama-slots",help="directory for /slots save/restore files (llama.cpp compatible)")- parser.add_argument("--chat-template", default=None, help="Jinja chat template file (default: the model's)")- parser.add_argument("--default-temperature", type=float, default=0.0, help="used when a request omits temperature")- parser.add_argument("--default-top-p", type=float, default=1.0, help="used when a request omits top_p")- parser.add_argument("--default-reasoning-effort", default=None, help="template reasoning_effort when a request omits it")+ parser.add_argument("--chat-template", default=None,+ help="Jinja chat template file (default: tools/lanes/assets/glm53-template-medium.jinja; "+ "<model>/chat_template.jinja is the model's unchanged one)")+ parser.add_argument("--default-temperature", type=float, default=None,+ help="used when a request omits temperature (default: generation_config.json)")+ parser.add_argument("--default-top-p", type=float, default=None,+ help="used when a request omits top_p (default: generation_config.json)")+ parser.add_argument("--default-reasoning-effort", choices=("low", "medium", "high", "max"), default=None,+ help="thinking effort when a request omits it (default: medium)")args = parser.parse_args()if args.no_uncensor:os.environ["EXL3_ABLIT_RUNTIME"] = "off"- SERVE_DEFAULTS.update(temperature=args.default_temperature, top_p=args.default_top_p,- reasoning_effort=args.default_reasoning_effort)+ SERVE_DEFAULTS.update(pack_sampling(args.model))+ SERVE_DEFAULTS.update({k: v for k, v in (("temperature", args.default_temperature), ("top_p", args.default_top_p),+ ("reasoning_effort", args.default_reasoning_effort)) if v is not None})for key, value in SPEED_ENV.items():os.environ.setdefault(key, value)os.environ.setdefault("EXL3_MOE_UNION_V2", "1")@@ -852,14 +871,14 @@ def main() -> None:warm = os.environ.get("EXL3_SERVE_WARMUP", "1") != "0"tune = warm and float(os.environ.get("EXL3_SERVE_DTUNE_PRIME_S", "600")) > 0stages = ["target weights", "drafter weights"] + (["warm-up"] if warm else []) + (["dense GEMM tuning"] if tune else [])- startup_health.check_model_dir("serve", args.model, ("config.json",) if args.chat_template else ("config.json", "chat_template.jinja"))+ startup_health.check_model_dir("serve", args.model, ("config.json",))# A start with the dense GEMM tuning already cached is much shorter than the first one: keep their timings apart.startup_health.start("glm", stages, args.host, args.port, routes=ROUTES,variant="tuned" if tune and dense_tune_path().exists() else "untuned")startup_health.report_compiler()try:engine = ResidentEngine(args.model, max_history=args.max_history or args.num_draft, max_ctx=args.max_ctx, num_draft=args.num_draft)- template = Path(args.chat_template or Path(args.model) / "chat_template.jinja").expanduser().read_text(encoding="utf-8")+ template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")print(mem_line("loaded"), flush=True)# Warm-up before the slot store is attached, so the warm-up prompt never shows in /slots.# EXL3_SERVE_WARMUP=0 skips it.diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.mdindex e36e137..d96a76e 100644--- a/tools/mimo/SERVE.md+++ b/tools/mimo/SERVE.md@@ -24,7 +24,9 @@ Defaults: `--ndt 7 --dynamic-draft --draft-confidence 0.6`, no spec gate. The drFlags: `--host --port --model --model-id --drafter --ctx --ndt`(`--dflash`/`--no-dflash`, `--dynamic-draft`/`--no-dynamic-draft`, `--draft-confidence`, `--spec-gate`/`--no-spec-gate`, `--spec-gate-reset-per-request`,-`--default-temperature`, `--default-top-p`: used when a request omits or nulls the field; the lane passes 1.0 / 0.95).+`--default-temperature`, `--default-top-p`: used when a request omits or nulls the field; default = the pack's `generation_config.json`, 1.0 / 0.95;+`--default-reasoning-effort medium|none`: `medium` (default) adds one effort instruction as a leading system block, `none` leaves the model's own prompt;+`--chat-template`: default `tools/mimo/chat_template.jinja`, the model's template plus that `medium` level).`tools/lanes/serve_mimo.sh` runs the lane configuration (speculation on, `MIMO_SPEC=0` for plain decode, model-card sampling).Tool calls: a block body is JSON or `<parameter=k>v</parameter>` XML, typed by the request's tool schema; one block may hold several `<function=...>` elements; a malformed body is passed through raw; a cut-off trailing call is dropped.diff --git a/tools/mimo/chat_template.jinja b/tools/mimo/chat_template.jinjanew file mode 100644index 0000000..d7d8587--- /dev/null+++ b/tools/mimo/chat_template.jinja@@ -0,0 +1,98 @@+{%- macro render_value(value) -%}+ {%- if value is string -%}+ {{- value -}}+ {%- else -%}+ {{- value | tojson(ensure_ascii=False) -}}+ {%- endif -%}+{%- endmacro -%}++{%- macro render_content(message_content) -%}+ {%- if message_content is string -%}+ {{- message_content -}}+ {%- elif message_content is iterable -%}+ {%- for part in message_content -%}+ {%- if part is not mapping -%}+ {{- part -}}+ {%- elif part['type'] == 'image' or 'image' in part or 'image_url' in part -%}+ {{- '<|vision_start|><|image_pad|><|vision_end|>' -}}+ {%- elif part['type'] == 'audio' or part['type'] == 'input_audio' or 'audio' in part or 'audio_url' in part or 'input_audio' in part -%}+ {{- '<|mimo_audio_start|><|audio_pad|><|mimo_audio_end|>' -}}+ {%- elif part['type'] == 'video' or 'video' in part or 'video_url' in part -%}+ {{- '<|vision_start|><|video_pad|><|vision_end|>' -}}+ {%- elif 'text' in part -%}+ {{- part['text'] -}}+ {%- endif -%}+ {%- endfor -%}+ {%- endif -%}+{%- endmacro -%}++{%- macro render_tools(tools) -%}+ {{- 'You are provided with the following tools:\n\n<tools>' -}}+ {%- for tool in tools -%}+ {{- '\n' ~ (tool | tojson(ensure_ascii=False)) -}}+ {%- endfor -%}+ {{- '\n</tools>' -}}+{%- endmacro -%}++{%- macro render_tool_calls(tool_calls) -%}+ {%- for tool_call in tool_calls -%}+ {%- if tool_call.function is defined -%}+ {%- set tool_call = tool_call.function -%}+ {%- elif tool_call.custom is defined -%}+ {%- set tool_call = tool_call.custom -%}+ {%- endif -%}+ {{- '<tool_call><function=' ~ tool_call.name ~ '>' -}}+ {%- if tool_call.input is defined and tool_call.input is string -%}+ {{- tool_call.input -}}+ {%- elif tool_call.arguments -%}+ {%- if tool_call.arguments is string -%}+ {{- tool_call.arguments -}}+ {%- else -%}+ {%- for args_name, args_value in tool_call.arguments | items -%}+ {{- '<parameter=' ~ args_name ~ '>' ~ render_value(args_value) ~ '</parameter>' -}}+ {%- endfor -%}+ {%- endif -%}+ {%- endif -%}+ {{- '</function></tool_call>' -}}+ {%- endfor -%}+{%- endmacro -%}++{%- macro render_assistant_message(message) -%}+ {%- set content = render_content(message.content) -%}+ {%- set reasoning = message.reasoning_content if message.reasoning_content is string else '' -%}+ {{- '<|im_start|>assistant\n<think>' ~ reasoning ~ '</think>' ~ content -}}+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 -%}+ {{- render_tool_calls(message.tool_calls) -}}+ {%- endif -%}+ {{- '<|im_end|>' -}}+{%- endmacro -%}++{%- if reasoning_effort is defined and reasoning_effort == 'medium' -%}+ {{- '<|im_start|>system\nMatch the depth of your work to the difficulty of the task: spend it on the points that decide the answer and verify what they rest on, not on alternatives the task does not call for. Gather what the answer needs, then give it.<|im_end|>' -}}+{%- endif -%}+{%- if tools is defined and tools is iterable and tools | length > 0 -%}+ {{- '<|im_start|>system\n' ~ render_tools(tools) ~ '<|im_end|>' -}}+{%- endif -%}++{%- for message in messages -%}+ {%- if message.role == 'assistant' -%}+ {{- render_assistant_message(message) -}}+ {%- else -%}+ {%- set body = render_content(message.content) -%}+ {{- '<|im_start|>' ~ message.role ~ '\n' ~ body -}}+ {%- if message.tools is defined and message.tools is iterable and message.tools | length > 0 -%}+ {%- if body -%}+ {{- '\n\n' -}}+ {%- endif -%}+ {{- render_tools(message.tools) -}}+ {%- endif -%}+ {{- '<|im_end|>' -}}+ {%- endif -%}+{%- endfor -%}++{%- if add_generation_prompt -%}+ {{- '<|im_start|>assistant\n' -}}+ {%- if enable_thinking is false -%}+ {{- '<think></think>' -}}+ {%- endif -%}+{%- endif -%}diff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex d92b30f..6417f16 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -38,9 +38,29 @@ DEFAULT_MODEL = os.path.expanduser("~/models/mimo26-exl3")DEFAULT_MODEL_ID = "MiMo-2.6-EXL3"DEFAULT_CTX = 4096DEFAULT_NDT = 7-# Sampling used when a request omits temperature/top_p. Agent clients often send neither, so-# a plain-greedy default makes the lane loop; the lane launchers pass the model-card values (T1.0, top_p 0.95).-SERVE_DEFAULTS: dict[str, float] = {"temperature": 0.0, "top_p": 1.0}+# Used when a request omits the field. Agent clients often send no sampling at all, and plain greedy+# makes the model loop: main() takes the values of the pack's generation_config.json (the model+# card's recommendation); command-line flags win over both.+SERVE_DEFAULTS: dict[str, Any] = {"temperature": 1.0, "top_p": 0.95, "reasoning_effort": "medium"}+# The model's own template plus a medium effort level (the model defines none).+DEFAULT_TEMPLATE = Path(__file__).with_name("chat_template.jinja")+++def pack_sampling(model_dir: str) -> dict[str, float]:+ """temperature / top_p of the pack's generation_config.json, when it has them."""+ gc = Path(model_dir).expanduser() / "generation_config.json"+ if not gc.is_file():+ return {}+ cfg = json.loads(gc.read_text())+ return {k: float(cfg[k]) for k in ("temperature", "top_p") if cfg.get(k) is not None}+++def template_kwargs(body: dict[str, Any]) -> dict[str, Any]:+ """reasoning_effort for the chat template: chat_template_kwargs > top level > server default."""+ ctk = body.get("chat_template_kwargs")+ ctk = ctk if isinstance(ctk, dict) else {}+ effort = ctk.get("reasoning_effort") or body.get("reasoning_effort") or SERVE_DEFAULTS["reasoning_effort"]+ return {"reasoning_effort": effort} if isinstance(effort, str) else {}# The template uses a zero-width space inside the tag so plain prose does not trigger tools.TOOL_OPEN = "<tool_call>"TOOL_CLOSE = "</tool_call>"@@ -480,7 +500,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:stops = body.get("stop", [])body["_stop"] = [stops] if isinstance(stops, str) else list(stops)body["_reset_gate"] = bool(getattr(app["engine"], "reset_gate_per_request", False))- prompt = render_prompt(template, body["messages"], body.get("tools"))+ prompt = render_prompt(template, body["messages"], body.get("tools"), **template_kwargs(body))prompt_tokens = engine.count_tokens(prompt)body["_prompt_tokens"] = prompt_tokensbody["_room"] = reply_room(engine, prompt_tokens)@@ -624,7 +644,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:body = await request.json()if not isinstance(body.get("messages"), list) or not body["messages"]:raise web.HTTPBadRequest(reason="messages must be a non-empty array")- prompt = render_prompt(template, body["messages"], body.get("tools"))+ prompt = render_prompt(template, body["messages"], body.get("tools"), **template_kwargs(body))except (json.JSONDecodeError, web.HTTPException, TypeError) as exc:if isinstance(exc, web.HTTPException):raise@@ -781,12 +801,21 @@ def main() -> None:help="rebuild the SpecGate for every request (default: keep it)")parser.add_argument("--slot-save-path", default="~/cache/llama-slots",help="directory for /slots save/restore files (llama.cpp compatible)")- parser.add_argument("--default-temperature", type=float, default=0.0, help="used when a request omits temperature")- parser.add_argument("--default-top-p", type=float, default=1.0, help="used when a request omits top_p")+ parser.add_argument("--chat-template", default=None,+ help="Jinja chat template file (default: chat_template.jinja next to this script; "+ "<model>/chat_template.jinja is the model's unchanged one)")+ parser.add_argument("--default-temperature", type=float, default=None,+ help="used when a request omits temperature (default: generation_config.json)")+ parser.add_argument("--default-top-p", type=float, default=None,+ help="used when a request omits top_p (default: generation_config.json)")+ parser.add_argument("--default-reasoning-effort", choices=("medium", "none"), default=None,+ help="medium (default) adds one effort instruction to the prompt; none leaves the model's own prompt")args = parser.parse_args()if args.no_uncensor:os.environ["EXL3_ABLIT_RUNTIME"] = "off"- SERVE_DEFAULTS.update(temperature=args.default_temperature, top_p=args.default_top_p)+ SERVE_DEFAULTS.update(pack_sampling(args.model))+ SERVE_DEFAULTS.update({k: v for k, v in (("temperature", args.default_temperature), ("top_p", args.default_top_p),+ ("reasoning_effort", args.default_reasoning_effort)) if v is not None})torch.set_grad_enabled(False)drafter = None@@ -818,7 +847,7 @@ def main() -> None:from exllamav3.generator.slot_store import SlotStoreengine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],args.slot_save_path, args.model_id)- template = (Path(args.model) / "chat_template.jinja").read_text(encoding="utf-8")+ template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")except BaseException as exc: # noqa: BLE001startup_health.abort(f"{type(exc).__name__}: {exc}")raisediff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdindex 7c0641e..7eb071d 100644--- a/tools/qwen/SERVE.md+++ b/tools/qwen/SERVE.md@@ -41,7 +41,8 @@ Quick test:| `--draft-policy` | `mix` | `mix` shipped rule, `mtp` fixed MTP chain, `off` plain decode (no drafter loaded) || `--no-vision` | off | do not load the vision tower (less memory, image input answers 400) || `--default-temperature/-top-p/-top-k/-min-p` | from `generation_config.json` (1.0 / 0.95 / 20) | used when a request omits them |-| `--default-reasoning-effort` | template default (`xhigh`) | `low`, `medium` or `xhigh` |+| `--default-reasoning-effort` | `medium` | `low`, `medium` or `xhigh` |+| `--chat-template` | `tools/qwen/chat_template.jinja` | the model's template with a `medium` effort instruction added (the model's own leaves medium empty); `<model>/chat_template.jinja` is the unchanged one || `--no-thinking` | off | thinking off unless a request turns it on || `--default-max-tokens` | 32768 | when a request omits `max_tokens` (always clipped to the free context) || `--slot-save-path` | `~/cache/llama-slots` | directory for slot files |@@ -60,8 +61,8 @@ environment wins. The engine modules read several of these when they are importe- `POST /v1/chat/completions`: stream (SSE) and non-stream, `tools` and `tool_calls`, `tool` role messages, images as`image_url` parts (`data:` URI or http(s) URL), `stop`, `max_tokens` / `max_completion_tokens`, `temperature`,- `top_p`, `top_k`, `min_p`, `seed`. The model's own chat template renders the prompt (identical to the HF `apply_chat_template`).-- Thinking: the template default is thinking ON at effort `xhigh`; the answer then starts inside a reasoning block.+ `top_p`, `top_k`, `min_p`, `seed`. The chat template renders the prompt (with the model's own file, identical to the HF `apply_chat_template`).+- Thinking: ON by default, at effort `medium`; the answer then starts inside a reasoning block.The server splits it into `reasoning_content` and `content`. Turn it off per request with `"enable_thinking": false`(or `"chat_template_kwargs": {"enable_thinking": false}` or `"reasoning_effort": "none"`). Effort: `low`, `medium`,`xhigh` (`high` maps to `xhigh`, `minimal` to `low`).diff --git a/tools/qwen/chat_template.jinja b/tools/qwen/chat_template.jinjanew file mode 100644index 0000000..88bb543--- /dev/null+++ b/tools/qwen/chat_template.jinja@@ -0,0 +1,172 @@+{%- set image_count = namespace(value=0) %}+{%- set video_count = namespace(value=0) %}+{%- macro render_content(content, do_vision_count, is_system_content=false) %}+ {%- if content is string %}+ {{- content }}+ {%- elif content is iterable and content is not mapping %}+ {%- for item in content %}+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}+ {%- 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 %}+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}+ {%- elif 'video' in item or item.type == 'video' %}+ {%- 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 %}+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}+ {%- elif 'text' in item %}+ {{- item.text }}+ {%- else %}+ {{- raise_exception('Unexpected item type in content.') }}+ {%- endif %}+ {%- endfor %}+ {%- elif content is none or content is undefined %}+ {{- '' }}+ {%- else %}+ {{- raise_exception('Unexpected content type.') }}+ {%- endif %}+{%- endmacro %}+{%- if not messages %}+ {{- raise_exception('No messages provided.') }}+{%- endif %}+{%- set reasoning_instructions = '' %}+{%- if enable_thinking is undefined or enable_thinking is true %}+ {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}+ {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}+ {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}+ {%- endif %}+ {%- if resolved_reasoning_effort == 'xhigh' %}+ {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}+ {%- elif resolved_reasoning_effort == 'medium' %}+ {%- set reasoning_instructions = 'Reasoning effort is set to medium. Match the depth of your work to the difficulty of the task: spend it on the points that decide the answer and verify what they rest on, not on alternatives the task does not call for. Gather what the answer needs, then give it.' %}+ {%- elif resolved_reasoning_effort == 'low' %}+ {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}+ {%- endif %}+{%- endif %}+{%- if tools and tools is iterable and tools is not mapping %}+ {{- '<|im_start|>system\n' }}+ {%- if reasoning_instructions %}+ {{- reasoning_instructions + '\n\n' }}+ {%- endif %}+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}+ {%- for tool in tools %}+ {{- "\n" }}+ {{- tool | tojson }}+ {%- endfor %}+ {{- "\n</tools>" }}+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}+ {%- if messages[0].role == 'system' %}+ {%- set content = render_content(messages[0].content, false, true)|trim %}+ {%- if content %}+ {{- '\n\n' + content }}+ {%- endif %}+ {%- endif %}+ {{- '<|im_end|>\n' }}+{%- else %}+ {%- if messages[0].role == 'system' %}+ {%- set content = render_content(messages[0].content, false, true)|trim %}+ {%- if content %}+ {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}+ {%- elif reasoning_instructions %}+ {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}+ {%- endif %}+ {%- elif reasoning_instructions %}+ {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}+ {%- endif %}+{%- endif %}+{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}+{%- for message in messages[::-1] %}+ {%- set index = (messages|length - 1) - loop.index0 %}+ {%- if ns.multi_step_tool and message.role == "user" %}+ {%- set content = render_content(message.content, false)|trim %}+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}+ {%- set ns.multi_step_tool = false %}+ {%- set ns.last_query_index = index %}+ {%- endif %}+ {%- endif %}+{%- endfor %}+{%- if ns.multi_step_tool %}+ {{- raise_exception('No user query found in messages.') }}+{%- endif %}+{%- for message in messages %}+ {%- set content = render_content(message.content, true)|trim %}+ {%- if message.role == "system" %}+ {%- if not loop.first %}+ {{- raise_exception('System message must be at the beginning.') }}+ {%- endif %}+ {%- elif message.role == "user" %}+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}+ {%- elif message.role == "assistant" %}+ {%- set reasoning_content = '' %}+ {%- if message.reasoning_content is string %}+ {%- set reasoning_content = message.reasoning_content %}+ {%- endif %}+ {%- set reasoning_content = reasoning_content|trim %}+ {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}+ {%- else %}+ {{- '<|im_start|>' + message.role + '\n' + content }}+ {%- endif %}+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}+ {%- for tool_call in message.tool_calls %}+ {%- if tool_call.function is defined %}+ {%- set tool_call = tool_call.function %}+ {%- endif %}+ {%- if loop.first %}+ {%- if content|trim %}+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}+ {%- else %}+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}+ {%- endif %}+ {%- else %}+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}+ {%- endif %}+ {%- if tool_call.arguments is defined and tool_call.arguments != '' %}+ {%- for args_name, args_value in tool_call.arguments|items %}+ {{- '<parameter=' + args_name + '>\n' }}+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}+ {{- args_value }}+ {{- '\n</parameter>\n' }}+ {%- endfor %}+ {%- endif %}+ {{- '</function>\n</tool_call>' }}+ {%- endfor %}+ {%- endif %}+ {{- '<|im_end|>\n' }}+ {%- elif message.role == "tool" %}+ {%- if loop.previtem and loop.previtem.role != "tool" %}+ {{- '<|im_start|>user' }}+ {%- endif %}+ {{- '\n<tool_response>\n' }}+ {{- content }}+ {{- '\n</tool_response>' }}+ {%- if not loop.last and loop.nextitem.role != "tool" %}+ {{- '<|im_end|>\n' }}+ {%- elif loop.last %}+ {{- '<|im_end|>\n' }}+ {%- endif %}+ {%- else %}+ {{- raise_exception('Unexpected message role.') }}+ {%- endif %}+{%- endfor %}+{%- if add_generation_prompt %}+ {{- '<|im_start|>assistant\n' }}+ {%- if enable_thinking is defined and enable_thinking is false %}+ {{- '<think>\n\n</think>\n\n' }}+ {%- else %}+ {{- '<think>\n' }}+ {%- endif %}+{%- endif %}\ No newline at end of filediff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 98cba46..1ffd6a1 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -60,6 +60,10 @@ IMAGE_PAD = "<|image_pad|>"MAX_IMAGE_BYTES = 20 * 1024**2# Used when generation_config.json is missing (values of the Qwen3.8 card).FALLBACK_DEFAULTS: dict[str, Any] = {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0}+# Thinking effort when a request names none. The model's own template defines xhigh and low only;+# chat_template.jinja next to this file is that template plus a medium level.+DEFAULT_EFFORT = "medium"+DEFAULT_TEMPLATE = Path(__file__).with_name("chat_template.jinja")# OpenAI effort names -> the Qwen template names (xhigh, medium, low).EFFORT_ALIASES = {"high": "xhigh", "minimal": "low"}@@ -336,7 +340,7 @@ def load_defaults(model_dir: str, args: argparse.Namespace | None = None) -> dicif gc.is_file():cfg = json.loads(gc.read_text())d.update({k: cfg[k] for k in ("temperature", "top_p", "top_k") if k in cfg})- d.update({"enable_thinking": None, "reasoning_effort": None})+ d.update({"enable_thinking": None, "reasoning_effort": DEFAULT_EFFORT})if args is not None:for key in ("temperature", "top_p", "top_k", "min_p"):v = getattr(args, "default_" + key, None)@@ -1694,7 +1698,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Andef load_all(args: argparse.Namespace):"""Everything before the port opens: template, defaults, engine, slot store, warm-up."""model_dir = str(Path(args.model).expanduser())- template = (Path(model_dir) / "chat_template.jinja").read_text(encoding="utf-8")+ template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")defaults = load_defaults(model_dir, args)t0 = time.time()print(f"qserve: starting, model={model_dir} ctx={args.ctx} sessions={args.sessions} draft_policy={args.draft_policy} "@@ -1734,8 +1738,11 @@ def main() -> None:parser.add_argument("--default-top-p", type=float, default=None)parser.add_argument("--default-top-k", type=int, default=None)parser.add_argument("--default-min-p", type=float, default=None)+ parser.add_argument("--chat-template", default=None,+ help="Jinja chat template file (default: chat_template.jinja next to this script; "+ "<model>/chat_template.jinja is the model's unchanged one)")parser.add_argument("--default-reasoning-effort", choices=("low", "medium", "xhigh"), default=None,- help="thinking effort when a request omits it (template default: xhigh)")+ help=f"thinking effort when a request omits it (default: {DEFAULT_EFFORT})")parser.add_argument("--no-thinking", action="store_true", help="thinking off unless a request turns it on")parser.add_argument("--default-max-tokens", type=int, default=32768, help="when a request omits max_tokens")parser.add_argument("--slot-save-path", default="~/cache/llama-slots")diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex 0381d1e..9d7c47f 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -27,6 +27,8 @@ THINK_TEMPLATE = ("{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content"{% if enable_thinking is defined and enable_thinking is false %}<think>\n\n</think>\n\n""{% else %}<think>\n{% endif %}{% endif %}""{% if reasoning_effort is defined %}EFFORT={{ reasoning_effort }}{% endif %}")+# THINK_TEMPLATE prints the effort after the generation prompt: the HTTP tests run without a default effort.+NO_EFFORT_DEFAULTS = dict(serve.load_defaults("/x"), reasoning_effort=None)TOOLS = [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}, "days": {"type": "integer"},"opts": {"type": "object"}}}}}]@@ -65,7 +67,7 @@ def with_client(engine, fn, template=THINK_TEMPLATE, defaults=None):from aiohttp.test_utils import TestClient, TestServerasync def go():- client = TestClient(TestServer(serve.create_app(engine, "m", template, defaults or serve.load_defaults("/x"))))+ client = TestClient(TestServer(serve.create_app(engine, "m", template, defaults or NO_EFFORT_DEFAULTS)))await client.start_server()try:return await fn(client)@@ -126,6 +128,7 @@ class ParserTests(unittest.TestCase):class RequestTests(unittest.TestCase):def test_template_kwargs_precedence(self):+ self.assertEqual(serve.resolve_template_kwargs({}, serve.load_defaults("/x")), {"reasoning_effort": "medium"})d = {"enable_thinking": None, "reasoning_effort": "low"}self.assertEqual(serve.resolve_template_kwargs({}, d), {"reasoning_effort": "low"})self.assertEqual(serve.resolve_template_kwargs({"reasoning_effort": "high"}, d), {"reasoning_effort": "xhigh"})