Commit 74e7f4465 for llama.cpp

commit 74e7f44650e264c311e777cd894e24f9847dc050
Author: Xuan-Son Nguyen <son@huggingface.co>
Date:   Thu Dec 3 19:18:55 2026 +0100

    model: qwen4 (#33626)

    Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
    Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
    Co-authored-by: Pascal <admin@serveurperso.com>

diff --git a/common/parsers/qwen3-coder.cpp b/common/parsers/qwen3-coder.cpp
index c943b93f3..3256660fc 100644
--- a/common/parsers/qwen3-coder.cpp
+++ b/common/parsers/qwen3-coder.cpp
@@ -20,12 +20,30 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat

     auto is_qwen3_coder  = !supports_reasoning;

+    // Compact reasoning: "<think>" + reasoning + "</think>" + content with no separators (Qwen4), unlike the
+    // "<think>\n...\n</think>\n\n" of Qwen3.5. The template shows it when thinking is turned off.
+    bool compact_think = false;
+    if (supports_reasoning) {
+        autoparser::generation_params probe;
+        probe.messages              = json::array({ { { "role", "user" }, { "content", "x" } } });
+        probe.add_generation_prompt = true;
+        probe.enable_thinking       = false;
+        try {
+            compact_think = string_ends_with(common_chat_template_generation_prompt(tmpl, probe), "<think></think>");
+        } catch (const std::exception &) {
+            // a template that cannot render without thinking keeps the default layout
+        }
+    }
+
     if (supports_reasoning) {
         data.thinking_start_tag = "<think>";
         // Support both </think> and <tool_call> as reasoning end sequences.
         // The newline variant comes first so it is included in the forced message
         // <function= is omitted, as it is a workaround for Qwen3-Coder which is not a thinking model
         data.thinking_end_tags = { "\n</think>", "</think>", "<tool_call>" };
+        if (compact_think) {
+            data.thinking_end_tags = { "</think>", "<tool_call>" };
+        }
         data.preserved_tokens.insert(data.preserved_tokens.end(), { "<think>", "</think>" });
     }

@@ -33,6 +51,7 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
         { COMMON_CHAT_ROLE_ASSISTANT, "<|im_start|>assistant"             },
         { COMMON_CHAT_ROLE_TOOL,      "<|im_start|>user\n<tool_response>" }, // Qwen3-Coder, Qwen3.5, Nemotron Nano 3
         { COMMON_CHAT_ROLE_TOOL,      "<|im_start|>tool_response"         }, // StepFun-3.5-Flash
+        { COMMON_CHAT_ROLE_TOOL,      "<|im_start|>tool\n"                }, // Qwen4
         { COMMON_CHAT_ROLE_USER,      "<|im_start|>user"                  },
         { COMMON_CHAT_ROLE_SYSTEM,    "<|im_start|>system"                },
     };
@@ -47,9 +66,9 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat

         data.generation_prompt = GEN_PREFIX;
         if (supports_reasoning) {
-            data.generation_prompt += "<think>\n" + msg.reasoning_content;
+            data.generation_prompt += (compact_think ? "<think>" : "<think>\n") + msg.reasoning_content;
             if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
-                data.generation_prompt += "\n</think>\n\n";
+                data.generation_prompt += compact_think ? "</think>" : "\n</think>\n\n";
             }
         }
         if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
