Commit a3f7cb2b9 for llama.cpp

commit a3f7cb2b9af09a001c9be9c9bc04b7de87162f9c
Author: MichelRosselli <71264400+MichelRosselli@users.noreply.github.com>
Date:   Tue Dec 1 11:35:03 2026 +0100

    model : add Apertus v1.5 text support (#32880)

    * apertus : add v1.5 text support and vocabulary validation

    Assisted-by: Codex

    * chat : add Apertus v1.5 template and tool-call parsing

    Assisted-by: Codex

    * mtmd : add Apertus vision support and discrete token transport

    Assisted-by: Codex

    * mtmd : add Apertus audio support

    Assisted-by: Codex

    * chat : fix Apertus v1.5 tool-call termination

    Assisted-by: Codex

    * convert : support both Apertus v1.5 checkpoint layouts

    Support the original Swiss AI checkpoint layout published on Hugging Face
    and the layout from the in-progress Hugging Face Transformers integration
    (PR #47662, revision 0c5e12f18a5f).

    Assisted-by: Codex

    * mtmd : preserve Apertus audio capacity on allocation failure

    Update graph capacity only after buffer and scheduler growth succeeds.

    Assisted-by: Codex

    * mtmd : align Apertus image preprocessing with HF training pipeline

    Read pixel limits from either processor metadata layout.
    Match the resize policy confirmed in Transformers PR #47662.

    Assisted-by: Codex

    * apertus : clean up comments and naming after upstream merge

    Remove duplicate test includes and align the embedding-width variable
    with the mmproj naming.

    Assisted-by: Codex

    * mtmd : use extended batches for discrete media decoding

    Replace deprecated batch calls and preserve post-decode token callbacks.
    Validate media position counts without signedness warnings.

    Assisted-by: Codex

    * tests : avoid Windows macro collision in Apertus image test

    Assisted-by: Codex

    * apertus : separate converters and keep architecture tests generic

    Remove model-specific usage documentation and align projector constants.

    Assisted-by: Codex

    * apertus : defer multimodal support to a separate PR

    Keep text conversion, inference, chat and related tests in this PR.

    Assisted-by: Codex

    * apertus : align formatting with surrounding code

    Assisted-by: Codex

diff --git a/common/chat.cpp b/common/chat.cpp
index 7ec670f30..f7e35e441 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -1377,6 +1377,13 @@ static common_chat_params common_chat_params_init_lfm2_5(const common_chat_templ
 // Pick the dedicated handler for a template from its source, or null for the autoparser.
 // Order matters: the first match wins, and later checks assume the earlier ones did not match.
 static common_chat_params_init_fn common_chat_template_detect_params_init(const std::string & src) {
+    if (src.find("You are Apertus 1.5 Omni") != std::string::npos &&
+        src.find("<|inner_prefix|>") != std::string::npos &&
+        src.find("<|tools_prefix|>") != std::string::npos) {
+        LOG_DBG("Using specialized template: Apertus 1.5\n");
+        return common_chat_params_init_apertus_1_5;
+    }
+
     // Ministral/Mistral Large 3 - uses special reasoning structure fixes, can't use autoparser
     // Note: Mistral Small 3.2 uses [CALL_ID] which Ministral doesn't have, so we can distinguish them
     if (src.find("[SYSTEM_PROMPT]") != std::string::npos && src.find("[TOOL_CALLS]") != std::string::npos &&
diff --git a/common/parsers/apertus.cpp b/common/parsers/apertus.cpp
new file mode 100644
index 000000000..974d9689f
--- /dev/null
+++ b/common/parsers/apertus.cpp
@@ -0,0 +1,171 @@
+#include "parsers.h"
+
+// Normalize assistant history to content.blocks: the template rejects mixed string and block formats.
+static json apertus_1_5_adjust_messages(const json & messages) {
+    json adjusted = json::array();
+
+    for (const auto & message : messages) {
+        if (message.value("role", "") != "assistant") {
+            adjusted.push_back(message);
+            continue;
+        }
+
+        json blocks = json::array();
+
+        if (message.contains("reasoning_content") && message.at("reasoning_content").is_string()) {
+            const auto reasoning = message.at("reasoning_content").get<std::string>();
+            if (!reasoning.empty()) {
+                blocks.push_back({
+                    { "type", "thoughts" },
+                    { "text", reasoning },
+                });
+            }
+        }
+
+        if (message.contains("content") && message.at("content").is_string()) {
+            const auto content = message.at("content").get<std::string>();
+            if (!content.empty()) {
+                blocks.push_back({
+                    { "type", "response" },
+                    { "text", content },
+                });
+            }
+        }
+
+        if (message.contains("tool_calls") && message.at("tool_calls").is_array() &&
+            !message.at("tool_calls").empty()) {
+            blocks.push_back({
+                { "type", "tool_calls" },
+                { "calls", message.at("tool_calls") },
+            });
+        }
+
+        json converted = message;
+        converted["content"] = {
+            { "blocks", std::move(blocks) },
+        };
+        converted.erase("reasoning_content");
+        converted.erase("tool_calls");
+        adjusted.push_back(std::move(converted));
+    }
+
+    return adjusted;
+}
+
+// Apertus 1.5 format:
+// - reasoning: <|inner_prefix|>{reasoning}<|inner_suffix|>
+// - tool calls: <|tools_prefix|>[{"function_name": { ... }}]<|tools_suffix|>
+common_chat_params common_chat_params_init_apertus_1_5(
+        const common_chat_template &          tmpl,
+        const autoparser::generation_params & inputs) {
+    static const std::string ASSISTANT_START = "<|assistant_start|>";
+    static const std::string INNER_START     = "<|inner_prefix|>";
+    static const std::string INNER_END       = "<|inner_suffix|>";
+    static const std::string TOOLS_START     = "<|tools_prefix|>";
+    static const std::string TOOLS_END       = "<|tools_suffix|>";
+
+    common_chat_params data;
+
+    auto adjusted_messages = apertus_1_5_adjust_messages(inputs.messages);
+    data.prompt             = common_chat_template_direct_apply_impl(tmpl, inputs, adjusted_messages);
+    data.generation_prompt  = common_chat_template_generation_prompt_impl(tmpl, inputs, adjusted_messages);
+    data.format             = COMMON_CHAT_FORMAT_PEG_NATIVE;
+    data.supports_thinking  = true;
+    data.thinking_start_tag = INNER_START;
+    data.thinking_end_tags  = {INNER_END};
+    data.preserved_tokens   = {
+        INNER_START,
+        INNER_END,
+        TOOLS_START,
+        TOOLS_END,
+    };
+    data.message_delimiters = {
+        { COMMON_CHAT_ROLE_ASSISTANT, ASSISTANT_START         },
+        { COMMON_CHAT_ROLE_TOOL,      "<|tool_output_start|>" },
+        { COMMON_CHAT_ROLE_USER,      "<|user_start|>"        },
+        { COMMON_CHAT_ROLE_SYSTEM,    "<|system_start|>"      },
+    };
+
+    if (inputs.has_continuation()) {
+        const auto & message = inputs.continue_msg;
+
+        data.generation_prompt = ASSISTANT_START;
+        if (!message.reasoning_content.empty()) {
+            data.generation_prompt += INNER_START + message.reasoning_content;
+            if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
+                data.generation_prompt += INNER_END;
+            }
+        }
+        if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
+            data.generation_prompt += message.render_content();
+        }
+
+        data.prompt.append(data.generation_prompt);
+    }
+
+    const bool has_tools = inputs.tools.is_array() && !inputs.tools.empty() &&
+                           inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
+    const bool has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
+    const bool extract_reasoning   = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
+    const bool include_grammar     = has_response_format || has_tools;
+
+    data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
+        auto generation_prompt = p.literal(ASSISTANT_START);
+        auto end               = p.end();
+
+        auto reasoning = p.eps();
+        if (extract_reasoning) {
+            reasoning = p.optional(
+                p.literal(INNER_START) + p.reasoning(p.until(INNER_END)) + p.literal(INNER_END));
+        }
+
+        if (has_response_format) {
+            return generation_prompt + reasoning +
+                   p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)) + end;
+        }
+
+        if (!has_tools) {
+            return generation_prompt + reasoning + p.content(p.rest()) + end;
+        }
+
+        auto tool_choice = p.choice();
+        foreach_function(inputs.tools, [&](size_t, const json & tool) {
+            const auto & function = tool.at("function");
+            const auto name = function.at("name").get<std::string>();
+            // Do not emit a prefix name before the complete JSON key arrives.
+            auto key = p.atomic(p.tool_open(p.literal("{")) + p.space() + p.literal("\"") +
+                p.tool_name(p.literal(name)) + p.literal("\"") + p.space() + p.literal(":"));
+            tool_choice |= p.rule("tool-" + name, p.tool(key + p.space() +
+                p.tool_args(p.schema(p.json(), "tool-" + name + "-schema", common_chat_tool_parameters(function))) +
+                p.space() + p.tool_close(p.literal("}"))));
+        });
+        auto tool_calls = tool_choice;
+        if (inputs.parallel_tool_calls) {
+            tool_calls += p.zero_or_more(p.space() + p.literal(",") + p.space() + tool_choice);
+        }
+        // Allow the EOG token once the tool-call JSON is complete.
+        auto suffix = p.optional(p.literal(TOOLS_END));
+        auto tool_section = p.trigger_rule("tool-call", p.literal(TOOLS_START) + p.space() +
+            p.literal("[") + p.space() + tool_calls + p.space() + p.literal("]") + p.space() + suffix);
+
+        auto content_before = p.content(p.until(TOOLS_START));
+        auto content_after  = p.content(p.rest());
+        auto tools = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? tool_section : p.optional(tool_section);
+        return generation_prompt + reasoning + content_before + tools + content_after + end;
+    });
+
+    if (include_grammar) {
+        data.grammar_lazy = !(has_response_format || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED);
+        data.grammar = build_grammar([&](const common_grammar_builder & builder) {
+            data.parser.build_grammar(builder, data.grammar_lazy);
+        });
+
+        if (has_tools && data.grammar_lazy) {
+            data.grammar_triggers = {
+                { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, TOOLS_START },
+            };
+        }
+    }
+
+    return data;
+}
diff --git a/common/parsers/parsers.h b/common/parsers/parsers.h
index 867403370..6afef02b9 100644
--- a/common/parsers/parsers.h
+++ b/common/parsers/parsers.h
@@ -43,6 +43,8 @@ bool is_lfm2_template(const std::string & src);

 bool is_inkling_template(const std::string & src);

