Compare commits

..
17 Commits
Author SHA1 Message Date
Xuan-Son Nguyen 441d045986 server : unblock server_response readers on termination (#33404) 2026-12-01 12:51:32 +01:00
Georgi Gerganov 75bfc7de2e metal : keep the MUL_MAT weight scale off skipped MoE slots (#33430)
* metal : keep skipped MoE slots unscaled with a per-tensor scale

kernel_mul_mat_scale reads the expert ids only when the weight scale is
per-expert or per-channel-per-expert, so a per-tensor scale also scaled
the slots of a skipped expert. The MoE matmul kernels zero those slots,
which turns 0 * +inf into NaN and fails the MUL_MAT_ID scale_gran=3
tests. Always pass the ids for MUL_MAT_ID and separate the skip check
from the per-expert scale offset.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* metal : keep the matmul weight scale inside the matmul op

The scale pass had to be chained by hand after ggml_metal_op_mul_mat and
ggml_metal_op_mul_mat_id in the encoder switch, and the two cases dropped
its return value on the way. Make it a private tail step of both ops, the
same way kernel_mul_mm_id_map0 and kernel_mul_mm_id_zero belong to
ggml_metal_op_mul_mat_id, and assert the invariant that made ignoring the
fused result safe: a scaled matmul never fuses a following ADD.

No functional change.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)
2026-12-01 12:37:31 +02:00
MichelRosselli a3f7cb2b9a 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
2026-12-01 11:35:03 +01:00
ravel7524 8f24c2288a vulkan: enable split-K for GQA batches above the tile row count (#32097)
* vulkan: enable split-K for GQA steps above tile row count

Assisted-by: Codex

* Simplify test cases for flash attention extension

Removed nested loops for test cases with variable parameters and replaced with a single test case for specific values.
2026-12-01 11:16:40 +01:00
frogscooper 2efe7f1d41 jinja : make functions truthy and give them no attributes (#33419) 2026-12-01 10:16:55 +01:00
SIDDHARTH UandSiddharth U dee778bd0b grammar : fix builder crash on invalid minItems/maxItems (#29462) (#29497)
* bug: fix grammar builder crash on invalid minItems/maxItems (#29462)

When parsing JSON schemas with `minItems` greater than `maxItems`
(e.g., `{"minItems": 10, "maxItems": 2}`), or direct GBNF like `{10,2}`,
`llama-grammar.cpp` previously underflowed the `(max_times - min_times)`
subtraction because it was evaluating it in unsigned arithmetic
without a `min_times <= max_times` check. This underflow led to
allocating quintillions of grammar rules, resulting in an immediate
OOM / `std::bad_alloc`.

Additionally, the `json-schema-to-grammar.cpp` builder lacked a check
to cap `max_items = min_items` when the JSON schema contained logically
contradictory inputs, leading to out-of-order bounds being forwarded to
the grammar parser.

This PR adds:
1. A guard in `json-schema-to-grammar.cpp` that sets
   `max_items = min_items` if `min_items > max_items`.
2. A strict runtime validation in `llama-grammar.cpp` that explicitly
   rejects out-of-order repetition bounds with a `std::runtime_error`,
   preventing catastrophic memory allocation.

Closes #29462

* grammar : simplify min/max repetition check (review feedback)

---------

Co-authored-by: Siddharth U <cid@example.com>
2026-12-01 10:14:52 +01:00
Leon ba16f3f8c9 vulkan : fix large ROLL shifts (#32876) 2026-12-01 10:01:54 +01:00
Masashi Yoshimura 103b19e9ff webgpu: split the GDN replay into a separate pipeline (#33289)
* add replay pipeline to GDN

* add switching between 1-pass and 2-pass path depding on the maxStorageBuffersPerShaderStage of the platform.
2026-12-01 09:22:15 +01:00
Georgi Gerganov 7dca4a8daa qwen4exp : simplify the PLE conv graph (#33380)
* qwen4exp : remove redundant cont in ple conv output

conv_out is contiguous after ggml_silu, so the extra ggml_cont before the reshape is unnecessary.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* qwen4exp : avoid the permute copy in the PLE conv

Fold the sequence axis into the channel axis so im2col writes the layout needed by the batched matmul directly, removing the cont(permute(x)) copy.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* qwen4exp : load the PLE conv kernel as 3D

Use TENSOR_ALLOW_RESHAPE to load ple_conv1d as [kern, 1, hc_dim], so the graph uses it directly without a reshape or f32 cast. Update the tensor op mapping to GGML_OP_MUL_MAT for buffer selection with the 3D shape.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* qwen4exp : use a standalone shape tensor for im2col

ggml_im2col only needs the kernel shape, so create the [kern, 1] tensor directly instead of viewing the PLE conv weight.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
2026-12-01 09:26:03 +02:00
Aman GuptaandClaude Opus 5.5 ce94c097bc kv-cache : reuse SWA cells shared by several sequences once masked for all of them (#32309)
In a unified KV cache, cells that are shared between sequences (e.g. a
common prompt copied with llama_memory_seq_cp) were never considered by
find_slot, which only recycled SWA-masked cells with a single owner. The
shared cells stayed occupied forever and the SWA cache, sized as
n_swa*n_seq_max + n_ubatch, ran out of slots once the shared prefix grew
past the padding.

Allow find_slot to reuse a shared cell once it is SWA-masked for all of
its sequences, and let apply_ubatch purge the overwritten positions for
each of them.

Fixes #32258

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 08:26:03 +02:00
Kong Jiale a1973da637 ggml-cpu : vectorize the Mamba-2 SSM scan on RVV (#32448) 2026-12-01 13:42:44 +08:00
Aman Gupta 5b1ba66b59 CUDA : read K/V through kv_rows in the vec flash attention kernel (#32520)
* CUDA : read K/V through kv_rows in the vec flash attention kernel

Without a bias only the MMA kernel read K/V through kv_rows. With a quantized, BF16 or F8_E4M3 cache it converted the whole K/V view to F16 on every call, so decode in a unified cache slowed down with the cells of all sequences, idle ones included.

The vec kernel already reads K/V through kv_rows for the indexed bias. Its kv_rows variant is now also instantiated without a bias (one query per slice, no softcap), and the kv_rows dispatch takes it for non-F16 K/V with one query per slice. F16 K/V and slices of several queries keep the MMA kernel.

tests : kv_rows cases with one query per slice for f16/bf16/q8_0/q4_0

ref #32181

* CUDA : take the vec kv_rows path only for K/V pairs with a compiled vec kernel

Without a compiled vec kernel for the K/V pair (the default GGML_CUDA_FA_QUANTS has only same-type pairs), the vec kernel falls back to f16 and converts the whole cache, which is slower than the MMA kernel. Mixed pairs such as q8_0/q4_0 keep the MMA kernel as on master. The lookup also covers the head sizes of the vec kernel.
2026-12-01 12:40:27 +08:00
Aman Gupta 713fee7fb0 llama : budget graph nodes for KV cache rotation (#33382) 2026-12-01 11:01:37 +08:00
cwriterandcwriter e89795bf78 sycl: Add GDN Replay support (#32944)
* sycl : replay the pending gated delta net tokens in the kernel

Assisted-by: Codex
Assisted-by: Claude Opus 5.5

* sycl : fuse the state and pending input cpys into the replay gated delta net kernel

Assisted-by: Claude Opus 5.5

* sycl : stage tensor reads through pinned memory

Port of the download half of 6511ba973 (prompt-cache-speed) to master: reads
of 64 KiB or more go through a pinned block, up to four workers each own a
1 MiB slot, queue the device copy, touch the destination pages while it is in
flight, then copy out. The original applied from 1 MiB; the recurrent-state
reads of a GDN checkpoint are 64 KiB to 3 MiB per tensor.

Assisted-by: Claude Opus 5.5

* sycl : gated delta net with separate q and k strides

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: cwriter <cwriter@localhost>
2026-11-30 18:48:27 -08:00
Xuan-Son Nguyen 1f1e6cb26a unicode : fix \p{Lu} and \p{Ll} (#33403) 2026-12-01 00:50:42 +01:00
Sigbjørn Skjæret db503b89fd server : fix build (#33410) 2026-12-01 00:27:09 +01:00
Luc PommeretandLuc Pommeret 78c9ca4b06 llama : allow prism.hadamard folded weights for LFM3 (#33387)
* llama : allow prism.hadamard folded weights for LFM3

Add LLM_ARCH_LFM3 to the architectures that may load Hadamard-folded
weights, and accept the LFM3 short-convolution projections
(shortconv.in_proj, shortconv.out_proj) as foldable. Both are built
through build_lora_mm in lfm-base.cpp, so the input transform is applied.
The Python converter filter is aligned with the loader.

Assisted-by: Claude Opus 5.5

* llama : accept shortconv projections as Hadamard-foldable kinds

Drop the LFM3-only condition: shortconv.in_proj and shortconv.out_proj
are built through build_lora_mm, so list them with the other foldable
kinds in the loader and the converter.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Luc Pommeret <zlucpommeret@gmail.com>
2026-11-30 23:58:38 +01:00
58 changed files with 3281 additions and 409 deletions
+7
View File
@@ -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 &&
+6
View File
@@ -1571,6 +1571,12 @@ const func_builtins & value_undefined_t::get_builtins() const {
return builtins;
}
const func_builtins & value_func_t::get_builtins() const {
// no attributes, so func.foo and func['foo'] are undefined
static const func_builtins no_builtins = {};
return no_builtins;
}
//////////////////////////////////
+2
View File
@@ -770,7 +770,9 @@ struct value_func_t : public value_t {
return val_func(new_args);
}
virtual std::string type() const override { return "Function"; }
virtual bool as_bool() const override { return true; } // like python, a function is truthy
virtual std::string as_repr() const override { return type() + "<" + name + ">(" + (arg0 ? arg0->as_repr() : "") + ")"; }
virtual const func_builtins & get_builtins() const override;
virtual bool is_hashable() const override { return false; }
virtual hasher unique_hash() const noexcept override {
// Note: this is unused for now, we don't support function as object keys
+3
View File
@@ -16,6 +16,9 @@
using json = common_json;
static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
if (min_items > max_items) {
max_items = min_items;
}
auto has_max = max_items != std::numeric_limits<int>::max();
if (max_items == 0) {
+171
View File
@@ -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;
}
+2
View File
@@ -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);
+1
View File
@@ -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
+3 -1
View File
@@ -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",
+74
View File
@@ -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)
+2
View File
@@ -1071,6 +1071,7 @@ class ModelBase:
gguf.MODEL_ARCH.QWEN35,
gguf.MODEL_ARCH.QWEN35MOE,
gguf.MODEL_ARCH.QWEN3NEXT,
gguf.MODEL_ARCH.LFM3,
}
if self.model_arch not in _HADAMARD_ARCHS:
raise ValueError(
@@ -1085,6 +1086,7 @@ class ModelBase:
r"|ffn_gate_exps|ffn_up_exps|ffn_down_exps|ffn_gate_up_exps"
r"|ffn_gate_shexp|ffn_up_shexp|ffn_down_shexp"
r"|ssm_out"
r"|shortconv\.in_proj|shortconv\.out_proj"
r")\.weight"
)
weight_names: list[str] = []
-38
View File
@@ -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)
+24 -2
View File
@@ -10251,8 +10251,30 @@ static void ggml_compute_forward_ssm_scan_f32(
sumf = GGML_F32xt_REDUCE_ONE(sum);
#elif defined(__riscv_v)
// todo: RVV implementation
const int np = 0;
int64_t np = 0;
if (!params->use_ref) {
const size_t vlmax = __riscv_vsetvlmax_e32m4();
vfloat32m4_t sum = __riscv_vfmv_v_f_f32m4(0.0f, vlmax);
for (int64_t i0 = 0; i0 < nc; ) {
const size_t vl = __riscv_vsetvl_e32m4(nc - i0);
vfloat32m4_t t0 = __riscv_vle32_v_f32m4(s0 + i0 + ii*nc, vl);
vfloat32m4_t t1 = __riscv_vle32_v_f32m4(B + i0 + g*nc, vl);
vfloat32m4_t t2 = __riscv_vle32_v_f32m4(C + i0 + g*nc, vl);
t0 = __riscv_vfmul_vf_f32m4(t0, dA, vl);
t1 = __riscv_vfmul_vf_f32m4(t1, x_dt, vl);
t0 = __riscv_vfadd_vv_f32m4(t0, t1, vl);
sum = __riscv_vfmacc_vv_f32m4_tu(sum, t0, t2, vl);
__riscv_vse32_v_f32m4(s + i0 + ii*nc, t0, vl);
i0 += vl;
}
vfloat32m1_t zero = __riscv_vfmv_v_f_f32m1(0.0f, 1);
sumf = __riscv_vfmv_f_s_f32m1_f32(__riscv_vfredusum_vs_f32m4_f32m1(sum, zero, vlmax));
np = nc;
}
#else
const int np = (nc & ~(GGML_F32_STEP - 1));
+8
View File
@@ -574,6 +574,11 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc);
const int nwarps = nthreads / WARP_SIZE;
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, false>;
if constexpr (cols_per_block == 1 && !use_logit_softcap) {
if (dst->src[5]) {
fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, true>;
}
}
if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) {
if (ggml_flash_attn_ext_bias_is_indexed(dst)) {
fattn_kernel = dst->src[5] ? flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, true>
@@ -594,6 +599,9 @@ void ggml_cuda_flash_attn_ext_vec_case(ggml_backend_cuda_context & ctx, ggml_ten
float logit_softcap;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
// the kv_rows variant exists for one query per sequence without softcap
GGML_ASSERT(!dst->src[5] || (Q->ne[1] == 1 && logit_softcap == 0.0f));
if (Q->ne[1] == 1) {
constexpr int cols_per_block = 1;
if (logit_softcap == 0.0f) {
+16 -3
View File
@@ -765,10 +765,23 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
}
}
// without a bias only the MMA kernel reads K/V through kv_rows
// without a bias only the MMA and vec kernels read K/V through kv_rows
if (kv_rows) {
return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ?
BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
if (!(GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask)) {
return BEST_FATTN_KERNEL_NONE;
}
float logit_softcap = 0.0f;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
// the vec kernel reads quantized/bf16/f8 K/V in place, the MMA kernel would convert the whole cache to f16
// only for K/V pairs with a compiled vec kernel, the f16 fallback of the vec kernel also converts the whole cache
const bool vec_rows = n_kv % FATTN_KQ_STRIDE == 0 &&
(K->type != GGML_TYPE_F16 || V->type != GGML_TYPE_F16) && K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 &&
Q->ne[1] == 1 && logit_softcap == 0.0f && ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr;
if (vec_rows) {
return BEST_FATTN_KERNEL_VEC;
}
return Q->ne[0] != 40 && Q->ne[0] != 72 ? BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
}
// For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes:
+1
View File
@@ -302,6 +302,7 @@ typedef struct {
uint64_t ids_nb0;
uint64_t ids_nb1;
int32_t use_ids;
int32_t has_ids;
} ggml_metal_kargs_mul_mat_scale;
typedef struct {
+78 -56
View File
@@ -388,12 +388,10 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
case GGML_OP_MUL_MAT:
{
n_fuse = ggml_metal_op_mul_mat(ctx, idx);
ggml_metal_op_mul_mat_scale(ctx, idx);
} break;
case GGML_OP_MUL_MAT_ID:
{
n_fuse = ggml_metal_op_mul_mat_id(ctx, idx);
ggml_metal_op_mul_mat_scale(ctx, idx);
} break;
case GGML_OP_GET_ROWS:
{
@@ -2771,7 +2769,59 @@ static int ggml_metal_op_mul_mat_mv(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
// apply the weight scale of a MUL_MAT or MUL_MAT_ID built by ggml_mul_mat_ext / ggml_mul_mat_id_ext
// the matmul kernels write the unscaled result, so this pass runs after them with a barrier
static void ggml_metal_op_mul_mat_scale(ggml_metal_op_t ctx, const ggml_tensor * op) {
const ggml_tensor * scale = ggml_get_src_scale(op, 0);
if (scale == nullptr) {
return;
}
ggml_metal_library_t lib = ctx->lib;
ggml_metal_encoder_t enc = ctx->enc;
GGML_ASSERT(scale->type == GGML_TYPE_F32);
GGML_ASSERT(op->type == GGML_TYPE_F32);
GGML_ASSERT(ggml_is_contiguous_rows(op));
const ggml_tensor * src0 = op->src[0];
const ggml_tensor * ids = op->op == GGML_OP_MUL_MAT_ID ? op->src[2] : nullptr;
const bool has_ids = ids != nullptr;
const bool per_channel_expert = has_ids && scale->ne[0] == op->ne[0] && scale->ne[1] == src0->ne[2];
const bool per_expert = has_ids && (ggml_nelements(scale) == src0->ne[2] || per_channel_expert);
const bool per_channel = per_expert ? per_channel_expert : scale->ne[0] == op->ne[0] && ggml_nelements(scale) > 1;
ggml_metal_kargs_mul_mat_scale args = {
/*.ne0 =*/ op->ne[0],
/*.ne2 =*/ op->ne[2],
/*.nb1 =*/ op->nb[1],
/*.nb2 =*/ op->nb[2],
/*.nb3 =*/ op->nb[3],
/*.s_nb0 =*/ per_channel ? scale->nb[0] : 0,
/*.s_nb1 =*/ per_expert ? (per_channel_expert ? scale->nb[1] : scale->nb[0]) : 0,
/*.ids_nb0 =*/ has_ids ? ids->nb[0] : 0,
/*.ids_nb1 =*/ has_ids ? ids->nb[1] : 0,
/*.use_ids =*/ per_expert,
/*.has_ids =*/ has_ids,
};
ggml_metal_op_concurrency_reset(ctx);
auto pipeline = ggml_metal_library_get_pipeline_mul_mat_scale(lib);
ggml_metal_encoder_set_pipeline(enc, pipeline);
ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(scale), 1);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(has_ids ? ids : scale), 2);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), 3);
const int nth = std::min<int64_t>(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), op->ne[0]);
ggml_metal_encoder_dispatch_threadgroups(enc, op->ne[1], op->ne[2]*op->ne[3], 1, nth, 1, 1);
}
static int ggml_metal_op_mul_mat_impl(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
ggml_metal_library_t lib = ctx->lib;
@@ -2957,6 +3007,18 @@ int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
const int n_fuse = ggml_metal_op_mul_mat_impl(ctx, idx);
GGML_ASSERT(ggml_get_src_scale(op, 0) == nullptr || n_fuse == 1);
ggml_metal_op_mul_mat_scale(ctx, op);
return n_fuse;
}
// upper bound on the number of entry tiles emitted by kernel_mul_mm_id_map0: the full tiles
// over all entries plus at most one partial tile per expert
static int64_t ggml_metal_op_mul_mat_id_max_tiles(const ggml_tensor * op) {
@@ -2992,7 +3054,7 @@ size_t ggml_metal_op_mul_mat_id_extra_ids(const ggml_tensor * op) {
return ggml_type_size(GGML_TYPE_I32)*(ne20*ne21 + ne02);
}
int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
static int ggml_metal_op_mul_mat_id_impl(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
ggml_metal_library_t lib = ctx->lib;
@@ -3195,6 +3257,18 @@ int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
const int n_fuse = ggml_metal_op_mul_mat_id_impl(ctx, idx);
GGML_ASSERT(ggml_get_src_scale(op, 0) == nullptr || n_fuse == 1);
ggml_metal_op_mul_mat_scale(ctx, op);
return n_fuse;
}
int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
@@ -3241,58 +3315,6 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat_scale(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
const ggml_tensor * scale = ggml_get_src_scale(op, 0);
if (scale == nullptr) {
return 1;
}
ggml_metal_library_t lib = ctx->lib;
ggml_metal_encoder_t enc = ctx->enc;
GGML_ASSERT(scale->type == GGML_TYPE_F32);
GGML_ASSERT(op->type == GGML_TYPE_F32);
GGML_ASSERT(ggml_is_contiguous_rows(op));
const ggml_tensor * src0 = op->src[0];
const ggml_tensor * ids = op->op == GGML_OP_MUL_MAT_ID ? op->src[2] : nullptr;
const bool per_channel_expert = ids && scale->ne[0] == op->ne[0] && scale->ne[1] == src0->ne[2];
const bool per_expert = ids && (ggml_nelements(scale) == src0->ne[2] || per_channel_expert);
const bool per_channel = per_expert ? per_channel_expert : scale->ne[0] == op->ne[0] && ggml_nelements(scale) > 1;
ggml_metal_kargs_mul_mat_scale args = {
/*.ne0 =*/ op->ne[0],
/*.ne2 =*/ op->ne[2],
/*.nb1 =*/ op->nb[1],
/*.nb2 =*/ op->nb[2],
/*.nb3 =*/ op->nb[3],
/*.s_nb0 =*/ per_channel ? scale->nb[0] : 0,
/*.s_nb1 =*/ per_expert ? (per_channel_expert ? scale->nb[1] : scale->nb[0]) : 0,
/*.ids_nb0 =*/ per_expert ? ids->nb[0] : 0,
/*.ids_nb1 =*/ per_expert ? ids->nb[1] : 0,
/*.use_ids =*/ per_expert,
};
ggml_metal_op_concurrency_reset(ctx);
auto pipeline = ggml_metal_library_get_pipeline_mul_mat_scale(lib);
ggml_metal_encoder_set_pipeline(enc, pipeline);
ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(scale), 1);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(per_expert ? ids : scale), 2);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), 3);
const int nth = std::min<int64_t>(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), op->ne[0]);
ggml_metal_encoder_dispatch_threadgroups(enc, op->ne[1], op->ne[2]*op->ne[3], 1, nth, 1, 1);
return 1;
}
bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) {
assert(op->op == GGML_OP_FLASH_ATTN_EXT);
-1
View File
@@ -83,7 +83,6 @@ int ggml_metal_op_pool_2d (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_fwht (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat_id (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat_scale (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_add_id (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_flash_attn_ext (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_bin (ggml_metal_op_t ctx, int idx);
+5 -2
View File
@@ -219,12 +219,15 @@ kernel void kernel_mul_mat_scale(
device const char * s = scale;
if (args.use_ids) {
if (args.has_ids) {
// a skipped expert (id < 0) has zeroed output, do not scale it
const int32_t expert = *((device const int32_t *) (ids + i1*args.ids_nb0 + i2*args.ids_nb1));
if (expert < 0) {
return;
}
s += expert*args.s_nb1;
if (args.use_ids) {
s += expert*args.s_nb1;
}
}
device float * dst_row = (device float *) (dst + i1*args.nb1 + i2*args.nb2 + i3*args.nb3);
+192 -26
View File
@@ -22,6 +22,9 @@ static void launch_gated_delta_net_esimd(const float * q,
int64_t sq1,
int64_t sq2,
int64_t sq3,
int64_t sk1,
int64_t sk2,
int64_t sk3,
int64_t sv1,
int64_t sv2,
int64_t sv3,
@@ -52,7 +55,7 @@ static void launch_gated_delta_net_esimd(const float * q,
for (int t = 0; t < n_tokens; ++t) {
const simd<float, S_v> q_t = block_load<float, S_v>(q + iq3 * sq3 + t * sq2 + iq1 * sq1);
const simd<float, S_v> k_t = block_load<float, S_v>(k + iq3 * sq3 + t * sq2 + iq1 * sq1);
const simd<float, S_v> k_t = block_load<float, S_v>(k + iq3 * sk3 + t * sk2 + iq1 * sk1);
const float v_val = v[sequence * sv3 + t * sv2 + h_idx * sv1 + col];
const int64_t gb = sequence * sb3 + t * sb2 + h_idx * sb1;
const float g_val = exp(g[gb]);
@@ -78,8 +81,26 @@ static constexpr int gdn_warps = 2;
// State columns per warp when there are enough heads, see launch_gated_delta_net.
static constexpr int gdn_cols_wide = 4;
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
struct gdn_replay_args {
const float * pk; // [S_v, H_k, n_pend, n_seqs]
const float * pv; // [S_v, H, n_pend, n_seqs]
const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas
const int32_t * n_rep; // [n_seqs]
int64_t sk1, sk2, sk3; // head, token and seq strides in floats
int64_t sv1, sv2, sv3;
int64_t sg1, sg2, sg3;
int n_pend;
bool keep; // write the state after the replay, not the final one
// optional (not KDA): store the k, v, g, beta inputs of the new tokens as pending (fused cpys)
float * st[4];
int64_t st2[4]; // token stride in floats
int64_t st3[4]; // seq stride in floats
};
// C is the number of state columns per warp: a token's q/k shard is loaded once and shared by these columns.
template <int S_v, int C, bool KDA, bool keep_rs_t>
template <int S_v, int C, bool KDA, bool keep_rs_t, bool replay>
void gated_delta_net_sycl(const float * q,
const float * k,
const float * v,
@@ -93,6 +114,9 @@ void gated_delta_net_sycl(const float * q,
int64_t sq1,
int64_t sq2,
int64_t sq3,
int64_t sk1,
int64_t sk2,
int64_t sk3,
int64_t sv1,
int64_t sv2,
int64_t sv3,
@@ -103,7 +127,8 @@ void gated_delta_net_sycl(const float * q,
const sycl::uint3 rq3_magic,
float scale,
int64_t state_slot_stride,
int K) {
int K,
const gdn_replay_args rep) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const uint32_t h_idx = item_ct1.get_group(2);
const uint32_t sequence = item_ct1.get_group(1);
@@ -140,11 +165,79 @@ void gated_delta_net_sycl(const float * q,
}
}
if constexpr (replay) {
// the same state update as the main loop below, without the attention output
const int n_r = rep.n_rep[sequence];
const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1 + lane;
const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1 + col0;
const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1;
for (int t = 0; t < n_r; t++) {
const float * g_t = pgb + t * rep.sg2;
const float beta_val = pgb[(rep.n_pend + t) * rep.sg2];
float k_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
k_reg[r] = pk[t * rep.sk2 + r * warp_size];
}
if constexpr (!KDA) {
const float g_val = sycl::native::exp(*g_t);
#pragma unroll
for (int c = 0; c < C; c++) {
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
kv_shard += s_shard[c][r] * k_reg[r];
}
const float kv_col = warp_reduce_sum<warp_size>(kv_shard);
const float delta_col = (pv[t * rep.sv2 + c] - g_val * kv_col) * beta_val;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
s_shard[c][r] = g_val * s_shard[c][r] + k_reg[r] * delta_col;
}
}
} else {
float g_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
g_reg[r] = sycl::native::exp(g_t[r * warp_size + lane]);
}
#pragma unroll
for (int c = 0; c < C; c++) {
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
kv_shard += g_reg[r] * s_shard[c][r] * k_reg[r];
}
const float kv_col = warp_reduce_sum<warp_size>(kv_shard);
const float delta_col = (pv[t * rep.sv2 + c] - kv_col) * beta_val;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
s_shard[c][r] = g_reg[r] * s_shard[c][r] + k_reg[r] * delta_col;
}
}
}
}
if (rep.keep) {
float * out_col = state + col0 * S_v + lane;
#pragma unroll
for (int c = 0; c < C; c++) {
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
out_col[c * S_v + r * warp_size] = s_shard[c][r];
}
}
}
}
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
const float * qp = q + iq3 * sq3 + iq1 * sq1 + lane;
const float * kp = k + iq3 * sq3 + iq1 * sq1 + lane;
const float * kp = k + iq3 * sk3 + iq1 * sk1 + lane;
const float * vp = v + sequence * sv3 + h_idx * sv1 + col0;
const float * bp = beta + sequence * sb3 + h_idx * sb1;
const float * gp = g + (sequence * sb3 + h_idx * sb1) * (KDA ? S_v : 1);
@@ -173,7 +266,7 @@ void gated_delta_net_sycl(const float * q,
}
if (t + 1 < n_tokens) {
qp += sq2;
kp += sq2;
kp += sk2;
}
// Load outside the branch: the last token reads its own row again.
// A guarded load is 20% slower at 32 heads on Arc Pro B70.
@@ -190,6 +283,31 @@ void gated_delta_net_sycl(const float * q,
}
vp += sv2;
if constexpr (replay && !KDA) {
if (rep.st[0] != nullptr) {
// keep the inputs of this token pending: one work-group per k head writes k, each warp its v columns
const bool first_wg = item_ct1.get_group(0) == 0 && item_ct1.get_local_id(1) == 0;
if (first_wg && h_idx < neqk1_magic.z()) {
float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v + lane;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
dk[r * warp_size] = k_reg[r];
}
}
if (lane == 0) {
float * dv = rep.st[1] + sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col0;
#pragma unroll
for (int c = 0; c < C; c++) {
dv[c] = v_reg[c];
}
if (first_wg) {
rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t;
rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val;
}
}
}
}
// attn[col] = g * (S^T q)[col] + delta[col] * (k . q), so no reduction waits for delta
float kq_shard = 0.0f;
#pragma unroll
@@ -281,6 +399,9 @@ void gated_delta_net_sycl(const float * q,
}
if constexpr (!keep_rs_t) {
if (replay && rep.keep) {
return;
}
float * out_col = state + col0 * S_v + lane;
#pragma unroll
for (int c = 0; c < C; c++) {
@@ -292,7 +413,7 @@ void gated_delta_net_sycl(const float * q,
}
}
template <bool KDA, bool keep_rs_t>
template <bool KDA, bool keep_rs_t, bool replay>
static void launch_gated_delta_net(const float * q_d,
const float * k_d,
const float * v_d,
@@ -308,6 +429,9 @@ static void launch_gated_delta_net(const float * q_d,
int64_t sq1,
int64_t sq2,
int64_t sq3,
int64_t sk1,
int64_t sk2,
int64_t sk3,
int64_t sv1,
int64_t sv2,
int64_t sv3,
@@ -319,6 +443,7 @@ static void launch_gated_delta_net(const float * q_d,
float scale,
int64_t state_slot_stride,
int K,
const gdn_replay_args & rep,
dpct::queue_ptr stream) {
//TODO: Add chunked kernel for even faster pre-fill
const int warp_size = ggml_sycl_info().devices[ggml_sycl_get_device()].warp_size;
@@ -333,9 +458,9 @@ static void launch_gated_delta_net(const float * q_d,
dpct::dim3 block_dims(warp_size <= sv ? warp_size : sv, gdn_warps, 1);
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
gated_delta_net_sycl<sv, C, KDA, keep_rs_t>(
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sv1, sv2,
sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
gated_delta_net_sycl<sv, C, KDA, keep_rs_t, replay>(
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sk1, sk2, sk3, sv1, sv2,
sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
});
};
// gdn_cols_wide columns per warp cut the q/k loads but launch fewer warps, so with few heads 1 column is faster.
@@ -400,7 +525,6 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
GGML_ASSERT(ggml_is_contiguous_rows(src_q));
GGML_ASSERT(ggml_is_contiguous_rows(src_k));
GGML_ASSERT(ggml_is_contiguous_rows(src_v));
GGML_ASSERT(ggml_are_same_stride(src_q, src_k));
GGML_ASSERT(src_g->ne[0] == 1 || kda);
GGML_ASSERT(ggml_is_contiguous(src_g));
GGML_ASSERT(ggml_is_contiguous(src_beta));
@@ -410,6 +534,10 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
const int64_t sq1 = nbq1 / sizeof(float);
const int64_t sq2 = nbq2 / sizeof(float);
const int64_t sq3 = nbq3 / sizeof(float);
// k can have its own layout (a permuted or padded view), only its rows must be contiguous
const int64_t sk1 = nbk1 / sizeof(float);
const int64_t sk2 = nbk2 / sizeof(float);
const int64_t sk3 = nbk3 / sizeof(float);
const int64_t sv1 = nbv1 / sizeof(float);
const int64_t sv2 = nbv2 / sizeof(float);
const int64_t sv3 = nbv3 / sizeof(float);
@@ -433,35 +561,73 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
state_slot_stride = cache->slot_stride;
}
const ggml_tensor * src_pk = dst->src[6];
gdn_replay_args rep = {};
if (src_pk != nullptr) {
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const ggml_tensor * src_nr = dst->src[9];
GGML_ASSERT(K == 1);
GGML_ASSERT(src_pv != nullptr && src_pgb != nullptr && src_nr != nullptr);
GGML_ASSERT(src_pk->type == GGML_TYPE_F32 && src_pv->type == GGML_TYPE_F32 && src_pgb->type == GGML_TYPE_F32);
GGML_ASSERT(src_nr->type == GGML_TYPE_I32 && ggml_is_contiguous(src_nr) && ggml_nelements(src_nr) == n_seqs);
GGML_ASSERT(src_pk->nb[0] == sizeof(float) && src_pv->nb[0] == sizeof(float) && src_pgb->nb[0] == sizeof(float));
rep.pk = (const float *) src_pk->data;
rep.pv = (const float *) src_pv->data;
rep.pgb = (const float *) src_pgb->data;
rep.n_rep = (const int32_t *) src_nr->data;
rep.sk1 = src_pk->nb[1] / sizeof(float);
rep.sk2 = src_pk->nb[2] / sizeof(float);
rep.sk3 = src_pk->nb[3] / sizeof(float);
rep.sv1 = src_pv->nb[1] / sizeof(float);
rep.sv2 = src_pv->nb[2] / sizeof(float);
rep.sv3 = src_pv->nb[3] / sizeof(float);
rep.sg1 = src_pgb->nb[1] / sizeof(float);
rep.sg2 = src_pgb->nb[2] / sizeof(float);
rep.sg3 = src_pgb->nb[3] / sizeof(float);
rep.n_pend = ggml_get_op_params_i32(dst, 1);
rep.keep = ggml_get_op_params_i32(dst, 2) != 0;
for (int i = 0; i < 4; ++i) {
rep.st[i] = cache != nullptr ? cache->in_dst[i] : nullptr;
rep.st2[i] = cache != nullptr ? cache->in_nb2[i] : 0;
rep.st3[i] = cache != nullptr ? cache->in_nb3[i] : 0;
}
}
#ifdef GGML_SYCL_DMMV_HAS_ESIMD
if (!kda && S_v == 128 && g_ggml_sycl_enable_esimd && state_slot_stride % 4 == 0 && (uintptr_t) state_d % 16 == 0) {
if (src_pk == nullptr && !kda && S_v == 128 && g_ggml_sycl_enable_esimd && state_slot_stride % 4 == 0 && (uintptr_t) state_d % 16 == 0) {
launch_gated_delta_net_esimd(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3,
sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
return;
}
#endif
#define GDN_LAUNCH(KDA, KEEP, REPLAY) \
launch_gated_delta_net<KDA, KEEP, REPLAY>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, S_v, H, n_tokens, \
n_seqs, sq1, sq2, sq3, sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, \
scale, state_slot_stride, K, rep, stream)
if (kda) {
if (keep_rs) {
launch_gated_delta_net<true, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, true, false);
} else if (src_pk != nullptr) {
GDN_LAUNCH(true, false, true);
} else {
launch_gated_delta_net<true, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, false, false);
}
} else {
if (keep_rs) {
launch_gated_delta_net<false, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, true, false);
} else if (src_pk != nullptr) {
GDN_LAUNCH(false, false, true);
} else {
launch_gated_delta_net<false, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, false, false);
}
}
#undef GDN_LAUNCH
}
void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
@@ -469,12 +635,12 @@ void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor *
}
void ggml_sycl_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/6);
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/dst->src[6] != nullptr ? 10 : 6);
ggml_sycl_op_gated_delta_net(ctx, dst);
}
void ggml_sycl_op_gated_delta_net_fused_cache(ggml_backend_sycl_context & ctx, ggml_tensor * dst,
ggml_sycl_gated_delta_net_fused_cache cache) {
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/6);
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/dst->src[6] != nullptr ? 10 : 6);
ggml_sycl_op_gated_delta_net_impl(ctx, dst, &cache);
}
+5
View File
@@ -9,6 +9,11 @@
struct ggml_sycl_gated_delta_net_fused_cache {
float * data; // rollback slot 0
int64_t slot_stride; // between rollback slots (0 when K==1)
// replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused
float * in_dst[4] = {};
int64_t in_nb2[4] = {}; // token stride in elements
int64_t in_nb3[4] = {}; // seq stride in elements
};
void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst);
+116 -5
View File
@@ -14,6 +14,7 @@
#include <array>
#include <assert.h>
#include <atomic>
#include <thread>
#include <cctype>
#include <cinttypes>
#include <cstddef>
@@ -747,6 +748,8 @@ struct ggml_backend_sycl_buffer_context {
optimize_feature opt_feature;
std::vector<ggml_tensor_extra_gpu *> tensor_extras;
host_staging staging;
// pinned block for get_tensor, one slot per download worker
char * download_staging = nullptr;
bool is_usm_system;
ggml_backend_sycl_buffer_context(int device, void * dev_ptr, queue_ptr stream, bool is_usm_system) :
@@ -772,6 +775,10 @@ struct ggml_backend_sycl_buffer_context {
~ggml_backend_sycl_buffer_context() {
drop_host_staging();
if (download_staging != nullptr) {
sycl::free(download_staging, *stream);
download_staging = nullptr;
}
if (dev_ptr != nullptr) {
ggml_sycl_set_device(device);
if (is_usm_system)
@@ -980,6 +987,54 @@ catch (sycl::exception const &exc) {
std::exit(1);
}
// Reads go through a pinned block, as a copy into pageable memory is slow, and the caller often hands over fresh
// memory, where the first write to each 4 KiB page takes a page fault. Each worker owns one slot and loops over the
// chunks: queue the device copy, touch the destination pages while it is in flight, wait, copy out. So the faults
// overlap the transfer and run on several threads. Returns false when the pinned block is not available.
static bool ggml_sycl_buffer_download_staged(ggml_backend_sycl_buffer_context * ctx, char * dst, const char * src,
size_t size) {
constexpr size_t min_size = 64*1024;
constexpr size_t chunk = 1*1024*1024;
constexpr size_t n_max = 4;
constexpr size_t page = 4096;
if (size < min_size) {
return false;
}
sycl::queue & q = *ctx->stream;
if (ctx->download_staging == nullptr) {
ctx->download_staging = (char *) sycl::malloc_host(n_max * chunk, q);
if (ctx->download_staging == nullptr) {
return false;
}
}
const size_t n_chnk = (size + chunk - 1) / chunk;
const size_t n_work = std::min(n_max, n_chnk);
std::atomic<size_t> next{ 0 };
auto work = [&](size_t w) {
char * stage = ctx->download_staging + w * chunk;
for (size_t i = next++; i < n_chnk; i = next++) {
const size_t off = i * chunk;
const size_t n = std::min(chunk, size - off);
sycl::event ev = q.memcpy(stage, src + off, n);
for (size_t j = 0; j < n; j += page) {
((volatile char *) dst)[off + j] = 0;
}
ev.wait_and_throw();
memcpy(dst + off, stage, n);
}
};
std::vector<std::thread> workers;
for (size_t w = 1; w < n_work; ++w) {
workers.emplace_back(work, w);
}
work(0);
for (auto & t : workers) {
t.join();
}
return true;
}
static void ggml_backend_sycl_buffer_get_tensor(ggml_backend_buffer_t buffer,
const ggml_tensor *tensor,
void *data, size_t offset,
@@ -992,9 +1047,11 @@ static void ggml_backend_sycl_buffer_get_tensor(ggml_backend_buffer_t buffer,
ggml_sycl_set_device(ctx->device);
auto stream = dpct::dev_mgr::instance().get_device(ctx->device).default_queue();
SYCL_CHECK(CHECK_TRY_ERROR(
stream.memcpy(data, (const char *)tensor->data + offset, size)
.wait()));
if (!ggml_sycl_buffer_download_staged(ctx, (char *) data, (const char *) tensor->data + offset, size)) {
SYCL_CHECK(CHECK_TRY_ERROR(
stream.memcpy(data, (const char *)tensor->data + offset, size)
.wait()));
}
}
catch (sycl::exception const &exc) {
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
@@ -6657,8 +6714,62 @@ static int ggml_sycl_try_gdn_cache_fusion(const ggml_cgraph * cgraph, int node_i
return 0;
}
// replay: the kernel reads the pending inputs (src[6..8]) while it writes the cache, so they must not share memory
const auto overlaps = [](const ggml_tensor * x, const ggml_tensor * y) {
const char * x0 = (const char *) x->data;
const char * y0 = (const char *) y->data;
return x0 < y0 + ggml_nbytes(y) && y0 < x0 + ggml_nbytes(x);
};
for (int s = 6; s <= 8; ++s) {
if (gdn->src[s] != nullptr && overlaps(gdn->src[s], dst)) {
return 0;
}
}
fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest)
fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
// replay (not KDA): the next 4 real nodes may store the k, v, g, beta inputs into the pending rows
if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) {
float * in_dst[4];
int64_t in_nb2[4];
int64_t in_nb3[4];
int skip_in = skip;
int n_in = 0;
for (int j = node_idx + skip + 1; n_in < 4 && j < cgraph->n_nodes; ++j) {
const ggml_tensor * n = cgraph->nodes[j];
if (ggml_sycl_is_view_or_noop(n) || (n->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
continue;
}
const ggml_tensor * in = gdn->src[1 + n_in];
const ggml_tensor * s0 = n->src[0];
const ggml_tensor * d = n->src[1];
// the cpy reads the whole input, directly or through a view of the same data
const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) &&
ggml_are_same_stride(s0, in));
if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in ||
d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) ||
d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) ||
d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float) ||
overlaps(d, gdn->src[6]) || overlaps(d, gdn->src[7]) || overlaps(d, gdn->src[8])) {
break;
}
in_dst[n_in] = (float *) d->data;
in_nb2[n_in] = d->nb[2] / sizeof(float);
in_nb3[n_in] = d->nb[3] / sizeof(float);
skip_in = j - node_idx;
++n_in;
}
if (n_in == 4) {
for (int c = 0; c < 4; ++c) {
fused_state_cpy.in_dst[c] = in_dst[c];
fused_state_cpy.in_nb2[c] = in_nb2[c];
fused_state_cpy.in_nb3[c] = in_nb3[c];
}
skip = skip_in;
}
}
return skip;
}
@@ -7718,8 +7829,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
case GGML_OP_OPT_STEP_SGD:
return true;
case GGML_OP_GATED_DELTA_NET:
// replay of pending tokens (op param 1) is not implemented
return ggml_get_op_params_i32(op, 1) == 0;
// replay of pending tokens (src[6..9]) always has a single state slot
return op->src[6] == nullptr || ggml_get_op_params_i32(op, 0) == 1;
case GGML_OP_SSM_CONV:
return op->type == GGML_TYPE_F32 &&
op->src[0]->type == GGML_TYPE_F32 &&
+8 -10
View File
@@ -9620,7 +9620,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
// Match the shader's per-split block count so no split is empty.
const uint32_t per_blocks = CEIL_DIV(total_blocks, split_k);
split_k = CEIL_DIV(total_blocks, per_blocks);
} else if (gqa_ratio > 1 && workgroups_x <= Br) {
} else if (gqa_ratio > 1) {
split_k = shader_core_count * 2 / (workgroups_x * workgroups_y * workgroups_z);
} else if (gqa_ratio <= 1) {
uint32_t total_wgs_no_split = Tr * workgroups_y * workgroups_z;
@@ -12446,16 +12446,14 @@ void ggml_vk_pad_reflect_1d(ggml_backend_vk_context * ctx, vk_context& subctx, c
}
void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
const int32_t s0 = ggml_get_op_params_i32(dst, 0);
const int32_t s1 = ggml_get_op_params_i32(dst, 1);
const int32_t s2 = ggml_get_op_params_i32(dst, 2);
const int32_t s3 = ggml_get_op_params_i32(dst, 3);
const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
memcpy(&p.param1, &s01_packed, sizeof(float));
memcpy(&p.param2, &s23_packed, sizeof(float));
float * params[] = { &p.param1, &p.param2, &p.param3, &p.param4 };
for (int i = 0; i < 4; ++i) {
const int64_t shift = ggml_get_op_params_i32(dst, i);
const uint32_t normalized = uint32_t(shift < 0 ? shift + dst->ne[i] : shift);
// The shader reads the integer bits from the float slots.
memcpy(params[i], &normalized, sizeof(normalized));
}
ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
}
+6 -18
View File
@@ -5,13 +5,8 @@
layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
uint wrap_idx(int i, uint ne) {
if (i < 0) {
return i + ne;
} else if (i >= ne) {
return i - ne;
}
return i;
uint roll_idx(uint i, uint shift, uint ne) {
return i >= shift ? i - shift : ne - (shift - i);
}
void main() {
@@ -27,17 +22,10 @@ void main() {
const uint i1 = fastdiv(idx - i3_offset - i2_offset, p.ne1_0mp, fastdiv_L(p.ne1_Ls, 2));
const uint i0 = idx - i3_offset - i2_offset - i1*p.ne10;
const uint p1 = floatBitsToUint(p.param1);
const uint p2 = floatBitsToUint(p.param2);
const int s0 = int(p1 >> 16) - 0x8000;
const int s1 = int(p1 & 0xFFFF) - 0x8000;
const int s2 = int(p2 >> 16) - 0x8000;
const int s3 = int(p2 & 0xFFFF) - 0x8000;
const uint i00 = wrap_idx(int(i0) - s0, p.ne10);
const uint i01 = wrap_idx(int(i1) - s1, p.ne11);
const uint i02 = wrap_idx(int(i2) - s2, p.ne12);
const uint i03 = wrap_idx(int(i3) - s3, p.ne13);
const uint i00 = roll_idx(i0, floatBitsToUint(p.param1), p.ne10);
const uint i01 = roll_idx(i1, floatBitsToUint(p.param2), p.ne11);
const uint i02 = roll_idx(i2, floatBitsToUint(p.param3), p.ne12);
const uint i03 = roll_idx(i3, floatBitsToUint(p.param4), p.ne13);
const uint a_idx = i03*p.nb03 + i02*p.nb02 + i01*p.nb01 + i00*p.nb00;
const uint d_idx = i3 *p.nb13 + i2 *p.nb12 + i1 *p.nb11 + i0 *p.nb10;
@@ -86,6 +86,7 @@ struct ggml_webgpu_shader_lib_context {
ggml_tensor * dst_fuse;
uint32_t max_wg_size;
uint32_t max_storage_buffers = 0;
size_t wg_mem_limit_bytes = 0;
bool supports_subgroups = false;
bool supports_subgroup_matrix = false;
@@ -448,16 +449,26 @@ struct ggml_webgpu_im2col_pipeline_key_hash {
};
/** Gated Delta Net **/
// check whether the replay of pending tokens runs in a separate pass
// the single pass binds 7 inputs (q, k, v, g, beta, dst, state), the fused cache and the 4 replay inputs
inline bool ggml_webgpu_gated_delta_net_split_replay(const ggml_tensor * op,
bool fused_cache,
uint32_t max_storage_buffers) {
return op->src[6] != nullptr && 7u + (fused_cache ? 1u : 0u) + 4u > max_storage_buffers;
}
struct ggml_webgpu_gated_delta_net_pipeline_key {
int type;
int s_v;
int kda;
bool fused_cache;
bool replay;
bool replay_split;
bool operator==(const ggml_webgpu_gated_delta_net_pipeline_key & other) const {
return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache &&
replay == other.replay;
replay == other.replay && replay_split == other.replay_split;
}
};
@@ -468,6 +479,7 @@ struct ggml_webgpu_gated_delta_net_pipeline_key_hash {
ggml_webgpu_hash_combine(seed, key.s_v);
ggml_webgpu_hash_combine(seed, key.kda);
ggml_webgpu_hash_combine(seed, key.replay);
ggml_webgpu_hash_combine(seed, key.replay_split);
return seed;
}
};
@@ -1320,12 +1332,16 @@ class ggml_webgpu_shader_lib {
webgpu_pipeline,
ggml_webgpu_gated_delta_net_pipeline_key_hash>
gated_delta_net_pipelines; // type/S_v/kda
std::unordered_map<ggml_webgpu_gated_delta_net_pipeline_key,
webgpu_pipeline,
ggml_webgpu_gated_delta_net_pipeline_key_hash>
gated_delta_net_replay_pipelines; // type/S_v/kda
std::unordered_map<ggml_webgpu_pad_pipeline_key, webgpu_pipeline, ggml_webgpu_pad_pipeline_key_hash>
pad_pipelines; // circular/non-circular
pad_pipelines; // circular/non-circular
std::unordered_map<ggml_webgpu_binary_pipeline_key, webgpu_pipeline, ggml_webgpu_binary_pipeline_key_hash>
binary_pipelines; // type/op/inplace/overlap/src_overlap
binary_pipelines; // type/op/inplace/overlap/src_overlap
std::unordered_map<ggml_webgpu_add_id_pipeline_key, webgpu_pipeline, ggml_webgpu_add_id_pipeline_key_hash>
add_id_pipelines; // inplace
add_id_pipelines; // inplace
std::unordered_map<ggml_webgpu_mul_mat_scale_pipeline_key,
webgpu_pipeline,
ggml_webgpu_mul_mat_scale_pipeline_key_hash>
@@ -2047,6 +2063,8 @@ class ggml_webgpu_shader_lib {
key.kda = context.src3->ne[0] == context.src2->ne[0];
key.fused_cache = context.dst_fuse != nullptr;
key.replay = context.dst->src[6] != nullptr;
key.replay_split =
ggml_webgpu_gated_delta_net_split_replay(context.dst, key.fused_cache, context.max_storage_buffers);
auto it = gated_delta_net_pipelines.find(key);
if (it != gated_delta_net_pipelines.end()) {
@@ -2074,7 +2092,10 @@ class ggml_webgpu_shader_lib {
variant += "_fused_cache";
}
if (key.replay) {
if (key.replay_split) {
defines.push_back("REPLAY_SPLIT");
variant += "_replay_split";
} else if (key.replay) {
defines.push_back("REPLAY");
variant += "_replay";
}
@@ -2088,6 +2109,43 @@ class ggml_webgpu_shader_lib {
return gated_delta_net_pipelines[key];
}
webgpu_pipeline get_gated_delta_net_replay_pipeline(const ggml_webgpu_shader_lib_context & context) {
ggml_webgpu_gated_delta_net_pipeline_key key = {};
key.type = context.dst->type;
key.s_v = (int) context.src2->ne[0];
key.kda = context.src3->ne[0] == context.src2->ne[0];
key.replay = true;
auto it = gated_delta_net_replay_pipelines.find(key);
if (it != gated_delta_net_replay_pipelines.end()) {
return it->second;
}
std::vector<std::string> defines;
std::string variant = "gated_delta_net_replay";
switch (key.type) {
case GGML_TYPE_F32:
variant += "_f32";
break;
default:
GGML_ABORT("Unsupported type for gated_delta_net_replay shader");
}
if (key.kda) {
defines.push_back("KDA");
variant += "_kda";
}
defines.push_back("S_V=" + std::to_string(key.s_v) + "u");
defines.push_back("WG_SIZE=" + std::to_string(key.s_v) + "u");
auto processed = preprocessor.preprocess(wgsl_gated_delta_net_replay, defines);
webgpu_pipeline pipeline = ggml_webgpu_create_pipeline(device, processed, variant);
gated_delta_net_replay_pipelines[key] = pipeline;
return gated_delta_net_replay_pipelines[key];
}
webgpu_pipeline get_arange_pipeline(const ggml_webgpu_shader_lib_context & context) {
auto it = arange_pipelines.find(1);
if (it != arange_pipelines.end()) {
+56 -24
View File
@@ -1569,11 +1569,6 @@ static webgpu_encoded_op ggml_webgpu_ssm_scan(webgpu_context & ctx,
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
}
// storage buffers of the gated delta net shader: q, k, v, g, beta, state and dst, the fused cache, then the replay inputs
static uint32_t ggml_webgpu_gated_delta_net_n_storage_buffers(const ggml_tensor * op, bool fused_cache) {
return 7 + (fused_cache ? 1 : 0) + (op->src[6] != nullptr ? 4 : 0);
}
static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
ggml_tensor * src0,
ggml_tensor * src1,
@@ -1591,7 +1586,8 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
shader_lib_ctx.src4 = src4;
shader_lib_ctx.dst = dst;
shader_lib_ctx.dst_fuse = dst_fuse;
shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
shader_lib_ctx.max_storage_buffers = ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage;
webgpu_pipeline pipeline = ctx->shader_lib->get_gated_delta_net_pipeline(shader_lib_ctx);
@@ -1635,8 +1631,8 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
dst_fuse ? (uint32_t) (dst_fuse->nb[2] / ggml_type_size(dst_fuse->type)) : 0,
dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) : 0,
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 1) : 0,
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0,
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 1) : 0, // n_pend
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0, // keep
pend_k ? (uint32_t) (pend_k->nb[1] / ggml_type_size(pend_k->type)) : 0,
pend_k ? (uint32_t) (pend_k->nb[2] / ggml_type_size(pend_k->type)) : 0,
@@ -1654,23 +1650,63 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
std::vector<wgpu::BindGroupEntry> entries = {
ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src0), ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, src1),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, src2), ggml_webgpu_make_tensor_bind_group_entry(ctx, 3, src3),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 4, src4), ggml_webgpu_make_tensor_bind_group_entry(ctx, 5, src5),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 6, dst),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 4, src4), ggml_webgpu_make_tensor_bind_group_entry(ctx, 5, dst),
};
if (dst_fuse) {
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 6, dst_fuse));
}
if (pend_k) {
const uint32_t binding = dst_fuse ? 8 : 7;
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 0, pend_k));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 1, pend_v));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 2, pend_gb));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 3, n_rep));
if (!ggml_webgpu_gated_delta_net_split_replay(dst, dst_fuse != nullptr, shader_lib_ctx.max_storage_buffers)) {
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, entries.size(), src5));
if (pend_k) {
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, entries.size(), pend_k));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, entries.size(), pend_v));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, entries.size(), pend_gb));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, entries.size(), n_rep));
}
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs);
}
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs);
// split replay: a first pass runs the pending tokens and writes the state where the main pass starts
webgpu_pipeline replay_pipeline = ctx->shader_lib->get_gated_delta_net_replay_pipeline(shader_lib_ctx);
ggml_tensor * state_dst = dst_fuse ? dst_fuse : dst;
std::vector<uint32_t> replay_params = {
h,
(uint32_t) src0->ne[1],
dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) :
s_v * h * n_tokens * n_seqs,
(uint32_t) ggml_get_op_params_i32(dst, 1), // n_pend
(uint32_t) (pend_k->nb[1] / ggml_type_size(pend_k->type)),
(uint32_t) (pend_k->nb[2] / ggml_type_size(pend_k->type)),
(uint32_t) (pend_k->nb[3] / ggml_type_size(pend_k->type)),
(uint32_t) (pend_v->nb[1] / ggml_type_size(pend_v->type)),
(uint32_t) (pend_v->nb[2] / ggml_type_size(pend_v->type)),
(uint32_t) (pend_v->nb[3] / ggml_type_size(pend_v->type)),
(uint32_t) (pend_gb->nb[1] / ggml_type_size(pend_gb->type)),
(uint32_t) (pend_gb->nb[2] / ggml_type_size(pend_gb->type)),
(uint32_t) (pend_gb->nb[3] / ggml_type_size(pend_gb->type)),
};
std::vector<wgpu::BindGroupEntry> replay_entries = {
ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src5),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, pend_k),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 2, pend_v),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 3, pend_gb),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 4, n_rep),
ggml_webgpu_make_tensor_bind_group_entry(ctx, 5, state_dst),
};
return ggml_backend_webgpu_build_multi(
ctx, {
{ replay_pipeline, std::move(replay_params), std::move(replay_entries), { h, n_seqs } },
{ pipeline, std::move(params), std::move(entries), { h, n_seqs } },
});
}
static std::optional<webgpu_encoded_op> ggml_webgpu_set_rows(webgpu_context & ctx,
@@ -3910,9 +3946,7 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
return ggml_webgpu_ssm_scan(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node->src[6],
node);
case GGML_OP_GATED_DELTA_NET:
if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <=
ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage &&
ggml_webgpu_can_fuse_gdn_cache(ctx->global_ctx, cgraph, node_idx, num_encoded_ops)) {
if (ggml_webgpu_can_fuse_gdn_cache(ctx->global_ctx, cgraph, node_idx, num_encoded_ops)) {
ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1];
return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
node, dst_fuse);
@@ -5459,9 +5493,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 &&
op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 &&
s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup &&
ggml_are_same_stride(src0, src1) &&
ggml_webgpu_gated_delta_net_n_storage_buffers(op, false) <=
ctx->webgpu_global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage;
ggml_are_same_stride(src0, src1);
}
break;
case GGML_OP_CLAMP:
@@ -14,40 +14,44 @@ var<storage, read_write> src_g: array<f32>;
var<storage, read_write> src_beta: array<f32>;
@group(0) @binding(5)
var<storage, read_write> src_state: array<f32>;
@group(0) @binding(6)
var<storage, read_write> dst: array<f32>;
#ifdef FUSED_CACHE
@group(0) @binding(7)
@group(0) @binding(6)
var<storage, read_write> dst_fuse: array<f32>;
#define DST_SNAP dst_fuse
#define NEXT_BINDING 8
#define NEXT_BINDING 7
#else
#define DST_SNAP dst
#define NEXT_BINDING 7
#define NEXT_BINDING 6
#endif
#ifdef REPLAY
// pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
// REPLAY runs the pending tokens of ggml_gated_delta_net_ext in this pass. REPLAY_SPLIT runs them in the separate pipeline.
#ifdef REPLAY_SPLIT
#define PARAMS_BINDING NEXT_BINDING
#else
@group(0) @binding(NEXT_BINDING)
var<storage, read_write> src_state: array<f32>;
#ifdef REPLAY
@group(0) @binding(NEXT_BINDING + 1)
var<storage, read_write> pend_k: array<f32>;
@group(0) @binding(NEXT_BINDING + 1)
@group(0) @binding(NEXT_BINDING + 2)
var<storage, read_write> pend_v: array<f32>;
@group(0) @binding(NEXT_BINDING + 2)
@group(0) @binding(NEXT_BINDING + 3)
var<storage, read_write> pend_gb: array<f32>;
@group(0) @binding(NEXT_BINDING + 3)
@group(0) @binding(NEXT_BINDING + 4)
var<storage, read_write> n_rep: array<i32>;
var<workgroup> wg_n_rep: u32;
#define PARAMS_BINDING (NEXT_BINDING + 4)
#define PARAMS_BINDING (NEXT_BINDING + 5)
#else
#define PARAMS_BINDING NEXT_BINDING
#define PARAMS_BINDING (NEXT_BINDING + 1)
#endif
#endif
struct Params {
@@ -125,7 +129,12 @@ fn main(
var state: array<f32, S_V>;
for (var i = 0u; i < S_V; i++) {
#ifdef REPLAY_SPLIT
// each thread reads back the row it alone wrote in the replay pass, and overwrites it at most once below
state[i] = DST_SNAP[snap_off + state_out_base + col * S_V + i];
#else
state[i] = src_state[state_in_base + col * S_V + i];
#endif
}
#ifdef REPLAY
@@ -256,7 +265,7 @@ fn main(
workgroupBarrier();
}
#ifdef REPLAY
#if defined(REPLAY) || defined(REPLAY_SPLIT)
// replay with keep: the state output is the state after the replay
let write_state = params.K == 1u && params.keep == 0u;
#else
@@ -0,0 +1,118 @@
@group(0) @binding(0)
var<storage, read_write> src_state: array<f32>;
@group(0) @binding(1)
var<storage, read_write> pend_k: array<f32>;
@group(0) @binding(2)
var<storage, read_write> pend_v: array<f32>;
@group(0) @binding(3)
var<storage, read_write> pend_gb: array<f32>;
@group(0) @binding(4)
var<storage, read_write> n_rep: array<i32>;
// dst of the gdn op, or the fused cache view
@group(0) @binding(5)
var<storage, read_write> dst_state: array<f32>;
struct Params {
h: u32,
neq1: u32,
state_off: u32,
n_pend: u32,
spk1: u32,
spk2: u32,
spk3: u32,
spv1: u32,
spv2: u32,
spv3: u32,
spg1: u32,
spg2: u32,
spg3: u32,
};
@group(0) @binding(6)
var<uniform> params: Params;
var<workgroup> sh_k: array<f32, S_V>;
var<workgroup> sh_g: array<f32, S_V>;
var<workgroup> wg_n_rep: u32;
@compute @workgroup_size(WG_SIZE)
fn main(
@builtin(workgroup_id) workgroup_id: vec3<u32>,
@builtin(local_invocation_id) local_id: vec3<u32>
) {
let head_id = workgroup_id.x;
let seq_id = workgroup_id.y;
let col = local_id.x;
let iq1 = head_id % params.neq1;
let state_base = (seq_id * params.h + head_id) * S_V * S_V;
var state: array<f32, S_V>;
for (var i = 0u; i < S_V; i++) {
state[i] = src_state[state_base + col * S_V + i];
}
if (col == 0u) {
wg_n_rep = u32(n_rep[seq_id]);
}
let n_r = workgroupUniformLoad(&wg_n_rep);
for (var t = 0u; t < n_r; t++) {
let k_off = seq_id * params.spk3 + t * params.spk2 + iq1 * params.spk1;
let v_off = seq_id * params.spv3 + t * params.spv2 + head_id * params.spv1;
let g_off = seq_id * params.spg3 + t * params.spg2 + head_id * params.spg1;
sh_k[col] = pend_k[k_off + col];
#ifdef KDA
sh_g[col] = exp(pend_gb[g_off + col]);
#endif
workgroupBarrier();
let v_val = pend_v[v_off + col];
let beta_val = pend_gb[g_off + params.n_pend * params.spg2];
var kv_col = 0.0;
var delta_col = 0.0;
#ifdef KDA
for (var i = 0u; i < S_V; i++) {
kv_col += (sh_g[i] * state[i]) * sh_k[i];
}
delta_col = (v_val - kv_col) * beta_val;
for (var i = 0u; i < S_V; i++) {
state[i] = sh_g[i] * state[i] + sh_k[i] * delta_col;
}
#else
let g_val = exp(pend_gb[g_off]);
for (var i = 0u; i < S_V; i++) {
kv_col += state[i] * sh_k[i];
}
delta_col = (v_val - g_val * kv_col) * beta_val;
for (var i = 0u; i < S_V; i++) {
state[i] = g_val * state[i] + sh_k[i] * delta_col;
}
#endif
workgroupBarrier();
}
for (var i = 0u; i < S_V; i++) {
dst_state[params.state_off + state_base + col * S_V + i] = state[i];
}
}
+1
View File
@@ -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"
+3
View File
@@ -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)
@@ -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 -%}
+6
View File
@@ -98,6 +98,8 @@ CODEPOINT_FLAG_MARK = 0x0010 # \p{M}
CODEPOINT_FLAG_PUNCTUATION = 0x0020 # \p{P}
CODEPOINT_FLAG_SYMBOL = 0x0040 # \p{S}
CODEPOINT_FLAG_CONTROL = 0x0080 # \p{C}
CODEPOINT_FLAG_LOWERCASE = 0x0200 # \p{Ll}
CODEPOINT_FLAG_UPPERCASE = 0x0400 # \p{Lu}
UNICODE_CATEGORY_TO_FLAG = {
"Cn": CODEPOINT_FLAG_UNDEFINED, # Undefined
@@ -146,6 +148,10 @@ for (cpt, cpt_lower, cpt_upper, categ, bidir) in unicode_data_iter():
# codepoint category flags
codepoint_flags[cpt] = UNICODE_CATEGORY_TO_FLAG[categ]
if categ == "Lu":
codepoint_flags[cpt] |= CODEPOINT_FLAG_UPPERCASE
elif categ == "Ll":
codepoint_flags[cpt] |= CODEPOINT_FLAG_LOWERCASE
# lowercase conversion
if cpt_lower:
+3 -2
View File
@@ -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" },
@@ -1083,7 +1084,7 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
{LLM_TENSOR_PLE_NORM_KEY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_PLE_NORM_QUERY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_PLE_NORM_CONV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_PLE_CONV1D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}},
{LLM_TENSOR_PLE_CONV1D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_COMPRESSOR_WKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_COMPRESSOR_WGATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_COMPRESSOR_APE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
@@ -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
+1
View File
@@ -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,
+8
View File
@@ -345,6 +345,7 @@ llama_context::llama_context(
cparams.op_offload = params.op_offload;
cparams.kv_unified = params.kv_unified;
cparams.kv_quantized = ggml_is_quantized(params.type_k) || ggml_is_quantized(params.type_v);
// the Hy4 flash pools gather their members from a single KV stream
if (model.arch == LLM_ARCH_HY_V4_FLASH && !cparams.kv_unified && cparams.n_seq_max > 1) {
@@ -2886,6 +2887,13 @@ uint32_t llama_context::graph_max_nodes() const {
res += 32u*model.hparams.n_layer_all;
}
// a quantized KV cache may rotate Q and K (K cache) and V and the attention output (V cache) of each layer,
// 3 nodes per rotation plus the rotation matrices, which the per-tensor estimate above does not cover for
// models with few tensors per layer (e.g. fused QKV)
if (cparams.kv_quantized) {
res += 16u*model.hparams.n_layer_all;
}
// every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling
for (const auto & [seq_id, sampler] : sampling.samplers) {
res += llama_sampler_backend_n_nodes(sampler) * cparams.n_outputs_max_per_seq;
+1
View File
@@ -51,6 +51,7 @@ struct llama_cparams {
bool no_perf;
bool op_offload;
bool kv_unified;
bool kv_quantized; // quantized K or V cache: the cache may rotate Q/K/V and the attention output
bool pipeline_parallel;
bool training; // set by llama_opt_init()
bool moe_random_routing; // benchmark only: random expert ids in the MoE GEMMs
+3
View File
@@ -529,6 +529,9 @@ const char * llama_grammar_parser::parse_sequence(
// use UINT64_MAX as the empty value because we aligned to the proper uint64_t type so -1 can't be used
// (though it's technically the same as -1 now)
auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
if (min_times > max_times) {
throw std::runtime_error("min_times cannot be greater than max_times");
}
bool no_max = max_times == UINT64_MAX;
if (last_sym_start == rule.size()) {
throw std::runtime_error(std::string("expecting preceding item to */+/?/{ at ") + pos);
+3
View File
@@ -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;
+24 -5
View File
@@ -1076,6 +1076,8 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch,
// - (disabled) mask causally, if the sequence is the same as the one we are inserting
// - mask SWA, using current max pos for that sequence in the cache
// always insert in the cell with minimum pos
// - the cell is shared by several sequences (e.g. after llama_memory_seq_cp in a unified cache):
// - mask SWA, the cell must be masked for all of its sequences
bool can_use = cells.is_empty(idx);
if (!can_use && cells.seq_count(idx) == 1) {
@@ -1095,6 +1097,20 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch,
can_use = true;
}
}
} else if (!can_use && n_swa > 0 && swa_type != LLAMA_SWA_TYPE_NONE) {
const llama_pos pos_cell = cells.pos_get(idx);
const auto & seq_set = cells.seq_get_all(idx);
// SWA mask
can_use = true;
for (uint32_t seq_id_cell = 0; seq_id_cell < LLAMA_MAX_SEQ; ++seq_id_cell) {
if (seq_set.test(seq_id_cell) &&
!llama_hparams::is_masked_swa(n_swa, swa_type, pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) {
can_use = false;
break;
}
}
}
if (can_use) {
@@ -1155,12 +1171,15 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch &
const auto idx = sinfo.idxs[s][ii];
if (!cells.is_empty(idx)) {
assert(cells.seq_count(idx) == 1);
// the cell can be shared by several sequences (see find_slot)
const auto & seq_set = cells.seq_get_all(idx);
const llama_pos pos = cells.pos_get(idx);
const llama_seq_id seq_id = cells.seq_get(idx);
const llama_pos pos = cells.pos_get(idx);
seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);
for (uint32_t seq_id = 0; seq_id < LLAMA_MAX_SEQ; ++seq_id) {
if (seq_set.test(seq_id)) {
seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);
}
}
cells.rm(idx);
}
+8 -4
View File
@@ -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);
+3
View File
@@ -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);
@@ -2249,6 +2250,7 @@ void llama_model_base::load_hparams_hadamard(llama_model_loader & ml) {
// only build_lora_mm/build_lora_mm_id apply the transform: refuse archs and tensor kinds that can skip them
switch (arch) {
case LLM_ARCH_LFM3:
case LLM_ARCH_LLAMA:
case LLM_ARCH_QWEN3:
case LLM_ARCH_QWEN3MOE:
@@ -2271,6 +2273,7 @@ void llama_model_base::load_hparams_hadamard(llama_model_loader & ml) {
"ffn_gate_exps", "ffn_up_exps", "ffn_down_exps", "ffn_gate_up_exps",
"ffn_gate_shexp", "ffn_up_shexp", "ffn_down_shexp",
"ssm_out",
"shortconv.in_proj", "shortconv.out_proj",
};
if (name == "output.weight") {
return true; // the output head is built through build_lora_mm in every arch
+19 -1
View File
@@ -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;
}
+10 -26
View File
@@ -294,7 +294,7 @@ void llama_model_qwen4exp::load_arch_tensors(llama_model_loader & ml) {
layer.ple_norm_key = create_tensor(tn(LLM_TENSOR_PLE_NORM_KEY, "weight", il), { n_embd, hc }, flags | TENSOR_ALLOW_RESHAPE);
layer.ple_norm_query = create_tensor(tn(LLM_TENSOR_PLE_NORM_QUERY, "weight", il), { n_embd, hc }, flags | TENSOR_ALLOW_RESHAPE);
layer.ple_norm_conv = create_tensor(tn(LLM_TENSOR_PLE_NORM_CONV, "weight", il), { n_embd, hc }, flags | TENSOR_ALLOW_RESHAPE);
layer.ple_conv1d = create_tensor(tn(LLM_TENSOR_PLE_CONV1D, "weight", il), { hparams.ple_conv_kernel, hc_dim }, flags);
layer.ple_conv1d = create_tensor(tn(LLM_TENSOR_PLE_CONV1D, "weight", il), { hparams.ple_conv_kernel, 1, hc_dim }, flags | TENSOR_ALLOW_RESHAPE);
}
layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", il), { n_embd, n_expert }, flags);
@@ -1479,34 +1479,18 @@ ggml_tensor * llama_model_qwen4exp::graph::build_ple(
ggml_reshape_3d(ctx0, normalized, hc_dim, n_seq_tokens, n_seqs),
hist, hc_dim, il);
ggml_tensor * conv_out = nullptr;
for (int64_t k = 0; k < kern; ++k) {
// tap k reads (kern-1-k)*dilation positions back
const int64_t start = hist - (kern - 1 - k) * dil;
ggml_tensor * w = model.layers[il].ple_conv1d;
ggml_tensor * shifted = ggml_cont(ctx0,
ggml_transpose(ctx0,
ggml_view_3d(ctx0, padded, n_seq_tokens, hc_dim, n_seqs,
padded->nb[1], padded->nb[2],
ggml_row_size(padded->type, start))));
// column k of the [kern, hc_dim] kernel is one weight per channel
ggml_tensor * wk = ggml_cont(ctx0,
ggml_view_2d(ctx0, model.layers[il].ple_conv1d, 1, hc_dim,
model.layers[il].ple_conv1d->nb[1],
k * model.layers[il].ple_conv1d->nb[0]));
// this kernel keeps the file type, so cast it before it multiplies an f32 activation
wk = ggml_reshape_1d(ctx0, wk, hc_dim);
if (wk->type != GGML_TYPE_F32) {
wk = ggml_cast(ctx0, wk, GGML_TYPE_F32);
}
ggml_tensor * term = ggml_mul(ctx0, shifted, wk);
conv_out = conv_out ? ggml_add(ctx0, conv_out, term) : term;
}
ggml_tensor * padded2 = ggml_reshape_3d(ctx0, padded, padded->ne[0], 1, hc_dim * n_seqs);
ggml_tensor * kshape = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, kern, 1);
ggml_tensor * im = ggml_im2col(ctx0, kshape, padded2, 1, 0, 0, 0, dil, 0, false, GGML_TYPE_F32);
ggml_tensor * x = ggml_reshape_4d(ctx0, im, kern, n_seq_tokens, hc_dim, n_seqs);
ggml_tensor * y = ggml_mul_mat(ctx0, w, x);
y = ggml_cont(ctx0, ggml_permute(ctx0, y, 2, 1, 0, 3));
ggml_tensor * conv_out = ggml_reshape_3d(ctx0, y, hc_dim, n_seq_tokens, n_seqs);
conv_out = ggml_silu(ctx0, conv_out);
conv_out = ggml_reshape_3d(ctx0, ggml_cont(ctx0, conv_out), n_embd, hc, n_tokens);
conv_out = ggml_reshape_3d(ctx0, conv_out, n_embd, hc, n_tokens);
cb(conv_out, "ple_conv_out", il);
return ggml_add(ctx0, hidden, ggml_add(ctx0, gated, conv_out));
+1336 -127
View File
File diff suppressed because it is too large Load Diff
+30 -25
View File
@@ -145,14 +145,6 @@ static std::vector<unicode_cpt_flags> unicode_cpt_flags_array() {
cpt_flags[cpt].is_whitespace = true;
}
for (auto p : unicode_map_lowercase) {
cpt_flags[p.second].is_lowercase = true;
}
for (auto p : unicode_map_uppercase) {
cpt_flags[p.second].is_uppercase = true;
}
for (auto &range : unicode_ranges_nfd) { // start, last, nfd
cpt_flags[range.nfd].is_nfd = true;
}
@@ -1653,31 +1645,41 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
return {};
}
// collapsed categories: LETTER alone means a letter that is not Lu or Ll
static constexpr int UCAT_LU = unicode_cpt_flags::LETTER | unicode_cpt_flags::UPPERCASE;
static constexpr int UCAT_LL = unicode_cpt_flags::LETTER | unicode_cpt_flags::LOWERCASE;
static constexpr int UCAT_LX = unicode_cpt_flags::LETTER;
// unicode categories
static const std::map<std::string, int> k_ucat_enum = {
{ "\\p{N}", unicode_cpt_flags::NUMBER },
{ "\\p{L}", unicode_cpt_flags::LETTER },
{ "\\p{P}", unicode_cpt_flags::PUNCTUATION },
{ "\\p{M}", unicode_cpt_flags::ACCENT_MARK },
{ "\\p{S}", unicode_cpt_flags::SYMBOL },
{ "\\p{Lu}", unicode_cpt_flags::LETTER }, // Uppercase letter
{ "\\p{Ll}", unicode_cpt_flags::LETTER }, // Lowercase letter
{ "\\p{Lt}", unicode_cpt_flags::LETTER }, // Titlecase letter
{ "\\p{Lm}", unicode_cpt_flags::LETTER }, // Modifier letter
{ "\\p{Lo}", unicode_cpt_flags::LETTER }, // Other letter
// Lt, Lm and Lo share one collapsed category, so \p{Lt} also matches Lm and Lo letters
static const std::map<std::string, std::vector<int>> k_ucat_enum = {
{ "\\p{N}", { unicode_cpt_flags::NUMBER } },
{ "\\p{L}", { UCAT_LU, UCAT_LL, UCAT_LX } },
{ "\\p{P}", { unicode_cpt_flags::PUNCTUATION } },
{ "\\p{M}", { unicode_cpt_flags::ACCENT_MARK } },
{ "\\p{S}", { unicode_cpt_flags::SYMBOL } },
{ "\\p{Lu}", { UCAT_LU } }, // Uppercase letter
{ "\\p{Ll}", { UCAT_LL } }, // Lowercase letter
{ "\\p{Lt}", { UCAT_LX } }, // Titlecase letter
{ "\\p{Lm}", { UCAT_LX } }, // Modifier letter
{ "\\p{Lo}", { UCAT_LX } }, // Other letter
};
static const std::map<int, int> k_ucat_cpt = {
{ unicode_cpt_flags::NUMBER, 0xD1 },
{ unicode_cpt_flags::LETTER, 0xD2 },
{ UCAT_LX, 0xD2 },
{ unicode_cpt_flags::PUNCTUATION, 0xD3 },
{ unicode_cpt_flags::ACCENT_MARK, 0xD4 },
{ unicode_cpt_flags::SYMBOL, 0xD5 },
{ UCAT_LU, 0xD6 },
{ UCAT_LL, 0xD7 },
};
static const std::map<int, std::string> k_ucat_map = {
{ unicode_cpt_flags::NUMBER, "\x30-\x39" }, // 0-9
{ unicode_cpt_flags::LETTER, "\x41-\x5A\x61-\x7A" }, // A-Za-z
{ UCAT_LX, "" }, // no sub-128 codepoints
{ UCAT_LU, "\x41-\x5A" }, // A-Z
{ UCAT_LL, "\x61-\x7A" }, // a-z
{ unicode_cpt_flags::PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
{ unicode_cpt_flags::ACCENT_MARK, "" }, // no sub-128 codepoints
{ unicode_cpt_flags::SYMBOL, "\\\x24\\\x2B\x3C-\x3E\x5E\x60\\\x7C\\\x7E" }, // $+<=>^`|~
@@ -1712,13 +1714,14 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
}
const auto flags = unicode_cpt_flags_from_cpt(cpts[i]);
const int ucat = flags.as_uint() & (unicode_cpt_flags::MASK_CATEGORIES | unicode_cpt_flags::UPPERCASE | unicode_cpt_flags::LOWERCASE);
if (flags.is_whitespace) {
//NOTE: C++ std::regex \s does not mach 0x85, Rust and Python regex does.
//text_collapsed[i] = (char) 0x85; // <Next Line> as whitespace fallback
text_collapsed[i] = (char) 0x0B; // <vertical tab> as whitespace fallback
} else if (k_ucat_cpt.find(flags.category_flag()) != k_ucat_cpt.end()) {
text_collapsed[i] = k_ucat_cpt.at(flags.category_flag());
} else if (k_ucat_cpt.find(ucat) != k_ucat_cpt.end()) {
text_collapsed[i] = k_ucat_cpt.at(ucat);
} else {
text_collapsed[i] = (char) 0xD0; // fallback
}
@@ -1787,8 +1790,10 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
if (!inside) {
regex_expr_collapsed += '[';
}
regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
for (const int ucat : k_ucat_enum.at(pat)) {
regex_expr_collapsed += k_ucat_cpt.at(ucat);
regex_expr_collapsed += k_ucat_map.at(ucat);
}
if (!inside) {
regex_expr_collapsed += ']';
}
+4 -4
View File
@@ -17,8 +17,8 @@ struct unicode_cpt_flags {
CONTROL = 0x0080, // regex: \p{C}
MASK_CATEGORIES = 0x00FF,
WHITESPACE = 0x0100,
LOWERCASE = 0x0200,
UPPERCASE = 0x0400,
LOWERCASE = 0x0200, // regex: \p{Ll}
UPPERCASE = 0x0400, // regex: \p{Lu}
NFD = 0x0800,
};
@@ -33,8 +33,8 @@ struct unicode_cpt_flags {
uint16_t is_control : 1; // regex: \p{C}
// helper flags
uint16_t is_whitespace : 1; // regex: \s
uint16_t is_lowercase : 1;
uint16_t is_uppercase : 1;
uint16_t is_lowercase : 1; // regex: \p{Ll}
uint16_t is_uppercase : 1; // regex: \p{Lu}
uint16_t is_nfd : 1;
// decode from uint16
+16
View File
@@ -14804,6 +14804,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_roll(0, 0, 0, 0, true));
test_cases.emplace_back(new test_roll(256, 0, 0, 0, false, {257, 1, 1, 1}));
test_cases.emplace_back(new test_roll(-16, 6, -2, 1, false, {17, 7, 3, 2}));
test_cases.emplace_back(new test_roll(0, 32768, 0, 0, false, {2, 32770, 1, 1}));
test_cases.emplace_back(new test_roll(0, 0, -32769, 0, false, {1, 1, 32770, 1}));
test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {42, 512, 1, 1}));
test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {380, 512, 1, 1}));
test_cases.emplace_back(new test_arange());
@@ -15074,6 +15076,13 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 8, 2, 4096, 1280, nb, n_slices));
}
}
// decode: one token per slice, non-f16 K/V take the vec kernel
for (ggml_type type_KV : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
for (int64_t n_slices : {1, 3, 8}) {
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 2, 12, 8192, 2304, 1, n_slices, type_KV));
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 4, 5000, 512, 2, n_slices, type_KV));
}
}
// flash attention with an indexed bias (Inkling 2 relative-position bias)
for (bool kv_rows : {false, true}) {
@@ -15223,6 +15232,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_flash_attn_ext(128, 128, 4, {4, 1}, 4096, 5, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_BF16, GGML_TYPE_BF16, {0, 2, 1, 3}, true, false, 0, 0, 1, true));
test_cases.emplace_back(new test_flash_attn_ext(128, 128, 4, { 3, 1}, 512, 32, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
// GQA with more query tokens than tile rows still uses split_k; one KV head so devices with few cores split too
test_cases.emplace_back(new test_flash_attn_ext(128, 128, 1, {4, 1}, 1024, 5, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
// dense-allocated (non-view) quant K/V at batch >= 64, in cache and native layouts
test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 512, 75, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q8_0, {0, 2, 1, 3}, false));
test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {4, 1}, 512, 75, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q8_0, {0, 2, 1, 3}, false));
@@ -16360,6 +16372,10 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1));
// GDN replay of pending tokens (27B shape): decode, MTP verify (keep), prefill
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 1, 1, 3, false, 4, false));
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 4, 1, 3, false, 4, true));
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 512, 1, 3, false, 4, false));
// lightning_indexer
for (int kv : { 256, 4096, 65536 }) {
+1
View File
@@ -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
+269
View File
@@ -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>
{
@@ -7817,6 +7924,13 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
.expect(message_assist_call_thoughts)
.run();
// Tool with an array param that has no "items" (#30781)
tst.test(" to=functions.todo_list<|channel|>analysis<|message|>{\"todos\": [\"buy milk\"]}")
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
.tools({ todo_list })
.expect(simple_assist_msg("", "", "todo_list", "{\"todos\": [\"buy milk\"]}"))
.run();
// Tool call with recipient in channel header: "<|channel|>analysis to=functions.NAME<|message|>JSON"
tst.test("<|channel|>analysis to=functions.special_function<|message|>{\"arg1\": 1}")
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
@@ -8475,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");
+13
View File
@@ -389,6 +389,19 @@ static void test_conditionals(testing & t) {
{{"y", 1.0}},
"yes"
);
// a missing 'items' key falls back to the dict's items() function, which is truthy
test_template(t, "function is truthy",
"{{ 'yes' if p['items'] else 'no' }}",
{{"p", {{"type", "array"}}}},
"yes"
);
test_template(t, "subscript on a function is undefined",
"{% if p['items'] %}{{ p['items']['type'] is defined }}{% endif %}",
{{"p", {{"type", "array"}}}},
"False"
);
}
static void test_loops(testing & t) {
+69
View File
@@ -1,6 +1,7 @@
#include "llama-kv-cache.h"
#include "llama-model.h"
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>
@@ -175,6 +176,74 @@ int main() {
GGML_ASSERT(kv.seq_pos_max(0) == 4);
}
// SWA cells shared by several sequences (e.g. after seq_cp in a unified cache) must be reused once they
// are masked for all of their sequences, otherwise they stay occupied forever
// ref: https://github.com/ggml-org/llama.cpp/issues/32258
{
std::unique_ptr<llama_model> model(llama_model_create(LLM_ARCH_LLAMA, llama_model_default_params()));
init_model(*model, 1);
const uint32_t kv_size = 8;
const uint32_t n_swa = 4;
llama_kv_cache kv(*model, false, model->hparams, GGML_TYPE_F16, GGML_TYPE_F16,
false, false, true, kv_size, 2, n_swa, LLAMA_SWA_TYPE_STANDARD, nullptr, nullptr, nullptr, nullptr);
GGML_ASSERT(kv.get_size() == kv_size);
auto add = [&](llama_seq_id seq_id, llama_pos pos) {
llama_token token = 0;
int32_t n_seq_id = 1;
llama_seq_id seq_ids[1] = { seq_id };
llama_seq_id * seq_id_ptr = seq_ids;
int32_t seq_idx[LLAMA_MAX_SEQ];
int8_t output = 1;
std::fill(seq_idx, seq_idx + LLAMA_MAX_SEQ, -1);
seq_idx[seq_id] = 0;
llama_ubatch ubatch = {};
ubatch.b_equal_seqs = 1;
ubatch.n_tokens = 1;
ubatch.n_seq_tokens = 1;
ubatch.n_seqs = 1;
ubatch.n_seqs_unq = 1;
ubatch.n_pos = 1;
ubatch.token = &token;
ubatch.pos = &pos;
ubatch.n_seq_id = &n_seq_id;
ubatch.seq_id = &seq_id_ptr;
ubatch.seq_id_unq = seq_ids;
ubatch.seq_idx = seq_idx;
ubatch.output = &output;
const auto sinfo = kv.find_slot(ubatch, false);
if (sinfo.empty()) {
return false;
}
kv.apply_ubatch(sinfo, ubatch);
return true;
};
// shared prefix [0, 1] of seq 0 and seq 1
GGML_ASSERT(add(0, 0));
GGML_ASSERT(add(0, 1));
kv.seq_cp(0, 1, -1, -1);
// fill the rest of the cache with tokens of each sequence that are still inside the window
for (llama_pos pos = 2; pos < 5; ++pos) {
GGML_ASSERT(add(0, pos));
GGML_ASSERT(add(1, pos));
}
// the cache is full and only the shared cells are masked for both sequences
for (llama_pos pos = 5; pos < 16; ++pos) {
GGML_ASSERT(add(0, pos));
GGML_ASSERT(add(1, pos));
GGML_ASSERT(kv.seq_pos_max(0) == pos && kv.seq_pos_max(1) == pos);
GGML_ASSERT(kv.seq_pos_min(0) == kv.seq_pos_min(1));
GGML_ASSERT(kv.seq_pos_max(0) - kv.seq_pos_min(0) + 1 >= (llama_pos) n_swa);
}
}
llama_backend_free();
return 0;
}
+32
View File
@@ -3,6 +3,7 @@
#include "../tools/server/server-chat.h"
#include "../tools/server/server-common.h"
#include "../tools/server/server-decision.h"
#include "../tools/server/server-queue.h"
#include "../tools/server/server-schema.h"
#include "../tools/server/server-slot-sched.h"
@@ -540,6 +541,36 @@ static void test_server_pipe(testing & t) {
});
}
//
// server_response
//
static void test_server_response_terminate(testing & t) {
auto is_unavailable = [](const server_task_result_ptr & res) {
const auto * err = dynamic_cast<const server_task_result_error *>(res.get());
return err != nullptr && err->err_type == ERROR_TYPE_UNAVAILABLE;
};
auto post_completion = [](server_response_reader & rd) {
server_task task(SERVER_TASK_TYPE_COMPLETION);
task.id = rd.get_new_id();
rd.post_task(std::move(task));
};
auto stop_now = []() { return true; };
server_queue queue_tasks;
server_response queue_results;
// task loop is not running, so no result will ever be sent
server_response_reader rd(queue_tasks, queue_results, 1);
post_completion(rd);
queue_results.terminate();
t.assert_true("waiting reader gets an error", is_unavailable(rd.next(stop_now)));
server_response_reader rd_late(queue_tasks, queue_results, 1);
post_completion(rd_late);
t.assert_true("reader added later gets an error", is_unavailable(rd_late.next(stop_now)));
}
//
// server_decision_escape_special_tokens
//
@@ -956,6 +987,7 @@ int main(int argc, char ** argv) {
t.test("lora_helpers", test_lora_helpers);
t.test("server_prompt_reuse", test_server_prompt_reuse);
t.test("server_pipe", test_server_pipe);
t.test("server_response_terminate", test_server_response_terminate);
t.test("decision_escape", test_decision_escape);
t.test("rerank_template", test_rerank_template);
t.test("decision_class_scores", test_decision_class_scores);
+18
View File
@@ -82,6 +82,24 @@ int main() {
success = false;
}
// \p{Lu} and \p{Ll} must split on case, expected output from HF tokenizers
const std::vector<std::string> regex_exprs_case = {
"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
};
const std::vector<std::string> expected_case = {
"get", "User", "By", "ID", " HTTPServer", " \xc3\x80" "bc", "D\xc3\x89" "f", " stra\xc3\x9f" "e", "\xc3\x96" "l",
};
const auto actual_case = unicode_regex_split("getUserByID HTTPServer \xc3\x80" "bcD\xc3\x89" "f stra\xc3\x9f" "e\xc3\x96" "l", regex_exprs_case, false);
if (actual_case != expected_case) {
fprintf(stderr, "unexpected case split:");
for (const auto & piece : actual_case) {
fprintf(stderr, " [%s]", piece.c_str());
}
fprintf(stderr, "\n");
success = false;
}
const std::vector<std::string> regex_exprs_bytes = { "\\p{L}+", "\\p{N}+", "\\s+" };
const std::string byte_encode_text = "\xc4\x80\xc4\xb1\xe0\xa4\x95\xf0\x9f\x98\x80";
const auto actual_byte_encode = unicode_regex_split(byte_encode_text, regex_exprs_bytes, true);
+1
View File
@@ -5178,6 +5178,7 @@ void server_context::start_loop() {
void server_context::terminate() {
impl->queue_tasks.terminate();
impl->queue_results.terminate();
}
llama_context * server_context::get_llama_context() const {
+1 -1
View File
@@ -75,7 +75,7 @@ struct server_context {
// this function will block main thread until termination
void start_loop();
// terminate main loop (will unblock start_loop)
// terminate main loop (will unblock start_loop), readers waiting for a result get an error
void terminate();
// get the underlaying llama_context, can return nullptr if sleeping
+20 -8
View File
@@ -429,15 +429,20 @@ void server_response::remove_waiting_task_ids(const std::unordered_set<int> & id
}
}
static server_task_result_ptr make_result_terminated(const std::unordered_set<int> & id_tasks) {
GGML_ASSERT(!id_tasks.empty());
auto res = std::make_unique<server_task_result_error>();
res->id = *id_tasks.begin();
res->err_type = ERROR_TYPE_UNAVAILABLE;
res->err_msg = "server is shutting down";
return res;
}
server_task_result_ptr server_response::recv(const std::unordered_set<int> & id_tasks) {
while (true) {
std::unique_lock<std::mutex> lock(mutex_results);
condition_results.wait(lock, [&]{
if (!running) {
RES_DBG("%s : queue result stop\n", "recv");
std::terminate(); // we cannot return here since the caller is HTTP code
}
return !queue_results.empty();
return !running || !queue_results.empty();
});
for (size_t i = 0; i < queue_results.size(); i++) {
@@ -447,6 +452,11 @@ server_task_result_ptr server_response::recv(const std::unordered_set<int> & id_
return res;
}
}
if (!running) {
RES_DBG("%s", "queue result stop\n");
return make_result_terminated(id_tasks);
}
}
// should never reach here
@@ -465,11 +475,12 @@ server_task_result_ptr server_response::recv_with_timeout(const std::unordered_s
}
}
std::cv_status cr_res = condition_results.wait_until(lock, deadline);
if (!running) {
RES_DBG("%s : queue result stop\n", __func__);
std::terminate(); // we cannot return here since the caller is HTTP code
RES_DBG("%s", "queue result stop\n");
return make_result_terminated(id_tasks);
}
std::cv_status cr_res = condition_results.wait_until(lock, deadline);
if (cr_res == std::cv_status::timeout) {
return nullptr;
}
@@ -510,6 +521,7 @@ void server_response::broadcast(server_task_result_ptr && result) {
}
void server_response::terminate() {
std::unique_lock<std::mutex> lock(mutex_results);
running = false;
condition_results.notify_all();
}
+2 -1
View File
@@ -182,6 +182,7 @@ public:
void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks);
// This function blocks the thread until there is a response for one of the id_tasks
// after terminate(), return the pending results first, then an ERROR_TYPE_UNAVAILABLE error
server_task_result_ptr recv(const std::unordered_set<int> & id_tasks);
// same as recv(), but have timeout in seconds
@@ -198,7 +199,7 @@ public:
// (used by router mode)
void broadcast(server_task_result_ptr && result);
// terminate the waiting loop
// wake up all readers, used when no more results will be sent
void terminate();
};
+2
View File
@@ -190,9 +190,11 @@ public:
const std::function<bool()> & should_stop = nullptr) const = 0;
};
#if defined(LLAMA_SUBPROCESS)
// time the output gets to close once the job is killed, and between two checks of exit, deadline and stop
static constexpr int SERVER_TOOL_SUBPROCESS_DRAIN_MS = 2000;
static constexpr int SERVER_TOOL_SUBPROCESS_POLL_MS = 100;
#endif
// output of a job, capped at max_output, handed to on_chunk as it arrives until on_chunk returns false
struct subprocess_output {
+19
View File
@@ -171,3 +171,22 @@ def test_server_ctrl_break():
server.process.send_signal(signal.CTRL_BREAK_EVENT)
# exit code 0 means a clean shutdown, the default handler would end it with STATUS_CONTROL_C_EXIT
assert server.process.wait(timeout=60) == 0
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal")
def test_server_sigterm_during_request():
global server
server.n_slots = 1
server.n_ctx = 131072
server.n_predict = -1
server.start()
stream = server.make_stream_request("POST", "/completion", data={
"prompt": "Once upon a time",
"ignore_eos": True,
"stream": True,
})
next(stream)
server.process.send_signal(signal.SIGTERM)
# the client keeps the connection open, so the HTTP thread must not wait for a result forever
assert server.process.wait(timeout=10) == 0
stream.close()