diff --git a/conversion/__init__.py b/conversion/__init__.py
index b177a6d83..879efb2ff 100644
--- a/conversion/__init__.py
+++ b/conversion/__init__.py
@@ -309,6 +309,10 @@ TEXT_MODEL_MAP: dict[str, str] = {
     "Qwen3_5TextModel": "qwen",
     "Qwen4ExpForCausalLM": "qwen4exp",
     "Qwen4ExpForConditionalGeneration": "qwen4exp",
+    "Qwen4MoeForCausalLM": "qwen4exp",
+    "Qwen4MoeForConditionalGeneration": "qwen4exp",
+    "Qwen4ForCausalLM": "qwen4exp",
+    "Qwen4ForConditionalGeneration": "qwen4exp",
     "RND1": "qwen",
     "RWForCausalLM": "falcon",
     "RWKV6Qwen2ForCausalLM": "rwkv",
@@ -455,6 +459,8 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
     "Qwen3_5ForConditionalGeneration": "qwen3vl",
     "Qwen3_5MoeForConditionalGeneration": "qwen3vl",
     "Qwen4ExpForConditionalGeneration": "qwen4exp",
+    "Qwen4MoeForConditionalGeneration": "qwen4exp",
+    "Qwen4ForConditionalGeneration": "qwen4exp",
     "RADIOModel": "nemotron",
     "Sarashina2VisionForCausalLM": "sarashina2",
     "SmolVLMForConditionalGeneration": "smolvlm",
diff --git a/conversion/qwen4exp.py b/conversion/qwen4exp.py
index 8eac47275..409fe405c 100644
--- a/conversion/qwen4exp.py
+++ b/conversion/qwen4exp.py
@@ -1,5 +1,6 @@
 from __future__ import annotations

+import json
 from typing import Iterable, cast

 import torch
@@ -13,7 +14,9 @@ from .qwen import _LinearAttentionVReorderBase, _Qwen35MRopeMixin
 from .qwen3vl import Qwen3VLVisionModel


-@ModelBase.register("Qwen4ExpForConditionalGeneration", "Qwen4ExpForCausalLM")
+@ModelBase.register("Qwen4ExpForConditionalGeneration", "Qwen4ExpForCausalLM",
+                    "Qwen4MoeForConditionalGeneration", "Qwen4MoeForCausalLM",
+                    "Qwen4ForConditionalGeneration", "Qwen4ForCausalLM")
 @ModelBase.example("Qwen/Qwen3.8-Flash-Next")
 class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
     """Qwen3.8-Flash-Next.
@@ -54,6 +57,29 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
                 self._ple_scale = float(scale[0])
         super().dequant_model()

+    def set_vocab(self):
+        # no tokenizer.json at the root: load the one in tokenizer-compat/
+        compat = self.dir_model / "tokenizer-compat"
+        if (self.dir_model / "tokenizer.json").is_file() or not (compat / "tokenizer.json").is_file():
+            super().set_vocab()
+            return
+        dir_model = self.dir_model
+        self.dir_model = compat
+        try:
+            super().set_vocab()
+        finally:
+            self.dir_model = dir_model
+
+    def get_vocab_base_pre(self, tokenizer) -> str:
+        res = super().get_vocab_base_pre(tokenizer)
+        # Qwen4 hashes like Qwen3.5 but is tiktoken-encoded (ignore_merges)
+        tokenizer_json = self.dir_model / "tokenizer.json"
+        if res == "qwen35" and tokenizer_json.is_file():
+            with open(tokenizer_json, encoding="utf-8") as f:
+                if json.load(f).get("model", {}).get("ignore_merges"):
+                    res = "qwen4"
+        return res
+
     def _has_fp8_source_scale(self, name: str) -> bool:
         if ".ngram_embedding.shard_" in name:
             prefix = name.split(".ngram_embedding.shard_")[0]
@@ -102,14 +128,14 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
         layer_types = hp["layer_types"]
         # the MTP block is a full-attention QSA layer too
         self.gguf_writer.add_attention_compress_ratios(
-            [ratio if layer_types[i] == "full_attention" else 0 for i in range(n_layer)]
+            [0 if layer_types[i] == "linear_attention" else ratio for i in range(n_layer)]
             + [ratio] * (self.block_count - n_layer)
         )

         # ple_layer_ids is 1-based in the HF config; empty means no n-gram table,
         # so emit no PLE keys rather than optional ones
         # the MTP head never reads PLE, so an MTP-only file carries none of it
-        ple_layers = [i - 1 for i in hp["ple_layer_ids"]]
+        ple_layers = [i - 1 for i in hp.get("ple_layer_ids") or []]
         if not ple_layers or self.mtp_only:
             return
         self.gguf_writer.add_ple_layers(ple_layers)
@@ -259,7 +285,7 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
             )


-@ModelBase.register("Qwen4ExpForConditionalGeneration")
+@ModelBase.register("Qwen4ExpForConditionalGeneration", "Qwen4MoeForConditionalGeneration", "Qwen4ForConditionalGeneration")
 @ModelBase.example("Qwen/Qwen3.8-Flash-Next")
 class Qwen4ExpVisionModel(Qwen3VLVisionModel):
     """The vision tower is an unmodified Qwen3-VL ViT."""
diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py
index d2b4c86b2..16ee0e640 100644
--- a/gguf-py/gguf/constants.py
+++ b/gguf-py/gguf/constants.py
@@ -3984,6 +3984,9 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
         MODEL_TENSOR.SSM_BETA,
         MODEL_TENSOR.SSM_ALPHA,
         MODEL_TENSOR.SSM_OUT,
+        MODEL_TENSOR.FFN_GATE,
+        MODEL_TENSOR.FFN_UP,
+        MODEL_TENSOR.FFN_DOWN,
         MODEL_TENSOR.FFN_GATE_INP,
         MODEL_TENSOR.FFN_GATE_INP_SHEXP,
         MODEL_TENSOR.FFN_UP_SHEXP,
diff --git a/models/templates/Qwen4-35B-A3B.jinja b/models/templates/Qwen4-35B-A3B.jinja
new file mode 100644
index 000000000..88f39cd16
--- /dev/null
+++ b/models/templates/Qwen4-35B-A3B.jinja
@@ -0,0 +1,220 @@
+{#- Qwen4 Jinja chat template for compatibility only. Deliberate omissions:
+    - tool-result ordering is limited to text-only runs with explicit tool_call_id.
+      Media runs keep input order: HF collects media before rendering this template.
+      Missing/null tool_call_id never falls back to id: newer HF versions strip null
+      fields before rendering, so these cases cannot be distinguished here.
+      For full Python ordering semantics, reorder messages before media collection.
+    - tool_calls[].function.arguments is only read as a dict; other types cause exceptions.
+    - no anti-injection: the encoder tokenizes data with allow_special=false, so message
+      text can never become a control token. A flat string cannot express that, and
+      re-tokenizing it does not reproduce the encoder's token ids -- use the Qwen4
+      tokenizer's apply_chat_template(tokenize=True) for exact ids.
+    - the generation blocks (return_assistant_tokens_mask) cover a whole assistant
+      body; the encoder additionally masks out media placeholders inside it.
+-#}
+{%- macro render_content(content) -%}
+    {%- if content is string -%}
+        {{- content -}}
+    {%- elif content is iterable and content is not mapping -%}
+        {%- for item in content -%}
+            {%- if item is string -%}
+                {{- item -}}
+            {%- elif item.get('type') == 'text' -%}
+                {{- item.get('text', '') | default('', true) -}}
+            {%- elif item.get('type') in ('image', 'image_url') -%}
+                {{- '<|vision_start|><|image_pad|><|vision_end|>' -}}
+            {%- elif item.get('type') in ('video', 'video_url') -%}
+                {{- '<|vision_start|><|video_pad|><|vision_end|>' -}}
+            {%- elif item.get('type') in ('audio', 'audio_url') -%}
+                {{- '<|audio_start|><|audio_pad|><|audio_end|>' -}}
+            {%- else -%}
+                {{- raise_exception('Unexpected content part type ' ~ item.get('type') ~ '. Supported types are text, image, image_url, video, video_url, audio and audio_url.') -}}
+            {%- endif -%}
+        {%- endfor -%}
+    {%- elif content is not none -%}
+        {{- content | tojson -}}
+    {%- endif -%}
+{%- endmacro -%}
+{%- macro render_reasoning(reasoning) -%}
+    {%- if reasoning is string -%}
+        {{- reasoning -}}
+    {%- elif reasoning is iterable and reasoning is not mapping -%}
+        {%- for item in reasoning -%}
+            {%- if item is string -%}
+                {{- item -}}
+            {%- elif item.get('type') in (none, 'text') -%}
+                {{- item.get('text', '') | default('', true) -}}
+            {%- else -%}
+                {{- item | tojson -}}
+            {%- endif -%}
+        {%- endfor -%}
+    {%- elif reasoning is not none -%}
+        {{- reasoning | tojson -}}
+    {%- endif -%}
+{%- endmacro -%}
+{%- macro render_tools(tools) -%}
+    {{- '# 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' -}}
+    {%- for tool in tools -%}
+        {%- if tool is not mapping -%}
+            {{- raise_exception('Unexpected tool spec ' ~ tool ~ '. Expected a function schema dict.') -}}
+        {%- elif tool.get('type') == 'function' and 'function' in tool -%}
+            {{- tool | tojson -}}
+        {%- elif 'function' in tool -%}
+            {{- ({'type': 'function', 'function': tool['function']}) | tojson -}}
+        {%- else -%}
+            {{- ({'type': 'function', 'function': tool}) | tojson -}}
+        {%- endif -%}
+        {{- '\n' -}}
+    {%- endfor -%}
+    {{- '</tools>\n\nIf you choose to call a function, use exactly this format:\n' -}}
+    {{- '<tool_call>\n<function={function-name}>\n<parameter={parameter-name}>\n{parameter-value}\n</parameter>\n</function>\n</tool_call>' -}}
+{%- endmacro -%}
+{%- macro render_tool_calls(tool_calls) -%}
+    {%- for tool_call in tool_calls -%}
+        {%- if tool_call.function is mapping -%}
+            {%- set name = tool_call.function.get('name', '') -%}
+            {%- set arguments = tool_call.function.get('arguments') -%}
+        {%- else -%}
+            {%- set name = tool_call.get('name', '') -%}
+            {%- set arguments = tool_call.get('arguments') -%}
+        {%- endif -%}
+        {{- '<tool_call>\n<function=' ~ name ~ '>\n' -}}
+        {%- if arguments is mapping -%}
+            {%- for arg_name, arg_value in arguments | items -%}
+                {{- '<parameter=' ~ (arg_name if arg_name is string else arg_name | tojson) ~ '>\n' -}}
+                {{- arg_value if arg_value is string else arg_value | tojson -}}
+                {{- '\n</parameter>\n' -}}
+            {%- endfor -%}
+        {%- elif arguments is not none and (arguments is not string or (arguments | trim) != '')  -%}
+            {{- raise_exception('Unexpected argument types. Expected dict.') -}}
+        {%- endif -%}
+        {{- '</function>\n</tool_call>' -}}
+    {%- endfor -%}
+{%- endmacro -%}
+{%- set enable_thinking = enable_thinking | default(none) -%}
+{%- if enable_thinking is not none and enable_thinking is not boolean -%}
+    {{- raise_exception('Unexpected enable_thinking ' ~ enable_thinking ~ '. Expected true, false or none.') -}}
+{%- endif -%}
+{%- set reasoning_effort = reasoning_effort | default(none) -%}
+{%- if reasoning_effort is not none and reasoning_effort not in ('xhigh', 'high', 'low', 'off') -%}
+    {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported efforts are xhigh, high, low and off.') -}}
+{%- endif -%}
+{%- if enable_thinking is none -%}
+    {%- set effort = reasoning_effort if reasoning_effort is not none else 'high' -%}
+{%- elif enable_thinking -%}
+    {%- if reasoning_effort == 'off' -%}
+        {{- raise_exception('Conflicting thinking settings: enable_thinking=true with reasoning_effort=off.') -}}
+    {%- endif -%}
+    {%- set effort = reasoning_effort if reasoning_effort is not none else 'high' -%}
+{%- else -%}
+    {%- if reasoning_effort is not none and reasoning_effort != 'off' -%}
+        {{- raise_exception('Conflicting thinking settings: enable_thinking=false with reasoning_effort=' ~ reasoning_effort ~ '.') -}}
+    {%- endif -%}
+    {%- set effort = 'off' -%}
+{%- endif -%}
+{%- set preserve_thinking = preserve_thinking | default(true) -%}
+{%- if preserve_thinking is not none and preserve_thinking is not boolean -%}
+    {{- raise_exception('Unexpected preserve_thinking ' ~ preserve_thinking ~ '. Expected true, false or none.') -}}
+{%- endif -%}
+{%- set preserve_thinking = true if preserve_thinking is none else preserve_thinking -%}
+{{- '<|im_start|>system\n' + 'Reasoning effort is set to ' + effort + '.' -}}
+{%- if tools -%}
+    {{- '\n\n' -}}
+    {{- render_tools(tools) -}}
+{%- endif -%}
+{{- '<|im_end|>\n' -}}
+{#- Sort text-only tool-result runs only when every explicit tool_call_id resolves. -#}
+{%- set order = namespace(messages=[], call_ids=[], pending=[], unresolved=false) -%}
+{%- for message in messages + [none] -%}
+    {%- if message is none or message.get('role') != 'tool' -%}
+        {%- if not order.unresolved -%}
+            {%- set order.pending = order.pending | sort(attribute='position') -%}
+        {%- endif -%}
+        {%- for item in order.pending -%}
+            {%- set order.messages = order.messages + [item.message] -%}
+        {%- endfor -%}
+        {%- set order.pending = [] -%}
+        {%- set order.unresolved = false -%}
+        {%- if message is not none -%}
+            {%- if message.get('role') == 'assistant' -%}
+                {%- set order.call_ids = [] -%}
+                {%- for call in message.get('tool_calls') or [] -%}
+                    {%- if call is mapping and call.get('id') is not none -%}
+                        {%- set order.call_ids = order.call_ids + [call.id | string] -%}
+                    {%- endif -%}
+                {%- endfor -%}
+            {%- endif -%}
+            {%- set order.messages = order.messages + [message] -%}
+        {%- endif -%}
+    {%- else -%}
+        {#- Do not reorder media independently of the processor's already-collected inputs. -#}
+        {%- set content = message.get('content') -%}
+        {%- if content is iterable and content is not string and content is not mapping -%}
+            {%- for part in content -%}
+                {%- if part is not string and (part is not mapping or part.get('type') != 'text') -%}
+                    {%- set order.unresolved = true -%}
+                {%- endif -%}
+            {%- endfor -%}
+        {%- elif content is not none and content is not string -%}
+            {%- set order.unresolved = true -%}
+        {%- endif -%}
+        {%- set cid = message.get('tool_call_id') -%}
+        {%- set match = namespace(position=none) -%}
+        {%- for call_id in order.call_ids -%}
+            {%- if cid is not none and call_id == (cid | string) and match.position is none -%}
+                {%- set match.position = loop.index0 -%}
+            {%- endif -%}
+        {%- endfor -%}
+        {%- if match.position is none -%}
+            {%- set order.unresolved = true -%}
+        {%- endif -%}
+        {%- set order.pending = order.pending + [{'position': match.position, 'message': message}] -%}
+    {%- endif -%}
+{%- endfor -%}
+{%- set messages = order.messages -%}
+{#- with preserve_thinking=false, reasoning survives only on and after the last user turn -#}
+{%- set ns = namespace(last_user=-1) -%}
+{%- if not preserve_thinking -%}
+    {%- for message in messages -%}
+        {%- if message.get('role') == 'user' -%}
+            {%- set ns.last_user = loop.index0 -%}
+        {%- endif -%}
+    {%- endfor -%}
+{%- endif -%}
+{%- for message in messages -%}
+    {%- set role = 'system' if message.get('role') == 'developer' else message.get('role') -%}
+    {%- if role in ('system', 'user') -%}
+        {{- '<|im_start|>' + role + '\n' + render_content(message.get('content')) + '<|im_end|>\n' -}}
+    {%- elif role == 'assistant' -%}
+        {%- if not preserve_thinking and loop.index0 < ns.last_user -%}
+            {%- set reasoning = '' -%}
+        {%- elif 'reasoning_content' in message -%}
+            {%- set reasoning = render_reasoning(message['reasoning_content']) | trim -%}
+        {%- elif 'reasoning' in message -%}
+            {%- set reasoning = render_reasoning(message['reasoning']) | trim -%}
+        {%- else -%}
+            {%- set reasoning = '' -%}
+        {%- endif -%}
+        {%- set content = render_content(message.get('content')) | trim -%}
+        {{- '<|im_start|>assistant\n' -}}
+        {%- generation -%}
+        {{- '<think>' + reasoning + '</think>' + content -}}
+        {%- if message.get('tool_calls') -%}
+            {{- render_tool_calls(message['tool_calls']) -}}
+        {%- endif -%}
+        {{- '<|im_end|>' -}}
+        {%- endgeneration -%}
+        {{- '\n' -}}
+    {%- elif role == 'tool' -%}
+        {{- '<|im_start|>tool\n' + render_content(message.get('content')) + '\n<|im_end|>\n' -}}
+    {%- else -%}
+        {{- raise_exception('Unexpected message role ' ~ message.get('role') ~ '. Supported roles are system, developer, user, assistant and tool.') -}}
+    {%- endif -%}
+{%- endfor -%}
+{%- if add_generation_prompt -%}
+    {{- '<|im_start|>assistant\n' -}}
+    {{- '<think>' -}}
+    {%- if effort == 'off' -%}
+        {{- '</think>' -}}
+    {%- endif -%}
+{%- endif -%}
diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp
index 674daaa23..8b9356684 100644
--- a/src/llama-vocab.cpp
+++ b/src/llama-vocab.cpp
@@ -2582,6 +2582,11 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
                     tokenizer_pre == "qwen35") {
                 pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35;
                 clean_spaces = false;
+            } else if (
+                    tokenizer_pre == "qwen4") {
+                pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35;
+                ignore_merges = true;
+                clean_spaces = false;
             } else if (
                 tokenizer_pre == "stablelm2") {
                 pre_type = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp
index a6bc485a9..e88a12ee9 100644
--- a/src/models/qwen4exp.cpp
+++ b/src/models/qwen4exp.cpp
@@ -166,6 +166,7 @@ void llama_model_qwen4exp::load_arch_hparams(llama_model_loader & ml) {
     }

     switch (hparams.n_layer()) {
+        case 40: type = LLM_TYPE_35B_A3B; break;
         case 48: type = LLM_TYPE_A3B; break;
         default: type = LLM_TYPE_UNKNOWN;
     }
@@ -225,7 +226,7 @@ void llama_model_qwen4exp::load_arch_tensors(llama_model_loader & ml) {
     auto load_block = [&](int il, int flags) {
         auto & layer = layers[il];

-        const int64_t n_ff_exp   = hparams.n_ff_exp() ? hparams.n_ff_exp() : n_ff / n_expert_used;
+        const int64_t n_ff_exp   = hparams.n_ff_exp() ? hparams.n_ff_exp() : n_ff / std::max<int64_t>(n_expert_used, 1);
         const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;

         const int64_t head_k_dim = hparams.ssm_d_state;
@@ -297,6 +298,13 @@ void llama_model_qwen4exp::load_arch_tensors(llama_model_loader & ml) {
             layer.ple_conv1d     = create_tensor(tn(LLM_TENSOR_PLE_CONV1D,     "weight", il), { hparams.ple_conv_kernel, 1, hc_dim }, flags | TENSOR_ALLOW_RESHAPE);
         }

+        if (n_expert == 0) {
+            layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", il), { n_embd, hparams.n_ff(il) }, flags);
+            layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", il), { n_embd, hparams.n_ff(il) }, flags);
+            layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", il), { hparams.n_ff(il), n_embd }, flags);
+            return;
+        }
+
         layer.ffn_gate_inp  = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,  "weight", il), { n_embd, n_expert }, flags);
         layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", il), { n_ff_exp, n_embd, n_expert }, flags);
         create_tensor_gate_up_exps(layer, il, n_embd, n_ff_exp, n_expert, flags);
@@ -1217,7 +1225,16 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_attn_linear(
 }

 ggml_tensor * llama_model_qwen4exp::graph::build_layer_ffn(ggml_tensor * cur, const int il) {
-    GGML_ASSERT(model.layers[il].ffn_gate_inp != nullptr);
+    if (model.layers[il].ffn_gate_inp == nullptr) {
+        cur = build_ffn(cur,
+            model.layers[il].ffn_up,   NULL,
+            model.layers[il].ffn_gate, NULL,
+            model.layers[il].ffn_down, NULL,
+            NULL,
+            LLM_FFN_SILU, LLM_FFN_PAR, il);
+        cb(cur, "ffn_out", il);
+        return cur;
+    }

     ggml_tensor * moe_out =
         build_moe_ffn(cur,
diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp
index 63faaa5b4..fcd9bde5e 100644
--- a/tests/test-chat.cpp
+++ b/tests/test-chat.cpp
@@ -2903,6 +2903,77 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
         }
     }

+    {
+        // Qwen4: Qwen3-Coder tool calls, compact "<think>...</think>" with no separators
+        auto tst = peg_tester("models/templates/Qwen4-35B-A3B.jinja", detailed_debug);
+        tst.specials(qwen3_coder_specials);
+
+        tst.test("I'm\nthinking</think>Hello, world!\nWhat's up?")
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .enable_thinking(true)
+            .expect(message_assist_thoughts)
+            .run();
+
+        tst.test("I'm\nthinking</think>Hello, world!\nWhat's up?")
+            .enable_thinking(true)
+            .reasoning_format(COMMON_REASONING_FORMAT_NONE)
+            .expect_content("<think>I'm\nthinking</think>Hello, world!\nWhat's up?")
+            .run();
+
+        tst.test("Hello, world!\nWhat's up?")
+            .enable_thinking(false)
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .expect(message_assist)
+            .run();
+
+        tst.test(
+               "I'm\nthinking</think>"
+               "<tool_call>\n"
+               "<function=special_function>\n"
+               "<parameter=arg1>\n1\n</parameter>\n"
+               "</function>\n"
+               "</tool_call>")
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .enable_thinking(true)
+            .tools({ special_function_tool })
+            .expect(message_assist_call_thoughts)
+            .run();
+
+        tst.test(
+               "<tool_call>\n"
+               "<function=special_function>\n"
+               "<parameter=arg1>\n1\n</parameter>\n"
+               "</function>\n"
+               "</tool_call>"
+               "<tool_call>\n"
+               "<function=special_function_with_opt>\n"
+               "<parameter=arg1>\n1\n</parameter>\n"
+               "<parameter=arg2>\n2\n</parameter>\n"
+               "</function>\n"
+               "</tool_call>")
+            .enable_thinking(false)
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .parallel_tool_calls(true)
+            .tools({
+                special_function_tool, special_function_tool_with_optional_param
+        })
+            .expect_tool_calls({
+                { "special_function", R"({"arg1": 1})", {} },
+                { "special_function_with_opt", R"({"arg1": 1, "arg2": 2})", {} },
+            })
+            .run();
+
+        tst.test(
+               "I need to output the invoice details in JSON</think>"
+               R"({"amount": 123.45, "date": "2025-12-03"})")
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .enable_thinking(true)
+            .json_schema(invoice_schema)
+            .expect_reasoning("I need to output the invoice details in JSON")
+            .expect_content(R"({"amount": 123.45, "date": "2025-12-03"})")
+            .run();
+    }
+
     {
         // Ministral-3-14B-Reasoning-2512
         auto tst = peg_tester("models/templates/mistralai-Ministral-3-14B-Reasoning-2512.jinja", detailed_debug);
@@ -8639,6 +8710,13 @@ static void test_template_generation_prompt() {
         assert_ends_with(params.prompt.str(), expected_generation_prompt);
     };

+    {
+        auto tmpls = read_templates("models/templates/Qwen4-35B-A3B.jinja");
+        check(tmpls, basic(),                  "<|im_start|>assistant\n<think>");
+        check(tmpls, continuation_content(),   "<|im_start|>assistant\n<think>I'm thinking</think>Hello, ");
+        check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n<think>I'm");
+    }
+
     {
         auto tmpls = read_templates("models/templates/Qwen3.5-4B.jinja");
         check(tmpls, basic(),                  "<|im_start|>assistant\n<think>\n");
@@ -9597,6 +9675,71 @@ static void test_chat_session() {
     }
 }

+// Qwen4 writes "<think>" + reasoning + "</think>" + content with no separators
+static void test_qwen4_chat_session() {
+    LOG_DBG("%s\n", __func__);
+    auto tmpls = read_templates("models/templates/Qwen4-35B-A3B.jinja");
+
+    common_chat_templates_inputs inputs;
+    inputs.messages         = { message_user };
+    inputs.tools            = { special_function_tool };
+    inputs.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
+
+    {
+        common_chat_session session(tmpls.get(), nullptr, inputs);
+        assert_equals(std::string("<|im_start|>assistant\n<think>"), session.generation_prompt());
+        // the reasoning budget closes with the bare tag, the template never writes a newline before it
+        assert_equals(json(std::vector<std::string>{ "</think>", "<tool_call>" }).dump(), json(session.thinking_end_tags()).dump());
+
+        const std::string output =
+            "I'm\nthinking</think>"
+            "Let me check."
+            "<tool_call>\n"
+            "<function=special_function>\n"
+            "<parameter=arg1>\n1\n</parameter>\n"
+            "</function>\n"
+            "</tool_call>";
+        for (size_t i = 0; i < output.size(); i += 3) {
+            session.feed(common_chat_input(output.substr(i, 3)));
+        }
+        assert_msg_equals(simple_assist_msg("Let me check.", "I'm\nthinking", "special_function", "{\"arg1\":1}"), session.finish());
+    }
+
+    // thinking off renders an empty think block, the output is content only
+    {
+        common_chat_templates_inputs off = inputs;
+        off.enable_thinking = false;
+        common_chat_session session(tmpls.get(), nullptr, off);
+        assert_equals(std::string("<|im_start|>assistant\n<think></think>"), session.generation_prompt());
+        session.feed(common_chat_input("Hello, world!"));
+        assert_msg_equals(simple_assist_msg("Hello, world!"), session.finish());
+    }
+
+    // a continued message is written back the way the template renders it
+    {
+        common_chat_templates_inputs cont;
+        cont.messages               = { message_user, message_assist_prefill_content };
+        cont.add_generation_prompt  = false;
+        cont.continue_final_message = COMMON_CHAT_CONTINUATION_CONTENT;
+        cont.reasoning_format       = COMMON_REASONING_FORMAT_AUTO;
+
+        common_chat_session session(tmpls.get(), nullptr, cont);
+        assert_equals(std::string("<|im_start|>assistant\n<think>I'm thinking</think>Hello, "), session.generation_prompt());
+        session.feed(common_chat_input("world!"));
+        assert_msg_equals(simple_assist_msg("Hello, world!", "I'm thinking"), session.msg());
+    }
+
+    // tool results are their own turn, "<|im_start|>tool"
+    {
+        bool found = false;
+        common_chat_session session(tmpls.get(), nullptr, inputs);
+        for (const auto & d : session.message_delimiters().delimiters) {
+            found |= d.role == COMMON_CHAT_ROLE_TOOL && d.delimiter == "<|im_start|>tool\n";
+        }
+        assert_equals(true, found);
+    }
+}
+
 static void test_chat_json_depth() {
     LOG_DBG("%s\n", __func__);
     const auto arrays = [](size_t n) {
@@ -9747,6 +9890,7 @@ static void test_reasoning_effort_caps() {
     assert_effort_levels("models/templates/muse-spark.jinja", { "minimal", "low", "medium", "high" });
     assert_effort_levels("models/templates/upstage-Solar-Open-100B.jinja", { "low" });
     assert_effort_levels("models/templates/muse-glimmer.jinja", all_levels);
+    assert_effort_levels("models/templates/Qwen4-35B-A3B.jinja", { "low", "high", "xhigh" });
     assert_effort_levels("models/templates/openai-gpt-oss-120b.jinja", all_levels);
     assert_effort_levels("models/templates/Cohere2MoE.jinja", { "none" });
     assert_effort_levels("models/templates/thinkingmachines-Inkling-2-Small.jinja", { "none", "minimal", "low", "medium", "high", "max" });
@@ -9931,6 +10075,7 @@ int main(int argc, char ** argv) {
         test_reasoning_effort_caps();
         test_prompt_parts();
         test_chat_session();
+        test_qwen4_chat_session();
         test_chat_json_depth();
         test_reasoning_budget_tokens_per_request();
         test_reasoning_budget_message_per_request();
diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp
index 5097c60ca..af3ecd6cd 100644
--- a/tools/server/server-common.cpp
+++ b/tools/server/server-common.cpp
@@ -1650,11 +1650,11 @@ json oaicompat_chat_params_parse(
         throw std::invalid_argument("invalid type for \"enable_thinking\" (expected boolean, got string)");
     }

-    // Parse the OAI "reasoning_effort" field; "none" disables reasoning.
+    // Parse the OAI "reasoning_effort" field; "none" (or "off") disables reasoning.
     if (body.contains("reasoning_effort")) {
         auto reasoning_effort = json_value(body, "reasoning_effort", std::string(""));
         const auto levels = caps.at("reasoning_effort_levels").get<std::vector<std::string>>();
-        if (reasoning_effort == "none") {
+        if (reasoning_effort == "none" || reasoning_effort == "off") {
             inputs.enable_thinking = false;
             // Some models use reasoning_effort = none and some throw an exception, so check the model's list of effort levels first
             if (std::find(levels.begin(), levels.end(), reasoning_effort) != levels.end()) {