+common_chat_params common_chat_params_init_apertus_1_5(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
+
 common_chat_params common_chat_params_init_cohere2moe(const common_chat_template & tmpl, const autoparser::generation_params & inputs);

 common_chat_params common_chat_params_init_deepseek_v3_2(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
diff --git a/common/parsers/sources.cmake b/common/parsers/sources.cmake
index 934e22673..4d16a91b8 100644
--- a/common/parsers/sources.cmake
+++ b/common/parsers/sources.cmake
@@ -3,6 +3,7 @@
 set(LLAMA_CHAT_PARSERS_SOURCES
     ${CMAKE_CURRENT_LIST_DIR}/parsers.cpp
     ${CMAKE_CURRENT_LIST_DIR}/parsers.h
+    ${CMAKE_CURRENT_LIST_DIR}/apertus.cpp
     ${CMAKE_CURRENT_LIST_DIR}/cohere2moe.cpp
     ${CMAKE_CURRENT_LIST_DIR}/deepseek.cpp
     ${CMAKE_CURRENT_LIST_DIR}/functionary-v3-2.cpp
diff --git a/conversion/__init__.py b/conversion/__init__.py
index 6b54c88e8..87624f653 100644
--- a/conversion/__init__.py
+++ b/conversion/__init__.py
@@ -22,7 +22,9 @@ TEXT_MODEL_MAP: dict[str, str] = {
     "LagunaForCausalLM": "laguna",
     "RicursiveForCausalLM": "ricursive",
     "FlintForCausalLM": "flint",
-    "ApertusForCausalLM": "llama",
+    "ApertusForCausalLM": "apertus",
+    "Apertus1p5ForConditionalGeneration": "apertus",
+    "Apertus1p5TextForCausalLM": "apertus",
     "ArceeForCausalLM": "llama",
     "ArcticForCausalLM": "arctic",
     "AudioFlamingo3ForConditionalGeneration": "qwen",
diff --git a/conversion/apertus.py b/conversion/apertus.py
new file mode 100644
index 000000000..54e204037
--- /dev/null
+++ b/conversion/apertus.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+import json
+
+from .base import ModelBase, gguf
+from .llama import LlamaModel
+
+
+@ModelBase.register("ApertusForCausalLM")
+@ModelBase.example("swiss-ai/Apertus-8B-Instruct-2509")
+class ApertusModel(LlamaModel):
+    model_arch = gguf.MODEL_ARCH.APERTUS
+    undo_permute = False
+
+    _alpha_n = {}
+    _alpha_p = {}
+    _beta = {}
+    _eps = {}
+
+    def modify_tensors(self, data_torch, name, bid):
+        # Handle xIELU activation parameters
+        n_layers = self.hparams["num_hidden_layers"]
+        if name.endswith(".act_fn.alpha_n"):
+            self._alpha_n[bid] = data_torch.to("cpu").float().item()
+            if (len(self._alpha_n) == n_layers):
+                self.gguf_writer.add_xielu_alpha_n([self._alpha_n[k] for k in sorted(self._alpha_n)])
+            return
+        if name.endswith(".act_fn.alpha_p"):
+            self._alpha_p[bid] = data_torch.to("cpu").float().item()
+            if (len(self._alpha_p) == n_layers):
+                self.gguf_writer.add_xielu_alpha_p([self._alpha_p[k] for k in sorted(self._alpha_p)])
+            return
+        if name.endswith(".act_fn.beta"):
+            self._beta[bid] = data_torch.to("cpu").float().item()
+            if (len(self._beta) == n_layers):
+                self.gguf_writer.add_xielu_beta([self._beta[k] for k in sorted(self._beta)])
+            return
+        if name.endswith(".act_fn.eps"):
+            self._eps[bid] = data_torch.to("cpu").float().item()
+            if (len(self._eps) == n_layers):
+                self.gguf_writer.add_xielu_eps([self._eps[k] for k in sorted(self._eps)])
+            return
+
+        yield from super().modify_tensors(data_torch, name, bid)
+
+
+@ModelBase.register(
+    "Apertus1p5ForConditionalGeneration",
+    "Apertus1p5TextForCausalLM",
+)
+@ModelBase.example("swiss-ai/Apertus-v1.5-8B", "swiss-ai/Apertus-v1.5-70B")
+class Apertus1p5Model(ApertusModel):
+    model_arch = gguf.MODEL_ARCH.APERTUS
+
+    def set_vocab(self):
+        super().set_vocab()
+
+        with open(self.dir_model / "tokenizer.json", encoding="utf-8") as f:
+            tokenizer_json = json.load(f)
+        added_tokens = {token["content"]: token["id"] for token in tokenizer_json["added_tokens"]}
+
+        self.gguf_writer.add_eot_token_id(added_tokens["<|assistant_end|>"])
+        self.gguf_writer.add_eom_token_id(added_tokens["<|tools_suffix|>"])
+
+    def set_gguf_parameters(self):
+        super().set_gguf_parameters()
+
+        n_vocab = self.hparams["vocab_size"]
+        n_vocab_out = self.hparams.get("output_vocab_size")
+        if n_vocab_out is None:
+            n_vocab_out = n_vocab
+        if type(n_vocab_out) is not int or not 0 < n_vocab_out <= n_vocab:
+            raise ValueError(f"Invalid output vocabulary size {n_vocab_out} for input vocabulary size {n_vocab}")
+        self.gguf_writer.add_vocab_size_out(n_vocab_out)
diff --git a/conversion/llama.py b/conversion/llama.py
index 6cb859cb9..8596cc3f4 100644
--- a/conversion/llama.py
+++ b/conversion/llama.py
@@ -439,41 +439,3 @@ class LlamaEmbedNemotronModel(LlamaModel):
 @ModelBase.example("HuggingFaceTB/SmolLM3-3B")
 class SmolLM3Model(LlamaModel):
     model_arch = gguf.MODEL_ARCH.SMOLLM3
-
-
-@ModelBase.register("ApertusForCausalLM")
-@ModelBase.example("swiss-ai/Apertus-8B-Instruct-2509")
-class ApertusModel(LlamaModel):
-    model_arch = gguf.MODEL_ARCH.APERTUS
-    undo_permute = False
-
-    _alpha_n = {}
-    _alpha_p = {}
-    _beta = {}
-    _eps = {}
-
-    def modify_tensors(self, data_torch, name, bid):
-        # Handle xIELU activation parameters
-        n_layers = self.hparams["num_hidden_layers"]
-        if name.endswith(".act_fn.alpha_n"):
-            self._alpha_n[bid] = data_torch.to("cpu").float().item()
-            if (len(self._alpha_n) == n_layers):
-                self.gguf_writer.add_xielu_alpha_n([self._alpha_n[k] for k in sorted(self._alpha_n)])
-            return
-        if name.endswith(".act_fn.alpha_p"):
-            self._alpha_p[bid] = data_torch.to("cpu").float().item()
-            if (len(self._alpha_p) == n_layers):
-                self.gguf_writer.add_xielu_alpha_p([self._alpha_p[k] for k in sorted(self._alpha_p)])
-            return
-        if name.endswith(".act_fn.beta"):
-            self._beta[bid] = data_torch.to("cpu").float().item()
-            if (len(self._beta) == n_layers):
-                self.gguf_writer.add_xielu_beta([self._beta[k] for k in sorted(self._beta)])
-            return
-        if name.endswith(".act_fn.eps"):
-            self._eps[bid] = data_torch.to("cpu").float().item()
-            if (len(self._eps) == n_layers):
-                self.gguf_writer.add_xielu_eps([self._eps[k] for k in sorted(self._eps)])
-            return
-
-        yield from super().modify_tensors(data_torch, name, bid)
diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py
index 64f2b5b25..ccae76f82 100644
--- a/gguf-py/gguf/constants.py
+++ b/gguf-py/gguf/constants.py
@@ -107,6 +107,7 @@ class Keys:

     class LLM:
         VOCAB_SIZE                        = "{arch}.vocab_size"
+        VOCAB_SIZE_OUT                    = "{arch}.vocab_size_out"
         VOCAB_SIZE_UNPADDED               = "{arch}.vocab_size_unpadded"
         CONTEXT_LENGTH                    = "{arch}.context_length"
         EMBEDDING_LENGTH                  = "{arch}.embedding_length"
diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py
index 0efdacc72..ba7e4c773 100644
--- a/gguf-py/gguf/gguf_writer.py
+++ b/gguf-py/gguf/gguf_writer.py
@@ -705,6 +705,9 @@ class GGUFWriter:
     def add_vocab_size(self, size: int) -> None:
         self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)

+    def add_vocab_size_out(self, size: int) -> None:
+        self.add_uint32(Keys.LLM.VOCAB_SIZE_OUT.format(arch=self.arch), size)
+
     def add_vocab_size_unpadded(self, size: int) -> None:
         self.add_uint32(Keys.LLM.VOCAB_SIZE_UNPADDED.format(arch=self.arch), size)

diff --git a/models/templates/swiss-ai-Apertus-v1.5.jinja b/models/templates/swiss-ai-Apertus-v1.5.jinja
new file mode 100644
index 000000000..a0707308b
--- /dev/null
+++ b/models/templates/swiss-ai-Apertus-v1.5.jinja
@@ -0,0 +1,365 @@
+{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}
+    {%- if param_spec.type == "array" -%}
+        {%- if param_spec['items'] -%}
+            {%- if param_spec['items']['type'] == "string" -%}
+                {{- "string[]" }}
+            {%- elif param_spec['items']['type'] == "number" -%}
+                {{- "number[]" }}
+            {%- elif param_spec['items']['type'] == "integer" -%}
+                {{- "number[]" }}
+            {%- elif param_spec['items']['type'] == "boolean" -%}
+                {{- "boolean[]" }}
+            {%- else -%}
+                {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%}
+                {%- if inner_type == "object | object" or inner_type|length > 50 -%}
+                    {{- "any[]" }}
+                {%- else -%}
+                    {{- inner_type + "[]" }}
+                {%- endif -%}
+            {%- endif -%}
+            {%- if param_spec.nullable -%}
+                {{- " | null" }}
+            {%- endif -%}
+        {%- else -%}
+            {{- "any[]" }}
+            {%- if param_spec.nullable -%}
+                {{- " | null" }}
+            {%- endif -%}
+        {%- endif -%}
+    {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%}
+        {#- Handle array of types like ["object", "object"] from Union[dict, list] #}
+        {%- if param_spec.type | length > 1 -%}
+            {{- param_spec.type | join(" | ") }}
+        {%- else -%}
+            {{- param_spec.type[0] }}
+        {%- endif -%}
+    {%- elif param_spec.oneOf -%}
+        {#- Handle oneOf schemas - check for complex unions and fallback to any #}
+        {%- set has_object_variants = false -%}
+        {%- for variant in param_spec.oneOf -%}
+            {%- if variant.type == "object" -%}
+                {%- set has_object_variants = true -%}
+            {%- endif -%}
+        {%- endfor -%}
+        {%- if has_object_variants and param_spec.oneOf|length > 1 -%}
+            {{- "any" }}
+        {%- else -%}
+            {%- for variant in param_spec.oneOf -%}
+                {{- render_typescript_type(variant, required_params) -}}
+                {%- if variant.description %}
+                    {{- "// " + variant.description }}
+                {%- endif -%}
+                {%- if variant.default is defined %}
+                    {{ "// default: " + variant.default|tojson }}
+                {%- endif -%}
+                {%- if not loop.last %}
+                    {{- " | " }}
+                {% endif -%}
+            {%- endfor -%}
+        {%- endif -%}
+    {%- elif param_spec.type == "string" -%}
+        {%- if param_spec.enum -%}
+            {{- '"' + param_spec.enum|join('" | "') + '"' -}}
+        {%- else -%}
+            {{- "string" }}
+            {%- if param_spec.nullable %}
+                {{- " | null" }}
+            {%- endif -%}
+        {%- endif -%}
+    {%- elif param_spec.type == "number" -%}
+        {{- "number" }}
+    {%- elif param_spec.type == "integer" -%}
+        {{- "number" }}
+    {%- elif param_spec.type == "boolean" -%}
+        {{- "boolean" }}
+    {%- elif param_spec.type == "object" -%}
+        {%- if param_spec.properties -%}
+            {{- "{\n" }}
+            {%- for prop_name, prop_spec in param_spec.properties.items() -%}
+                {{- prop_name -}}
+                {%- if prop_name not in (param_spec.required or []) -%}
+                    {{- "?" }}
+                {%- endif -%}
+                {{- ": " }}
+                {{ render_typescript_type(prop_spec, param_spec.required or []) }}
+                {%- if not loop.last -%}
+                    {{-", " }}
+                {%- endif -%}
+            {%- endfor -%}
+            {{- "}" }}
+        {%- else -%}
+            {{- "object" }}
+        {%- endif -%}
+    {%- else -%}
+        {{- "any" }}
+    {%- endif -%}
+{%- endmacro -%}
+
+{%- macro render_tools(tools) -%}
+    {%- for tool in tools %}
+        {%- if tool.function %}
+            {%- set tool = tool.function %}
+        {%- endif %}
+        {{- "// " + tool.description + "\n" }}
+        {{- "type "+ tool.name + " = " }}
+        {%- if tool.parameters and tool.parameters.properties %}
+            {{- "(_: {\n" }}
+            {%- for param_name, param_spec in tool.parameters.properties.items() %}
+                {%- if param_spec.description %}
+                    {{- "// " + param_spec.description + "\n" }}
+                {%- endif %}
+                {{- param_name }}
+                {%- if param_name not in (tool.parameters.required or []) -%}
+                    {{- "?" }}
+                {%- endif -%}
+                {{- ": " }}
+                {{- render_typescript_type(param_spec, tool.parameters.required or []) }}
+                {%- if param_spec.default is defined -%}
+                    {%- if param_spec.enum %}
+                        {{- ", // default: " + param_spec.default }}
+                    {%- elif param_spec.oneOf %}
+                        {{- "// default: " + param_spec.default }}
+                    {%- else %}
+                        {{- ", // default: " + param_spec.default|tojson }}
+                    {%- endif -%}
+                {%- endif -%}
+                {%- if not loop.last %}
+                    {{- ",\n" }}
+                {%- else %}
+                    {{- "\n" }}
+                {%- endif -%}
+            {%- endfor %}
+            {{- "}) => any;" }}
+        {%- else -%}
+            {{- "() => any;" }}
+        {%- endif -%}
+        {%- if not loop.last -%}
+            {{- "\n" }}
+        {%- endif -%}
+    {%- endfor %}
+{%- endmacro -%}
+
+{{ bos_token }}
+
+{%- set system_token = '<|system_start|>' -%}
+{%- set end_system_token = '<|system_end|>' -%}
+{%- set developer_token = '<|developer_start|>' -%}
+{%- set end_developer_token = '<|developer_end|>' -%}
+{%- set user_token = '<|user_start|>' -%}
+{%- set end_user_token = '<|user_end|>' -%}
+{%- set assistant_token = '<|assistant_start|>' -%}
+{%- set end_assistant_token = '<|assistant_end|>' -%}
+{%- set inner_token = '<|inner_prefix|>' -%}
+{%- set outer_token = '<|inner_suffix|>' -%}
+{%- set tool_calls_token = '<|tools_prefix|>' -%}
+{%- set end_tool_calls_token = '<|tools_suffix|>' -%}
+{%- set tool_output_start_token = '<|tool_output_start|>' -%}
+{%- set tool_output_end_token = '<|tool_output_end|>' -%}
+{%- set image_token = '<|image|>' -%}
+{%- set audio_token = '<|audio|>' -%}
+
+{%- set ns = namespace(in_assistant=false, in_tool=false, in_inner=false, waiting_for_tool_outputs=false, assistant_format=none) -%}
+
+{%- if messages and messages[0].role == 'system' -%}
+    {%- if "content" in messages[0] -%}
+        {%- if messages[0].content is string -%}
+            {{ system_token + messages[0].content + end_system_token }}
+        {%- elif messages[0].content is mapping and "text" in messages[0].content -%}
+            {{ system_token + messages[0].content.text + end_system_token }}
+        {%- else -%}
+            {{- raise_exception("Invalid system message") -}}
+        {%- endif -%}
+    {%- else -%}
+        {{- raise_exception("Invalid system message") -}}
+    {%- endif -%}
+    {%- set loop_messages = messages[1:] -%}
+{%- else -%}
+    {{ system_token + 'You are Apertus 1.5 Omni, a multimodal assistant developed by the Swiss AI Initiative. Extended from Apertus 1 via continued pretraining, you understand images and audio and respond in text.' + end_system_token }}
+    {%- set loop_messages = messages -%}
+{%- endif -%}
+
+{{ developer_token + 'Deliberation: ' }}
+{%- if enable_thinking is defined and enable_thinking -%}
+    {{ 'enabled\n' }}
+{%- else -%}
+    {{ 'disabled\n' }}
+{%- endif -%}
+{%- if tools is defined and tools -%}
+    {{ 'Tool Capabilities:\n' + render_tools(tools) }}
+{%- else -%}
+    {{ 'Tool Capabilities: disabled' }}
+{%- endif -%}
+{{ end_developer_token }}
+
+{%- for message in loop_messages -%}
+    {%- if message.role == 'user' -%}
+        {%- set ns.in_inner = false -%}
+        {%- if ns.in_tool -%}
+            {{ tool_output_end_token }}
+            {%- set ns.in_tool = false -%}
+        {%- endif -%}
+        {%- if ns.in_assistant -%}
+            {{ end_assistant_token }}
+            {%- set ns.in_assistant = false -%}
+        {%- endif -%}
+        {%- if "content" in message -%}
+            {{ user_token }}
+            {%- if message.content is string -%}
+                {{ message.content }}
+            {%- elif message.content is mapping and "parts" in message.content -%}
+                {%- set parts = message.content.parts -%}
+                {%- for part in parts -%}
+                    {%- if part.type == "text" -%}
+                        {{ part.text }}
+                    {%- elif part.type == "image" or part.type == "image_url" or part.type == "input_image" -%}
+                        {{ image_token }}
+                    {%- elif part.type == "audio" or part.type == "audio_url" or part.type == "input_audio" -%}
+                        {{ audio_token }}
+                    {%- else -%}
+                        {{- raise_exception("Invalid user part: " + part.type) -}}
+                    {%- endif -%}
+                {%- endfor -%}
+            {%- elif message.content is not string and message.content is not mapping and message.content is iterable -%}
+                {%- for part in message.content -%}
+                    {%- if part.type == "text" -%}
+                        {{ part.text }}
+                    {%- elif part.type == "image" or part.type == "image_url" or part.type == "input_image" -%}
+                        {{ image_token }}
+                    {%- elif part.type == "audio" or part.type == "audio_url" or part.type == "input_audio" -%}
+                        {{ audio_token }}
+                    {%- else -%}
+                        {{- raise_exception("Invalid user part: " + part.type) -}}
+                    {%- endif -%}
+                {%- endfor -%}
+            {%- else -%}
+                {{- raise_exception("Invalid user message: " + message.role) -}}
+            {%- endif -%}
+            {{ end_user_token }}
+        {%- endif -%}
+    {%- elif message.role == 'assistant' -%}
+        {%- if not ns.in_assistant -%}
+            {{ assistant_token }}
+            {%- set ns.in_assistant = true -%}
+        {%- endif -%}
+        {%- if "content" in message -%}
+            {%- if message.content is string and (ns.assistant_format is none or ns.assistant_format == "string") -%}
+                {%- if ns.in_tool -%}
+                    {{ tool_output_end_token }}
+                    {%- set ns.in_tool = false -%}
+                {%- endif -%}
+                {%- set ns.assistant_format = "string" -%}
+                {{ message.content }}
+            {%- elif message.content is mapping and "blocks" in message.content and (ns.assistant_format is none or ns.assistant_format == "mapping") -%}
+                {%- set ns.assistant_format = "mapping" -%}
+                {%- set blocks = message.content.blocks -%}
+                {%- for block in blocks -%}
+                    {%- if block.type == 'thoughts' -%}
+                        {%- if ns.in_tool -%}
+                            {{ tool_output_end_token }}
+                            {%- set ns.in_tool = false -%}
+                        {%- endif -%}
+                        {%- if not ns.in_inner -%}
+                            {%- set ns.in_inner = true -%}
+                            {{ inner_token }}
+                        {%- endif -%}
+                        {{ block.text }}
+                    {%- elif block.type == 'tool_calls' -%}
+                        {%- if ns.in_tool -%}
+                            {{ tool_output_end_token }}
+                            {%- set ns.in_tool = false -%}
+                        {%- endif -%}
+                        {%- if ns.in_inner and not loop.first and block.calls|length == 1 and block.calls[0].name == 'display_answers' -%}
+                            {%- set ns.in_inner = false -%}
+                            {{ outer_token }}
+                        {%- endif -%}
+                        {{ tool_calls_token + '[' }}
+                        {%- for tool_call in block.calls -%}
+                            {%- if tool_call.function %}
+                                {%- set tool_call = tool_call.function %}
+                            {%- endif %}
+                            {{- '{"' + tool_call.name + '": ' + (tool_call.arguments if tool_call.arguments is string else tool_call.arguments | tojson) + '}' }}
+                            {%- if not loop.last -%}
+                                {{- ", " }}
+                            {%- endif -%}
+                        {%- endfor -%}
+                        {{ ']' + end_tool_calls_token }}
+                        {%- set ns.waiting_for_tool_outputs = true -%}
+                    {%- elif block.type == 'tool_outputs' -%}
+                        {%- if ns.in_tool -%}
+                            {{- raise_exception("Cannot have both tool outputs as separate messages and tool outputs as blocks") -}}
+                        {%- endif -%}
+                        {{ tool_output_start_token }}
+                        {%- for tool_output in block.outputs -%}
+                            {{- tool_output.output }}
+                            {%- if not loop.last -%}
+                                {{- ", " }}
+                            {%- endif -%}
+                        {%- endfor -%}
+                        {{- tool_output_end_token }}
+                        {%- set ns.waiting_for_tool_outputs = false -%}
+                    {%- elif block.type == 'response' -%}
+                        {%- if ns.in_tool -%}
+                            {{ tool_output_end_token }}
+                            {%- set ns.in_tool = false -%}
+                        {%- endif -%}
+                        {%- if (not loop.first and ns.in_inner) or (ns.in_assistant and ns.in_inner) -%}
+                            {%- set ns.in_inner = false -%}
+                            {{ outer_token }}
+                        {%- endif -%}
+                        {{ block.text }}
+                    {%- else -%}
+                        {{- raise_exception("Invalid assistant block type: " + block.type) -}}
+                    {%- endif -%}
+                {%- endfor -%}
+            {%- else -%}
+                {{- raise_exception("Invalid assistant content") -}}
+            {%- endif -%}
+        {%- else -%}
+            {{- raise_exception("Invalid assistant message") -}}
+        {%- endif -%}
+        {%- if "tool_calls" in message and message.tool_calls -%}
+            {{ tool_calls_token + '[' }}
+            {%- for tool_call in message.tool_calls -%}
+                {%- if tool_call.type is defined and tool_call.type != 'function' -%}
+                    {{- raise_exception("Invalid tool call type: " + tool_call.type) -}}
+                {%- endif -%}
+                {%- if tool_call.function %}
+                    {%- set tool_call = tool_call.function %}
+                {%- endif %}
+                {%- if tool_call.name and tool_call.arguments -%}
+                    {{- '{"' + tool_call.name + '": ' + (tool_call.arguments if tool_call.arguments is string else tool_call.arguments | tojson) + '}' }}
+                    {%- if not loop.last -%}
+                        {{- ", " }}
+                    {%- endif -%}
+                {%- else -%}
+                    {{- raise_exception("Invalid tool call") -}}
+                {%- endif -%}
+            {%- endfor -%}
+            {{ ']' + end_tool_calls_token }}
+            {%- set ns.waiting_for_tool_outputs = true -%}
+        {%- endif -%}
+    {%- elif message.role == 'tool' -%}
+        {%- if not ns.in_assistant -%}
+            {{- raise_exception("Tool message outside of assistant") -}}
+        {%- endif -%}
+        {%- if not ns.in_tool -%}
+            {{ tool_output_start_token }}
+            {%- set ns.in_tool = true -%}
+        {%- else -%}
+            {{ ", "}}
+        {%- endif -%}
+        {{ message.content }}
+        {%- set ns.waiting_for_tool_outputs = false -%}
+    {%- else -%}
+        {{- raise_exception("Invalid message role") -}}
+    {%- endif -%}
+{%- endfor -%}
+{%- if ns.in_tool -%}
+    {{ tool_output_end_token }}
+{%- endif -%}
+{%- if ns.in_assistant and not (continue_assistant_message is defined and continue_assistant_message) and not ns.waiting_for_tool_outputs -%}
+    {{ end_assistant_token }}
+{%- endif -%}
+{%- if add_generation_prompt -%}
+    {{ assistant_token }}
+{%- endif -%}
diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp
index ff03ca871..e78c3d2a8 100644
--- a/src/llama-arch.cpp
+++ b/src/llama-arch.cpp
@@ -223,6 +223,7 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
     { LLM_KV_GENERAL_TENSOR_EXTRA_PREC_A4,           "general.tensor_extra.prec_a4"          },

     { LLM_KV_VOCAB_SIZE,                        "%s.vocab_size"                        },
+    { LLM_KV_VOCAB_SIZE_OUT,                    "%s.vocab_size_out"                    },
     { LLM_KV_VOCAB_SIZE_UNPADDED,               "%s.vocab_size_unpadded"               },
     { LLM_KV_CONTEXT_LENGTH,                    "%s.context_length"                    },
     { LLM_KV_EMBEDDING_LENGTH,                  "%s.embedding_length"                  },
@@ -1582,6 +1583,7 @@ bool llm_arch_supports_mixed_batch(const llm_arch & arch) {

 bool llm_arch_supports_sm_tensor(const llm_arch & arch) {
     switch (arch) {
+        case LLM_ARCH_APERTUS:
         case LLM_ARCH_CLOVER_MOE:
         case LLM_ARCH_ZAYA1:
         case LLM_ARCH_GROK:
@@ -1651,7 +1653,6 @@ bool llama_arch_supports_save(llm_arch arch) {
         case LLM_ARCH_GEMMA3N:
         case LLM_ARCH_BITNET:
         case LLM_ARCH_T5:
-        case LLM_ARCH_APERTUS:
         case LLM_ARCH_STEP35:
         case LLM_ARCH_CLEF: // the head tensors are not saved
         case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load
diff --git a/src/llama-arch.h b/src/llama-arch.h
index 2dd67435a..03e8b8c80 100644
--- a/src/llama-arch.h
+++ b/src/llama-arch.h
@@ -227,6 +227,7 @@ enum llm_kv {
     LLM_KV_GENERAL_TENSOR_EXTRA_PREC_A4,

     LLM_KV_VOCAB_SIZE,
+    LLM_KV_VOCAB_SIZE_OUT,
     LLM_KV_VOCAB_SIZE_UNPADDED,
     LLM_KV_CONTEXT_LENGTH,
     LLM_KV_EMBEDDING_LENGTH,
diff --git a/src/llama-hparams.h b/src/llama-hparams.h
index 3e846be03..bc93fe591 100644
--- a/src/llama-hparams.h
+++ b/src/llama-hparams.h
@@ -300,6 +300,9 @@ struct llama_hparams {
     // output embedding dimension (0 = use n_embd)
     uint32_t n_embd_out_impl = 0;

+    // output vocabulary size (0 = use the tokenizer vocabulary size)
+    uint32_t n_vocab_out_impl = 0;
+
     uint32_t dflash_block_size       = 0;
     uint32_t dflash_conv_kernel_size = 0;
     uint32_t dflash_conv_group_size  = 0;
diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp
index 7a02ef1a9..c39acf16d 100644
--- a/src/llama-model-saver.cpp
+++ b/src/llama-model-saver.cpp
@@ -188,6 +188,9 @@ void llama_model_saver::add_kv_from_model() {
     if (hparams.n_vocab_unpadded > 0) {
         add_kv(LLM_KV_VOCAB_SIZE_UNPADDED,           hparams.n_vocab_unpadded);
     }
+    if (hparams.n_vocab_out_impl > 0) {
+        add_kv(LLM_KV_VOCAB_SIZE_OUT,                hparams.n_vocab_out_impl);
+    }
     add_kv(LLM_KV_CONTEXT_LENGTH,                    hparams.n_ctx_train);
     add_kv(LLM_KV_EMBEDDING_LENGTH,                  hparams.n_embd);
     if (hparams.n_embd_out_impl > 0) {
@@ -497,10 +500,11 @@ void llama_model_saver::add_kv_from_model() {

     add_kv(LLM_KV_SHORTCONV_L_CACHE,                 hparams.n_shortconv_l_cache);

-    add_kv(LLM_KV_XIELU_ALPHA_N,                     hparams.xielu_alpha_n);
-    add_kv(LLM_KV_XIELU_ALPHA_P,                     hparams.xielu_alpha_p);
-    add_kv(LLM_KV_XIELU_BETA,                        hparams.xielu_beta);
-    add_kv(LLM_KV_XIELU_EPS,                         hparams.xielu_eps);
+    const bool xielu_per_layer = model->arch == LLM_ARCH_APERTUS;
+    add_kv(LLM_KV_XIELU_ALPHA_N,                     hparams.xielu_alpha_n, xielu_per_layer);
+    add_kv(LLM_KV_XIELU_ALPHA_P,                     hparams.xielu_alpha_p, xielu_per_layer);
+    add_kv(LLM_KV_XIELU_BETA,                        hparams.xielu_beta,    xielu_per_layer);
+    add_kv(LLM_KV_XIELU_EPS,                         hparams.xielu_eps,     xielu_per_layer);

     add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE,               hparams.attn_res_block_size);
     add_kv(LLM_KV_ACTIVATION_SITU_BETA,              hparams.situ_beta);
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index 225aeb6f9..7b6e9ea11 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -1602,6 +1602,7 @@ void llama_model_base::load_hparams(llama_model_loader & ml) {
     }

     ml.get_key(LLM_KV_CONTEXT_LENGTH,          hparams.n_ctx_train);
+    ml.get_key(LLM_KV_VOCAB_SIZE_OUT,          hparams.n_vocab_out_impl, false);
     ml.get_key(LLM_KV_EMBEDDING_LENGTH,        hparams.n_embd);
     ml.get_key(LLM_KV_EMBEDDING_LENGTH_OUT,    hparams.n_embd_out_impl, false);
     ml.get_key(LLM_KV_ATTENTION_CAUSAL,        hparams.causal_attn,     false);
diff --git a/src/models/apertus.cpp b/src/models/apertus.cpp
index ed42d1c6f..c8276af6b 100644
--- a/src/models/apertus.cpp
+++ b/src/models/apertus.cpp
@@ -1,4 +1,5 @@
 #include "models.h"
+#include <float.h>

 void llama_model_apertus::load_arch_hparams(llama_model_loader & ml) {
     ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
@@ -10,6 +11,7 @@ void llama_model_apertus::load_arch_hparams(llama_model_loader & ml) {

     switch (hparams.n_layer()) {
         case 32: type = LLM_TYPE_8B; break;
+        case 80: type = LLM_TYPE_70B; break;
         default: type = LLM_TYPE_UNKNOWN;
     }
 }
@@ -17,11 +19,16 @@ void llama_model_apertus::load_arch_hparams(llama_model_loader & ml) {
 void llama_model_apertus::load_arch_tensors(llama_model_loader &) {
     LLAMA_LOAD_LOCALS;

+    const int64_t n_vocab_out = hparams.n_vocab_out_impl > 0 ? hparams.n_vocab_out_impl : n_vocab;
+    if (n_vocab_out > n_vocab) {
+        throw std::runtime_error("output vocabulary size exceeds tokenizer vocabulary size");
+    }
+
     tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, 0);

     // output
     output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0);
-    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), { n_embd, n_vocab }, 0);
+    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), { n_embd, n_vocab_out }, 0);

     for (int i = 0; i < n_layer; ++i) {
         auto & layer = layers[i];
@@ -158,6 +165,17 @@ llama_model_apertus::graph::graph(const llm_graph_params & params) : llm_graph_c
     // lm_head
     cur = build_lora_mm(model.output, cur);

+    if (hparams.n_vocab_out_impl > 0 && hparams.n_vocab_out_impl < model.vocab.n_tokens()) {
+        const int64_t n_vocab     = model.vocab.n_tokens();
+        const int64_t n_vocab_out = hparams.n_vocab_out_impl;
+
+        ggml_tensor * output_padding = ggml_fill(
+            ctx0,
+            ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab - n_vocab_out, cur->ne[1]),
+            -FLT_MAX);
+        cur = ggml_concat(ctx0, cur, output_padding, 0);
+    }
+
     cb(cur, "result_output", -1);
     res->t_logits = cur;
 }
diff --git a/tests/test-chat-auto-parser.cpp b/tests/test-chat-auto-parser.cpp
index b9a407182..f98210c3d 100644
--- a/tests/test-chat-auto-parser.cpp
+++ b/tests/test-chat-auto-parser.cpp
@@ -2479,6 +2479,7 @@ static void test_role_markers_all_templates(testing & t) {
         // Apertus uses <|user_start|> / <|assistant_start|> but the user diff
         // carries the preceding <|assistant_end|> from the previous turn.
         { "Apertus-8B-Instruct.jinja",                       "<|user_start|>", "<|assistant_start|>" },
+        { "swiss-ai-Apertus-v1.5.jinja",                     "<|user_start|>", "<|assistant_start|>" },

         // Apriel 1.6 wraps the assistant body with <|begin_assistant|>, but
         // <|begin_assistant|> is also the detected reasoning start, so the
diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp
index fab75335c..b20553038 100644
--- a/tests/test-chat.cpp
+++ b/tests/test-chat.cpp
@@ -6637,6 +6637,113 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
             .run();
     }

+    // Apertus v1.5 tests - reasoning and FUNC_NAME_AS_KEY tool calls
+    {
+        auto tst = peg_tester("models/templates/swiss-ai-Apertus-v1.5.jinja", detailed_debug);
+
+        tst.test(R"(<|tools_prefix|>[{"special_function":{"arg1":1}}]<|tools_suffix|>)")
+            .tools({ special_function_tool })
+            .tool_choice(COMMON_CHAT_TOOL_CHOICE_NONE)
+            .expect_content(R"(<|tools_prefix|>[{"special_function":{"arg1":1}}]<|tools_suffix|>)")
+            .run();
+
+        tst.test(R"(<|inner_prefix|>Explain <|tools_prefix|> literally.<|inner_suffix|>Done.)")
+            .tools({ special_function_tool })
+            .enable_thinking(true)
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .expect_reasoning("Explain <|tools_prefix|> literally.")
+            .expect_content("Done.")
+            .expect_reconstruction()
+            .run();
+
+        for (const auto choice : { COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED }) {
+            tst.test(R"(<|tools_prefix|>[{"special_function":{"arg1":1}},{"special_function_with_opt":{"arg1":2}}]<|tools_suffix|>)")
+                .tools({ special_function_tool, special_function_tool_with_optional_param })
+                .parallel_tool_calls(true)
+                .tool_choice(choice)
+                .expect_tool_calls({
+                    { "special_function", R"({"arg1":1})", "" },
+                    { "special_function_with_opt", R"({"arg1":2})", "" },
+                })
+                .run();
+        }
+
+        tst.test("Hello, world!\nWhat's up?")
+            .expect(message_assist)
+            .expect_reconstruction()
+            .run();
+
+        tst.test("<|inner_prefix|>I'm\nthinking<|inner_suffix|>Hello, world!\nWhat's up?")
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .enable_thinking(true)
+            .expect(message_assist_thoughts)
+            .expect_reconstruction()
+            .run();
+
+        tst.test("<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>")
+            .tools({ special_function_tool })
+            .expect(message_assist_call)
+            .expect_reconstruction()
+            .run();
+
+        tst.test("<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}, "
+                 "{\"python\": {\"code\": \"print(1)\"}}]<|tools_suffix|>")
+            .parallel_tool_calls(true)
+            .tools({ special_function_tool, python_tool })
+            .expect_tool_calls({
+                { "special_function", "{\"arg1\":1}", "" },
+                { "python", "{\"code\":\"print(1)\"}", "" },
+            })
+            .run();
+
+        tst.test("Calling a tool.<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>")
+            .tools({ special_function_tool })
+            .expect(message_with_content_and_tool_call("Calling a tool.", "special_function", "{\"arg1\":1}"))
+            .expect_reconstruction()
+            .run();
+
+        // Recover complete tool-call JSON when the closing marker is missing.
+        tst.test("<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]")
+            .tools({ special_function_tool })
+            .is_partial(true)
+            .expect(message_assist_call)
+            .run();
+
+        tst.test("<|tools_prefix|>[{\"special_function\": {\"arg1\": ")
+            .tools({ special_function_tool })
+            .is_partial(true)
+            .expect(simple_assist_msg("", "", "special_function", "{\"arg1\": "))
+            .run();
+
+        tst.test("<|inner_prefix|>Check the schema.<|inner_suffix|>{\"response\":\"ok\"}")
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .enable_thinking(true)
+            .json_schema(R"({"type":"object","properties":{"response":{"type":"string"}},"required":["response"]})")
+            .expect_reasoning("Check the schema.")
+            .expect_content("{\"response\":\"ok\"}")
+            .run();
+
+        tst.test("world!\nWhat's up?")
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .enable_thinking(true)
+            .messages({ message_user, message_assist_prefill_content })
+            .add_generation_prompt(false)
+            .continue_final_message(COMMON_CHAT_CONTINUATION_CONTENT)
+            .expect(simple_assist_msg("Hello, world!\nWhat's up?", "I'm thinking"))
+            .run();
+
+        // A reasoning-only assistant prefill is valid and remains reasoning while incomplete.
+        tst.test(" thinking")
+            .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+            .enable_thinking(true)
+            .messages({ message_user, message_assist_prefill_reasoning })
+            .add_generation_prompt(false)
+            .continue_final_message(COMMON_CHAT_CONTINUATION_REASONING)
+            .is_partial(true)
+            .expect_reasoning("I'm thinking")
+            .run();
+    }
+
     // MiniMax-M2 tests - XML invoke format with parameter tags
     // Format: <minimax:tool_call><invoke name="func"><parameter name="key">value</parameter></invoke></minimax:tool_call>
     {
@@ -8482,6 +8589,161 @@ static void test_template_generation_prompt() {
         check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n<think>\nI'm");
     }

+    {
+        auto tmpls = read_templates("models/templates/swiss-ai-Apertus-v1.5.jinja");
+        common_chat_templates_inputs tool_inputs;
+        tool_inputs.messages = { message_user };
+        tool_inputs.tools = { special_function_tool, special_function_tool_with_optional_param };
+        tool_inputs.add_generation_prompt = true;
+        tool_inputs.tool_choice = COMMON_CHAT_TOOL_CHOICE_REQUIRED;
+        auto tool_parser = common_chat_templates_apply(tmpls.get(), tool_inputs);
+        assert_equals(false, tool_parser.grammar_lazy);
+        assert_equals(true, tool_parser.grammar_triggers.empty());
+        const std::string complete_call = R"(<|tools_prefix|>[{"special_function":{"arg1":1}}]<|tools_suffix|>)";
+        auto accepts_grammar = [&](const std::string & output) {
+            auto grammar = build_grammar(tool_parser.grammar);
+            return match_string_detailed(fake_tokenize({}, tool_parser.generation_prompt + output), grammar.get()).success;
+        };
+        assert_equals(true, accepts_grammar(complete_call));
+        assert_equals(false, accepts_grammar("No tool needed."));
+        const std::string no_suffix = R"(<|tools_prefix|>[{"special_function":{"arg1":1}}])";
+        assert_equals(true, accepts_grammar(no_suffix));
+        assert_equals(false, accepts_grammar(R"(<|tools_prefix|>[{"special_function":{"arg1":1}})"));
+        assert_msg_equals(message_assist_call, common_chat_peg_parse(tool_parser.parser, common_chat_input(no_suffix), false, common_chat_parser_params(tool_parser)), true);
+
+        for (const auto & malformed : {
+                R"(<|tools_prefix|>[{"unknown":{"arg1":1}}]<|tools_suffix|>)",
+                R"(<|tools_prefix|>[{"special_function" {"arg1":1}}]<|tools_suffix|>)",
+                R"(<|tools_prefix|>[{"special_function":{"arg1":1},"special_function":{"arg1":2}}]<|tools_suffix|>)" }) {
+            assert_equals(false, accepts_grammar(malformed));
+            for (auto choice : { COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED }) {
+                auto inputs = tool_inputs;
+                inputs.tool_choice = choice;
+                auto parser = common_chat_templates_apply(tmpls.get(), inputs);
+                bool has_calls = false;
+                try {
+                    has_calls = !common_chat_peg_parse(parser.parser, common_chat_input(malformed), false, common_chat_parser_params(parser)).tool_calls.empty();
+                } catch (const std::runtime_error &) {
+                    // Invalid complete envelopes may fail parsing instead of becoming content.
+                }
+                assert_equals(false, has_calls);
+            }
+        }
+
+        check(tmpls, basic(),                  "<|assistant_start|>");
+        check(tmpls, continuation_content(),   "<|assistant_start|><|inner_prefix|>I'm thinking<|inner_suffix|>Hello, ");
+        check(tmpls, continuation_reasoning(), "<|assistant_start|><|inner_prefix|>I'm");
+
+        common_chat_templates_inputs thinking_inputs;
+        thinking_inputs.messages = { system_msg, message_user };
+        thinking_inputs.enable_thinking = true;
+        auto thinking_params = common_chat_templates_apply(tmpls.get(), thinking_inputs);
+        assert_contains(thinking_params.prompt.str(), "<|developer_start|>Deliberation: enabled\n");
+        assert_equals(true, thinking_params.supports_thinking);
+        assert_equals(std::string("<|inner_prefix|>"), thinking_params.thinking_start_tag);
+        assert_equals(size_t(1), thinking_params.thinking_end_tags.size());
+        assert_equals(std::string("<|inner_suffix|>"), thinking_params.thinking_end_tags[0]);
+        bool has_tool_delimiter = false;
+        for (const auto & delimiter : thinking_params.message_delimiters.delimiters) {
+            if (delimiter.role == COMMON_CHAT_ROLE_TOOL && delimiter.delimiter == "<|tool_output_start|>") {
+                has_tool_delimiter = true;
+            }
+        }
+        assert_equals(true, has_tool_delimiter);
+
+        auto no_thinking_inputs = thinking_inputs;
+        no_thinking_inputs.enable_thinking = false;
+        auto no_thinking_params = common_chat_templates_apply(tmpls.get(), no_thinking_inputs);
+        assert_contains(no_thinking_params.prompt.str(), "<|developer_start|>Deliberation: disabled\n");
+
+        common_chat_msg assistant_history = simple_assist_msg("Previous answer", "Previous reasoning");
+        common_chat_msg user_followup;
+        user_followup.role = "user";
+        user_followup.content = "Follow up";
+
+        common_chat_templates_inputs history_inputs;
+        history_inputs.messages = { system_msg, message_user, assistant_history, user_followup };
+        auto history_params = common_chat_templates_apply(tmpls.get(), history_inputs);
+        assert_contains(
+            history_params.prompt.str(),
+            "<|assistant_start|><|inner_prefix|>Previous reasoning<|inner_suffix|>Previous answer"
+            "<|assistant_end|><|user_start|>Follow up<|user_end|><|assistant_start|>");
+
+        common_chat_templates_inputs tool_history_inputs;
+        tool_history_inputs.messages = { system_msg, message_user, tool_call_msg, tool_msg, user_followup };
+        tool_history_inputs.tools = { special_function_tool };
+        auto tool_history_params = common_chat_templates_apply(tmpls.get(), tool_history_inputs);
+        assert_contains(
+            tool_history_params.prompt.str(),
+            "<|assistant_start|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]"
+            "<|tools_suffix|><|tool_output_start|>Sunny<|tool_output_end|><|assistant_end|>"
+            "<|user_start|>Follow up<|user_end|><|assistant_start|>");
+
+        common_chat_msg multi_tool_call = message_with_reasoning_content_and_multiple_tool_calls(
+            "Need tool results", "Calling tools",
+            {
+                { "special_function", "{\"arg1\": 1}" },
+                { "special_function_with_opt", "{\"arg1\": 2, \"arg2\": 3}" },
+            });
+
+        common_chat_msg second_tool_msg;
+        second_tool_msg.role = "tool";
+        second_tool_msg.tool_name = "special_function_with_opt";
+        second_tool_msg.tool_call_id = "call1";
+        second_tool_msg.content = "Rainy";
+
+        common_chat_msg final_after_tools = simple_assist_msg("Weather checked.");
+
+        common_chat_templates_inputs multi_tool_history_inputs;
+        multi_tool_history_inputs.messages = {
+            system_msg, message_user, multi_tool_call, tool_msg, second_tool_msg, final_after_tools, user_followup
+        };
+        multi_tool_history_inputs.tools = { special_function_tool, special_function_tool_with_optional_param };
+        auto multi_tool_history_params = common_chat_templates_apply(tmpls.get(), multi_tool_history_inputs);
+        assert_contains(
+            multi_tool_history_params.prompt.str(),
+            "<|assistant_start|><|inner_prefix|>Need tool results<|inner_suffix|>Calling tools"
+            "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}, "
+            "{\"special_function_with_opt\": {\"arg1\": 2, \"arg2\": 3}}]<|tools_suffix|>"
+            "<|tool_output_start|>Sunny, Rainy<|tool_output_end|>Weather checked.<|assistant_end|>"
+            "<|user_start|>Follow up<|user_end|><|assistant_start|>");
+
+        common_chat_msg media_user;
+        media_user.role = "user";
+        media_user.content_parts = {
+            { "text", "Describe this image: ", "" },
+            { "media_marker", "<|image|>", "" },
+            { "text", " and transcribe this audio: ", "" },
+            { "media_marker", "<|audio|>", "" },
+        };
+
+        common_chat_templates_inputs media_inputs;
+        media_inputs.messages = { system_msg, media_user };
+        auto media_params = common_chat_templates_apply(tmpls.get(), media_inputs);
+        assert_contains(
+            media_params.prompt.str(),
+            "<|user_start|>Describe this image: <|image|> and transcribe this audio: <|audio|><|user_end|>");
+
+        common_chat_msg reserved_user;
+        reserved_user.role = "user";
+        reserved_user.content = "Explain <|assistant_start|> and <|tools_prefix|> literally.";
+        common_chat_templates_inputs reserved_inputs;
+        reserved_inputs.messages = { system_msg, reserved_user };
+        auto reserved_params = common_chat_templates_apply(tmpls.get(), reserved_inputs);
+        assert_contains(
+            reserved_params.prompt.str(),
+            "<|user_start|>Explain <|assistant_start|> and <|tools_prefix|> literally.<|user_end|>");
+
+        // Apertus uses enable_thinking; reasoning_effort kwargs do not select a level.
+        auto low_inputs = thinking_inputs;
+        low_inputs.chat_template_kwargs["reasoning_effort"] = R"("low")";
+        auto max_inputs = thinking_inputs;
+        max_inputs.chat_template_kwargs["reasoning_effort"] = R"("max")";
+        assert_equals(
+            common_chat_templates_apply(tmpls.get(), low_inputs).prompt.str(),
+            common_chat_templates_apply(tmpls.get(), max_inputs).prompt.str());
+    }
+
     {
         auto tmpls = read_templates("models/templates/KRAFTON-Raon-1-mini-preview.jinja");
         check(tmpls, basic(),                  "<|im_start|>assistant\n<think>\n");