Compare commits

..
Author SHA1 Message Date
Pascal e6fa277a8b model: cut the kernel count of the Olala graph
The rotary update uses ggml_set instead of concats, the remaining
concats are 3D, a single token per sequence takes a direct state
step, and the chunk states come from one decay product over the
chunks instead of a sequential loop. The CUDA concat launches one
kernel per dim 3 slice, which counted heads times sequences here.

Q8_0 on an RTX PRO 6000: tg128 70 -> 122 t/s, pp512 4270 -> 5000.
2026-12-01 09:35:59 +01:00
Pascal fcf449183e model: keep the Olala projections with huge inputs in BF16
The inputs of ssm_out, ffn_down_exps and ffn_latent_up overflow the
F16 scales of the Q8 activation blocks, and F16 itself on CUDA: any
quantized type or F16 for these weights decodes NaN after a few
tokens. llama-quantize leaves them unquantized and the converter
writes them in BF16, F32 for an F32 output.
2026-12-01 09:35:59 +01:00
Pascal b99932b928 model: add Olala (Mamba-3 MIMO and differential TPA hybrid)
Olala v1.0 mini (OVHaiLLM) stacks Mamba-3 MIMO layers and
differential tensor product attention layers, a latent MoE with a
shared expert, and geodesic residual updates on the unit sphere.

The graph uses existing ggml ops only. The Mamba-3 recurrence runs
as a chunked scan: the trapezoid rule folds into a rank 2R state
update, the data-dependent rotary angles are accumulated with cumsum
and kept wrapped in the recurrent state. The attention layers keep
the raw K/V of the previous token in the recurrent row for the token
shift, next to their KV cache.

New GGUF keys: ssm.mimo_rank and attention.tpa_rank.
2026-12-01 09:35:59 +01:00
135 changed files with 2849 additions and 5044 deletions
-7
View File
@@ -1377,13 +1377,6 @@ 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 &&
-2
View File
@@ -1170,7 +1170,6 @@ static const std::map<common_decision_type, std::string> COMMON_DECISION_TYPE_NA
{ COMMON_DECISION_TYPE_MINICPM_OCR_JEV, "openbmb-minicpm-ocr-jev" },
{ COMMON_DECISION_TYPE_LFM3_D1, "lfm3-d1" },
{ COMMON_DECISION_TYPE_LFM3_D1_OMNI, "lfm3-d1-omni" },
{ COMMON_DECISION_TYPE_CLEF_OMNI, "cloudflare-clef-omni" },
// for future models, ALWAYS add org name prefix to avoid name collisions, e.g. "orgname-modelname"
};
@@ -1299,7 +1298,6 @@ common_init_result::common_init_result(common_params & params, bool model_only)
const auto decision_type = common_get_decision_type(model);
// minicpm-ocr-jev reads its class scores from the pooled output, the pooling type is the one of the GGUF
if (decision_type == COMMON_DECISION_TYPE_LAYA || decision_type == COMMON_DECISION_TYPE_KEV || decision_type == COMMON_DECISION_TYPE_CLEF ||
decision_type == COMMON_DECISION_TYPE_CLEF_OMNI ||
decision_type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || decision_type == COMMON_DECISION_TYPE_VLLM_DECISION2 ||
decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV) {
const auto pooling_type = decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV ? LLAMA_POOLING_TYPE_UNSPECIFIED : LLAMA_POOLING_TYPE_NONE;
-1
View File
@@ -1002,7 +1002,6 @@ enum common_decision_type {
COMMON_DECISION_TYPE_MINICPM_OCR_JEV, // one score per class, the pooled embeddings output of the last token
COMMON_DECISION_TYPE_LFM3_D1, // same as lfm2-d1, non-causal, label codes A..Z then AA, AB..
COMMON_DECISION_TYPE_LFM3_D1_OMNI, // same as lfm3-d1
COMMON_DECISION_TYPE_CLEF_OMNI, // same as clef, with audio input and no video input
COMMON_DECISION_TYPE_UNKNOWN, // a decision model of a type that is not supported
};
+1 -17
View File
@@ -556,25 +556,10 @@ value for_statement::execute_impl(context & ctx) const {
iterable_val = mk_val<value_array>();
}
if (!is_val<value_array>(iterable_val) && !is_val<value_object>(iterable_val) && !is_val<value_string>(iterable_val)) {
if (!is_val<value_array>(iterable_val) && !is_val<value_object>(iterable_val)) {
throw std::runtime_error("Expected iterable or object type in for loop: got " + iterable_val->type());
}
if (is_val<value_string>(iterable_val)) {
// FIXME: byte-based iteration splits UTF-8 codepoints in multibyte strings
// iterable_val is rebound below, so hold an explicit reference to the source
const value str_owner = iterable_val;
const auto * str_val = cast_val<value_string>(str_owner);
std::vector<value> chars;
chars.reserve(str_val->val_str.length());
for (size_t i = 0; i < str_val->val_str.length(); ++i) {
if (auto byte = str_val->val_str.byte_at(i)) {
chars.push_back(mk_val<value_string>(std::string(1, *byte)));
}
}
iterable_val = mk_val<value_array>(std::move(chars));
}
std::vector<value> items;
if (is_val<value_object>(iterable_val)) {
JJ_DEBUG("%s", "For loop over object keys");
@@ -985,7 +970,6 @@ value member_expression::execute_impl(context & ctx) const {
val = arr->as_array().at(static_cast<size_t>(index));
}
} else { // value_string
// FIXME: byte-based indexing splits UTF-8 codepoints in multibyte strings
const auto * str = cast_val<value_string>(object);
const auto len = str->val_str.length();
if (index < 0) {
+33 -84
View File
@@ -1,6 +1,5 @@
#include "jinja/string.h"
#include "jinja/value.h"
#include "unicode.h"
#include <algorithm>
#include <functional>
@@ -206,103 +205,53 @@ string string::titlecase() {
return res;
});
}
// mirrors Python str.isspace() (CPython Py_UNICODE_ISSPACE)
static bool is_unicode_whitespace(uint32_t cp) {
return (cp >= 0x0009 && cp <= 0x000D) ||
(cp >= 0x001C && cp <= 0x0020) ||
cp == 0x0085 ||
cp == 0x00A0 ||
cp == 0x1680 ||
(cp >= 0x2000 && cp <= 0x200A) ||
cp == 0x2028 ||
cp == 0x2029 ||
cp == 0x202F ||
cp == 0x205F ||
cp == 0x3000;
}
static std::vector<uint32_t> decode_utf8_cpts(std::string_view s) {
std::vector<uint32_t> cpts;
size_t pos = 0;
while (pos < s.size()) {
auto parsed = common_parse_utf8_codepoint(s, pos);
if (parsed.status == utf8_parse_result::SUCCESS) {
cpts.push_back(parsed.codepoint);
pos += parsed.bytes_consumed;
} else {
// skip invalid UTF-8 bytes so they never match non-strippable raw bytes in the input
pos += 1;
}
}
return cpts;
}
string string::strip(bool left, bool right, std::optional<const std::string_view> chars) {
static auto strip_part = [](const std::string & s, bool left, bool right, std::optional<const std::string_view> chars) -> std::string {
size_t start = 0;
size_t end = s.length();
auto match_char = [&chars](unsigned char c) -> bool {
return chars ? (*chars).find(c) != std::string::npos : isspace(c);
};
if (left) {
while (start < end && match_char(static_cast<unsigned char>(s[start]))) {
++start;
}
}
if (right) {
while (end > start && match_char(static_cast<unsigned char>(s[end - 1]))) {
--end;
}
}
return s.substr(start, end - start);
};
if (parts.empty()) {
return *this;
}
std::vector<uint32_t> char_cpts;
if (chars) {
char_cpts = decode_utf8_cpts(*chars);
}
auto match_cp = [&](uint32_t cp) -> bool {
if (chars) {
return std::find(char_cpts.begin(), char_cpts.end(), cp) != char_cpts.end();
}
return is_unicode_whitespace(cp);
};
const std::string full = str();
size_t start = 0;
size_t end = full.size();
if (left) {
while (start < end) {
auto parsed = common_parse_utf8_codepoint(full, start);
if (parsed.status != utf8_parse_result::SUCCESS || !match_cp(parsed.codepoint)) {
for (size_t i = 0; i < parts.size(); ++i) {
parts[i].val = strip_part(parts[i].val, true, false, chars);
if (parts[i].val.empty()) {
// remove empty part
parts.erase(parts.begin() + i);
--i;
continue;
} else {
break;
}
start += parsed.bytes_consumed;
}
}
if (right) {
size_t new_end = start;
size_t pos = start;
while (pos < end) {
auto parsed = common_parse_utf8_codepoint(full, pos);
if (parsed.status != utf8_parse_result::SUCCESS) {
pos += 1;
new_end = pos;
for (size_t i = parts.size(); i-- > 0;) {
parts[i].val = strip_part(parts[i].val, false, true, chars);
if (parts[i].val.empty()) {
// remove empty part
parts.erase(parts.begin() + i);
continue;
} else {
pos += parsed.bytes_consumed;
if (!match_cp(parsed.codepoint)) {
new_end = pos;
}
break;
}
}
end = new_end;
}
std::vector<string_part> new_parts;
size_t offset = 0;
for (const auto & part : parts) {
const size_t part_start = offset;
const size_t part_end = offset + part.val.size();
offset = part_end;
const size_t keep_start = std::max(part_start, start);
const size_t keep_end = std::min(part_end, end);
if (keep_start < keep_end) {
new_parts.push_back({
part.is_input,
part.val.substr(keep_start - part_start, keep_end - keep_start)
});
}
}
parts = std::move(new_parts);
return *this;
}
+26 -28
View File
@@ -739,24 +739,6 @@ static bool string_endswith(const std::string & str, const std::string & suffix)
throw not_implemented_exception("String join builtin not implemented");
}
static value string_strip_impl(const func_args & args, bool left, bool right) {
args.ensure_kwargs({"chars"});
args.ensure_count(1, 2);
const std::string & name = args.func_name;
value val_input = args.get_pos(0);
if (!is_val<value_string>(val_input)) {
throw raised_exception(name + "() first argument must be a string");
}
value val_chars = args.get_kwarg_or_pos("chars", 1);
if (val_chars->is_undefined() || is_val<value_none>(val_chars)) {
return mk_val<value_string>(val_input->as_string().strip(left, right));
}
if (!is_val<value_string>(val_chars)) {
throw raised_exception(name + "() argument must be None or str");
}
return mk_val<value_string>(val_input->as_string().strip(left, right, val_chars->as_string().str()));
}
const func_builtins & value_string_t::get_builtins() const {
static const func_builtins builtins = {
{"default", default_value},
@@ -775,13 +757,36 @@ const func_builtins & value_string_t::get_builtins() const {
return mk_val<value_string>(str);
}},
{"strip", [](const func_args & args) -> value {
return string_strip_impl(args, true, true);
args.ensure_kwargs({"chars"});
args.ensure_count(1, 2);
value val_input = args.get_pos(0);
if (!is_val<value_string>(val_input)) {
throw raised_exception("strip() first argument must be a string");
}
value val_chars = args.get_kwarg_or_pos("chars", 1);
if (val_chars->is_undefined()) {
return mk_val<value_string>(args.get_pos(0)->as_string().strip(true, true));
} else {
return mk_val<value_string>(args.get_pos(0)->as_string().strip(true, true, val_chars->as_string().str()));
}
}},
{"rstrip", [](const func_args & args) -> value {
return string_strip_impl(args, false, true);
args.ensure_vals<value_string>();
value val_chars = args.get_kwarg_or_pos("chars", 1);
if (val_chars->is_undefined()) {
return mk_val<value_string>(args.get_pos(0)->as_string().strip(false, true));
} else {
return mk_val<value_string>(args.get_pos(0)->as_string().strip(false, true, val_chars->as_string().str()));
}
}},
{"lstrip", [](const func_args & args) -> value {
return string_strip_impl(args, true, false);
args.ensure_vals<value_string>();
value val_chars = args.get_kwarg_or_pos("chars", 1);
if (val_chars->is_undefined()) {
return mk_val<value_string>(args.get_pos(0)->as_string().strip(true, false));
} else {
return mk_val<value_string>(args.get_pos(0)->as_string().strip(true, false, val_chars->as_string().str()));
}
}},
{"title", [](const func_args & args) -> value {
args.ensure_kwargs();
@@ -1011,7 +1016,6 @@ const func_builtins & value_string_t::get_builtins() const {
throw raised_exception("slice step cannot be zero");
}
auto input = args.get_pos(0);
// FIXME: byte-based slicing splits UTF-8 codepoints in multibyte strings
auto sliced = slice(input->as_string().str(), start, stop, step);
auto res = mk_val<value_string>(sliced);
res->val_str.mark_input_based_on(input->as_string());
@@ -1567,12 +1571,6 @@ 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,9 +770,7 @@ 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,9 +16,6 @@
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
@@ -1,171 +0,0 @@
#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,8 +43,6 @@ 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,7 +3,6 @@
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
+2 -5
View File
@@ -22,9 +22,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"LagunaForCausalLM": "laguna",
"RicursiveForCausalLM": "ricursive",
"FlintForCausalLM": "flint",
"ApertusForCausalLM": "apertus",
"Apertus1p5ForConditionalGeneration": "apertus",
"Apertus1p5TextForCausalLM": "apertus",
"ApertusForCausalLM": "llama",
"ArceeForCausalLM": "llama",
"ArcticForCausalLM": "arctic",
"AudioFlamingo3ForConditionalGeneration": "qwen",
@@ -50,7 +48,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
"ChatGLMModel": "chatglm",
"ChatterboxModel": "chatterbox",
"ClefModel": "clef",
"ClefOmniModel": "clef",
"CloverMoeModelLM": "clover",
"CodeShellForCausalLM": "codeshell",
"CogVLMForCausalLM": "cogvlm",
@@ -252,6 +249,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"NeoBERTLMHead": "bert",
"NomicBertModel": "bert",
"OLMoForCausalLM": "olmo",
"OlalaForCausalLM": "olala",
"Olmo2ForCausalLM": "olmo",
"Olmo3ForCausalLM": "olmo",
"OlmoForCausalLM": "olmo",
@@ -362,7 +360,6 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
"AudioFlamingo3ForConditionalGeneration": "ultravox",
"ChatterboxModel": "chatterbox",
"ClefModel": "clef",
"ClefOmniModel": "clef",
"CogVLMForCausalLM": "cogvlm",
"Cohere2VisionForConditionalGeneration": "command_r",
"PplxDeciderModel": "pplx_decider",
-74
View File
@@ -1,74 +0,0 @@
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)
+13 -53
View File
@@ -4,7 +4,7 @@ import json
import math
from pathlib import Path
from typing import Any, Callable, Iterable, Iterator, TYPE_CHECKING
from typing import Any, Iterable, Iterator, TYPE_CHECKING
import torch
@@ -13,7 +13,7 @@ if TYPE_CHECKING:
from .base import ModelBase, gguf, logger
from .qwen import Qwen3_5TextModel
from .qwen3vl import Qwen3OmniMmprojModel, Qwen3OmniMoeTextModel, Qwen3VLVisionModel
from .qwen3vl import Qwen3VLVisionModel
def _is_clef_checkpoint(dir_model: Path) -> bool:
@@ -24,16 +24,16 @@ def _is_clef_checkpoint(dir_model: Path) -> bool:
def _load_clef_hparams(dir_model: Path) -> dict[str, Any]:
logger.info("gguf: detected Clef checkpoint")
hparams = ModelBase.load_hparams(dir_model, False, guess=False)
# clef-omni has the same head on the Qwen3-Omni thinker
is_omni = "thinker_config" in hparams
hparams["architectures"] = ["ClefOmniModel" if is_omni else "ClefModel"]
hparams["architectures"] = ["ClefModel"]
with open(dir_model / "joint_head_config.json", encoding="utf-8") as f:
hparams["decision"] = json.load(f)
return hparams
class _ClefHeadMixin:
# the joint schema head, on top of the text model of the class that uses this mixin
@ModelBase.register("ClefModel")
class ClefModel(Qwen3_5TextModel):
model_arch = gguf.MODEL_ARCH.CLEF
no_mtp = True # the checkpoint has no MTP head
# prompt follows joint_schema_model.py of the model repo
_SYSTEM_PROMPT = (
@@ -42,17 +42,6 @@ class _ClefHeadMixin:
)
# torch.nn.LayerNorm default, used by the head
_HEAD_NORM_EPS = 1e-5
# clef-omni puts a newline after each image, clef after all of them
_NEWLINE_PER_IMAGE = False
_DECISION_TYPE = gguf.DecisionType.CLEF
model_arch: gguf.MODEL_ARCH
hparams: dict[str, Any]
block_count: int
gguf_writer: gguf.GGUFWriter
dir_model: Path
format_tensor_name: Callable[..., str]
map_tensor_name: Callable[..., str]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -63,7 +52,7 @@ class _ClefHeadMixin:
self._scales: dict[str, float] = {}
def set_vocab(self):
super().set_vocab() # ty: ignore[missing-attribute]
super().set_vocab()
self.gguf_writer.add_chat_template([{"name": "systemone", "template": self._systemone_template()}])
@classmethod
@@ -86,13 +75,9 @@ class _ClefHeadMixin:
"{% endif %}"
"{{ ({'option_id': o.key} if d is none else {'description': d, 'option_id': o.key}) | tojson(separators=[',', ':']) }}"
)
if cls._NEWLINE_PER_IMAGE:
images = "{% for image in images %}{{ image }}" + text("\n") + "{% endfor %}"
else:
images = "{% for image in images %}{{ image }}{% endfor %}" + text("\n")
return (
text(f"<|im_start|>system\n{cls._SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n")
+ "{% if images %}{{ sep }}" + images + "{% endif %}"
+ "{% if images %}{{ sep }}{% for image in images %}{{ image }}{% endfor %}" + text("\n") + "{% endif %}"
+ "{{ sep }}" + render("state")
+ "{{ sep }}" + text("\n\nSCHEMA FIELDS:\n")
+ "{% for q in questions %}"
@@ -111,23 +96,23 @@ class _ClefHeadMixin:
)
def set_gguf_parameters(self):
super().set_gguf_parameters() # ty: ignore[missing-attribute]
super().set_gguf_parameters()
head = self.hparams["decision"]
self.gguf_writer.add_decision_type(self._DECISION_TYPE)
self.gguf_writer.add_decision_type(gguf.DecisionType.CLEF)
self.gguf_writer.add_decision_routing_block_count(head["routing_layers"])
self.gguf_writer.add_decision_block_count(head["layers"])
self.gguf_writer.add_decision_head_count(head["heads"])
self.gguf_writer.add_layer_norm_eps(self._HEAD_NORM_EPS)
def get_tensors(self) -> Iterator[tuple[str, Tensor]]:
yield from super().get_tensors() # ty: ignore[missing-attribute]
yield from super().get_tensors()
from safetensors.torch import load_file
for name, data in load_file(self.dir_model / "joint_head.safetensors").items():
yield "joint_head." + name, data
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
if not name.startswith("joint_head."):
yield from super().modify_tensors(data_torch, name, bid) # ty: ignore[missing-attribute]
yield from super().modify_tensors(data_torch, name, bid)
return
parts = name.split(".")
@@ -160,31 +145,6 @@ class _ClefHeadMixin:
yield self.map_tensor_name(name), data_torch
@ModelBase.register("ClefModel")
class ClefModel(_ClefHeadMixin, Qwen3_5TextModel):
model_arch = gguf.MODEL_ARCH.CLEF
no_mtp = True # the checkpoint has no MTP head
@ModelBase.register("ClefModel")
class ClefVisionModel(Qwen3VLVisionModel):
pass
@ModelBase.register("ClefOmniModel")
class ClefOmniModel(_ClefHeadMixin, Qwen3OmniMoeTextModel):
model_arch = gguf.MODEL_ARCH.CLEF_OMNI
_NEWLINE_PER_IMAGE = True
_DECISION_TYPE = gguf.DecisionType.CLEF_OMNI
@ModelBase.register("ClefOmniModel")
class ClefOmniMmprojModel(Qwen3OmniMmprojModel):
# IMAGE_SIZE of joint_schema_model.py, the image budget is set there and not in the processor config
_IMAGE_MIN_PIXELS = 65_536
_IMAGE_MAX_PIXELS = 1_048_576
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_vision_min_pixels(self._IMAGE_MIN_PIXELS)
self.gguf_writer.add_vision_max_pixels(self._IMAGE_MAX_PIXELS)
+15 -11
View File
@@ -62,19 +62,23 @@ class GptOssModel(TextModel):
self.gguf_writer.add_tensor(new_name, new_data, raw_dtype=gguf.GGMLQuantizationType.MXFP4)
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
for name, get_scales in self.model_tensors.items():
if not name.endswith(("mlp.experts.down_proj_scales", "mlp.experts.gate_up_proj_scales")):
continue
proj = name.removesuffix("_scales")
blocks = self.model_tensors[proj + "_blocks"]()
scales = get_scales()
if proj.endswith("down_proj"):
self.repack_mxfp4(self.map_tensor_name(proj + ".weight"), blocks, scales)
else:
blocks0: Tensor = torch.zeros(1)
blocks1: Tensor = torch.zeros(1)
# we assume that tensors are loaded in the correct order
for name, data_torch in self.get_tensors():
if "mlp.experts.down_proj_blocks" in name:
blocks0 = data_torch
elif "mlp.experts.down_proj_scales" in name:
new_name = self.map_tensor_name(name.replace("_scales", ".weight"))
self.repack_mxfp4(new_name, blocks0, data_torch)
elif "mlp.experts.gate_up_proj_blocks" in name:
blocks0, blocks1 = data_torch[:, ::2, :, :], data_torch[:, 1::2, :, :]
elif "mlp.experts.gate_up_proj_scales" in name:
scales0, scales1 = data_torch[:, ::2, :], data_torch[:, 1::2, :]
new_name_gate = self.map_tensor_name(name.replace("gate_up_proj_scales", "gate_proj.weight"))
new_name_up = self.map_tensor_name(name.replace("gate_up_proj_scales", "up_proj.weight"))
self.repack_mxfp4(new_name_gate, blocks[:, ::2, :, :], scales[:, ::2, :])
self.repack_mxfp4(new_name_up, blocks[:, 1::2, :, :], scales[:, 1::2, :])
self.repack_mxfp4(new_name_gate, blocks0, scales0)
self.repack_mxfp4(new_name_up, blocks1, scales1)
return []
@classmethod
+38
View File
@@ -439,3 +439,41 @@ 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)
+174
View File
@@ -0,0 +1,174 @@
from __future__ import annotations
from typing import Iterable, TYPE_CHECKING
import torch
if TYPE_CHECKING:
from torch import Tensor
from .base import ModelBase, TextModel, gguf
@ModelBase.register("OlalaForCausalLM")
@ModelBase.example("OVHaiLLM/Olala-v1.0-mini-7A1B")
class OlalaModel(TextModel):
model_arch = gguf.MODEL_ARCH.OLALA
# the graph implements this variant only
_REQUIRED = {
"normalization_type": "rmsnorm",
"zero_centered_gamma": True,
"normalize_embeddings_ngpt": True,
"normalize_embeddings": False,
"geodesic_update": True,
"layer_norm_scaling": False,
"final_norm": False,
"normalize_lm_head": False,
"logits_scaling_ngpt": False,
"tie_lm_head": False,
"cosnet": False,
"mixer_gn": False,
"use_value_embedding": False,
"moe": True,
"layers_mlp_config": "",
"moe_shared_expert_gate": False,
"gate_attn": True,
"gate_type": "elementwise",
"gate_act": "silu",
"zero_centered_gate": True,
"qk_norm": True,
"token_shift_attn": True,
"scalable_softmax": True,
"xsa": False,
"rope_theta": 0.0,
"mamba_ngroups": 1,
"mamba3_add_trapezoid": True,
"mamba3_is_A_dd": True,
"mamba3_remove_conv": True,
"mamba3_rope": True,
"mamba3_postgate_norm": False,
}
# the reference block adds this constant to the gate projection when zero_centered_gate is set
_GATE_BIAS = 1.15
# names of the checkpoint tensors without a .weight/.bias suffix
_RENAME = {
"mixer.dt_bias": "mixer.dt.bias",
"mixer.B_bias": "mixer.B.bias",
"mixer.C_bias": "mixer.C.bias",
"mixer.softmax_scaler": "mixer.softmax_scaler.weight",
"mlp.expert_bias": "mlp.expert.bias",
}
_IN_PROJ = ("mixer.in_proj.weight", "mixer.in_proj_dyn.weight")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
bad = {k: self.hparams.get(k) for k, v in self._REQUIRED.items() if self.hparams.get(k) != v}
if bad:
raise ValueError(f"unsupported Olala config values: {bad}")
self._parts: dict[tuple[int, str], dict[str, Tensor]] = {}
def set_gguf_parameters(self):
hparams = self.hparams
n_embd = hparams["hidden_size"]
head_dim = hparams["head_dim"]
d_inner = hparams["expand_factor"] * n_embd
d_state = hparams["mamba_d_state"]
n_noise = hparams["num_attention_heads"] - hparams["num_signal_heads_diff"]
self.gguf_writer.add_block_count(self.block_count)
# the attention window of the reference implementation
self.gguf_writer.add_context_length(hparams["slw_wsize"])
self.gguf_writer.add_embedding_length(n_embd)
self.gguf_writer.add_head_count(hparams["num_attention_heads"])
# the noise heads of the differential attention are the kv heads, 0 marks a Mamba-3 layer
self.gguf_writer.add_head_count_kv([n_noise if t == "V" else 0 for t in hparams["layers_config"]])
self.gguf_writer.add_key_length(head_dim)
self.gguf_writer.add_value_length(head_dim)
self.gguf_writer.add_layer_norm_rms_eps(hparams["norm_epsilon"])
self.gguf_writer.add_attn_logit_softcapping(hparams["softcap_attn"])
self.gguf_writer.add_attention_scale(1.0 / head_dim if hparams["use_completed_p"] else head_dim ** -0.5)
self.gguf_writer.add_tpa_rank(hparams["tpa_rank"])
self.gguf_writer.add_expert_count(hparams["moe_num_routed_experts"])
self.gguf_writer.add_expert_used_count(hparams["moe_num_active_experts"])
self.gguf_writer.add_expert_feed_forward_length(hparams["moe_routed_intermediate_size"])
self.gguf_writer.add_expert_shared_feed_forward_length(hparams["moe_shared_intermediate_size"])
self.gguf_writer.add_moe_latent_size(hparams["moe_routed_input_dim"])
self.gguf_writer.add_expert_weights_scale(hparams["moe_routed_scaling_factor"])
self.gguf_writer.add_expert_weights_norm(True)
self.gguf_writer.add_expert_gating_func(gguf.ExpertGatingFuncType.SIGMOID)
self.gguf_writer.add_ssm_inner_size(d_inner)
self.gguf_writer.add_ssm_state_size(d_state)
self.gguf_writer.add_ssm_time_step_rank(d_inner // hparams["mamba_headdim"])
self.gguf_writer.add_ssm_group_count(hparams["mamba_ngroups"])
self.gguf_writer.add_ssm_mimo_rank(hparams["mamba_mimo_dim"])
# Mamba-3 rotates the first half of the B and C state dims by the data-dependent angles
self.gguf_writer.add_rope_dimension_count(d_state // 2)
self.gguf_writer.add_file_type(self.ftype)
def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool:
if any(self.match_model_tensor_name(new_name, key, bid, suffix=suffix) for key, suffix in (
(gguf.MODEL_TENSOR.SSM_B, ".bias"),
(gguf.MODEL_TENSOR.SSM_C, ".bias"),
(gguf.MODEL_TENSOR.SSM_MIMO_X, ""),
(gguf.MODEL_TENSOR.SSM_MIMO_Z, ""),
(gguf.MODEL_TENSOR.SSM_MIMO_OUT, ""))):
return gguf.GGMLQuantizationType.F32
# their inputs overflow F16 and the F16 scales of the Q8 activation blocks
if any(self.match_model_tensor_name(new_name, key, bid) for key in (
gguf.MODEL_TENSOR.SSM_OUT,
gguf.MODEL_TENSOR.FFN_DOWN_EXP,
gguf.MODEL_TENSOR.MOE_LATENT_UP)):
return gguf.GGMLQuantizationType.F32 if self.ftype == gguf.LlamaFileType.ALL_F32 else gguf.GGMLQuantizationType.BF16
return super().tensor_force_quant(name, new_name, bid, n_dims)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
if bid is not None:
local = name.removeprefix(f"model.layers.{bid}.")
if local.endswith(".prosres_scalar"):
return
if local in self._IN_PROJ:
# one projection for z, x, dt, A, trap per head, then B, C and the angles
p = self._parts.setdefault((bid, "in_proj"), {})
p[local] = data_torch
if len(p) == len(self._IN_PROJ):
del self._parts[(bid, "in_proj")]
data_torch = torch.cat([p[n] for n in self._IN_PROJ], dim=0)
yield self.map_tensor_name(f"model.layers.{bid}.{self._IN_PROJ[0]}"), data_torch
return
if local == "mixer_proj.weight":
attn = self.hparams["layers_config"][bid] == "V"
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_OUT if attn else gguf.MODEL_TENSOR.SSM_OUT, bid), data_torch
return
if local.startswith(("geodesic_mixer.", "geodesic_mlp.")):
# theta * scale + bias is divided by the layer number: fold it in
suffix = ".weight" if local.endswith(".scale") else ".bias"
name = f"model.layers.{bid}.{local.rsplit('.', 1)[0]}{suffix}"
data_torch = data_torch.float().reshape(1) / (bid + 1)
elif local in self._RENAME:
name = f"model.layers.{bid}.{self._RENAME[local]}"
new_name = self.map_tensor_name(name)
if any(self.match_model_tensor_name(new_name, key, bid) for key in (
gguf.MODEL_TENSOR.SSM_B_NORM,
gguf.MODEL_TENSOR.SSM_C_NORM,
gguf.MODEL_TENSOR.ATTN_Q_NORM,
gguf.MODEL_TENSOR.ATTN_K_NORM)):
# zero-centered gamma
data_torch = data_torch + 1
elif any(self.match_model_tensor_name(new_name, key, bid) for key in (
gguf.MODEL_TENSOR.ATTN_TPA_K_A,
gguf.MODEL_TENSOR.ATTN_TPA_V_A)):
# K and V are the product of the A and B factors divided by the rank: fold it into A
data_torch = data_torch / self.hparams["tpa_rank"]
elif self.match_model_tensor_name(new_name, gguf.MODEL_TENSOR.ATTN_GATE, bid):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid, ".bias"), torch.full((data_torch.shape[0],), self._GATE_BIAS)
yield new_name, data_torch
+1 -1
View File
@@ -69,7 +69,7 @@ Legend:
| L2_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
| LEAKY_RELU | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| LIGHTNING_INDEXER | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| MEAN | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
| MUL | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| MUL_MAT | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 |
+9 -16
View File
@@ -8979,14 +8979,10 @@
"OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=0","support","0","no","OpenCL"
"OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=0","support","0","no","OpenCL"
"OpenCL","SCALE","type=bf16,ne=[100,10,10,10],scale=0.500000,bias=0.000000,inplace=0,v=0","support","0","no","OpenCL"
"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=0","support","1","yes","OpenCL"
"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=0","support","1","yes","OpenCL"
"OpenCL","SCALE","type=f16,ne=[100,10,10,10],scale=0.500000,bias=0.000000,inplace=0,v=0","support","1","yes","OpenCL"
"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=0.000000,inplace=0,v=1","support","1","yes","OpenCL"
"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","1","yes","OpenCL"
"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","1","yes","OpenCL"
"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=0.000000,inplace=0,v=1","support","0","no","OpenCL"
"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","0","no","OpenCL"
"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","0","no","OpenCL"
"OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","0","no","OpenCL"
"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","1","yes","OpenCL"
"OpenCL","SILU_BACK","type=f32,ne=[64,5,4,3],eps=0.000001","support","0","no","OpenCL"
"OpenCL","NORM","type=f32,ne=[64,5,4,3],v=0,eps=0.000000,noncontig_rows=0","support","1","yes","OpenCL"
"OpenCL","RMS_NORM","type=f32,ne=[64,5,4,3],v=0,eps=0.000000,inplace=0","support","1","yes","OpenCL"
@@ -14825,7 +14821,7 @@
"OpenCL","ADD_ID","type_a=f32,type_b=f32,n_embd=129,n_experts=8,n_experts_used=4,n_token=129,skip=1","support","1","yes","OpenCL"
"OpenCL","SQR","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL"
"OpenCL","SQRT","type=f16,ne=[10,3,3,2]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL"
"OpenCL","SIN","type=f16,ne=[10,2,2,2]","support","0","no","OpenCL"
"OpenCL","COS","type=f16,ne=[10,2,2,2]","support","0","no","OpenCL"
"OpenCL","CLAMP","type=f16,ne=[10,5,4,3],min=-0.500000,max=0.500000,v=0","support","0","no","OpenCL"
@@ -14839,8 +14835,8 @@
"OpenCL","SQR","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL"
"OpenCL","SQRT","type=f16,ne=[7,1,5,3]","support","1","yes","OpenCL"
"OpenCL","SQRT","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f16,ne=[7,1,5,3]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL"
"OpenCL","LOG","type=f16,ne=[1024,1024,1,1]","support","0","no","OpenCL"
"OpenCL","SIN","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL"
"OpenCL","SIN","type=f16,ne=[1024,1024,1,1]","support","0","no","OpenCL"
"OpenCL","COS","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL"
@@ -14859,7 +14855,7 @@
"OpenCL","TRUNC","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL"
"OpenCL","SQR","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL"
"OpenCL","SQRT","type=f32,ne=[10,3,3,2]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL"
"OpenCL","SIN","type=f32,ne=[10,2,2,2]","support","0","no","OpenCL"
"OpenCL","COS","type=f32,ne=[10,2,2,2]","support","0","no","OpenCL"
"OpenCL","CLAMP","type=f32,ne=[10,5,4,3],min=-0.500000,max=0.500000,v=0","support","1","yes","OpenCL"
@@ -14873,11 +14869,8 @@
"OpenCL","SQR","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL"
"OpenCL","SQRT","type=f32,ne=[7,1,5,3]","support","1","yes","OpenCL"
"OpenCL","SQRT","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f32,ne=[7,1,5,3]","support","1","yes","OpenCL"
"OpenCL","LOG","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL"
"OpenCL","LOG","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL"
"OpenCL","LOG","type=bf16,ne=[7,1,5,3]","support","0","no","OpenCL"
"OpenCL","LOG","type=bf16,ne=[1024,1024,1,1]","support","0","no","OpenCL"
"OpenCL","LOG","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL"
"OpenCL","LOG","type=f32,ne=[1024,1024,1,1]","support","0","no","OpenCL"
"OpenCL","SIN","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL"
"OpenCL","SIN","type=f32,ne=[1024,1024,1,1]","support","0","no","OpenCL"
"OpenCL","COS","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL"
Can't render this file because it is too large.
-1
View File
@@ -24,7 +24,6 @@
// 7. The tensor data binary blob (optional, aligned).
//
// Strings are serialized as the string length (uint64_t) followed by the C string without the null terminator.
// Keys and tensor names must not contain null bytes, string values can.
// All enums are stored as int32_t.
// All bool values are stored as int8_t.
// If the special key "general.alignment" (uint32_t) is defined it is used for alignment,
+8 -45
View File
@@ -40,23 +40,14 @@ static __global__ void dequantize_block(const void * __restrict__ vx, dst_t * __
}
}
// has_rows: rows of k elements, block (x, y) converts part y of row rows[x] (row 0 for x == n_rows, nothing for negative entries)
template <bool need_check, bool has_rows>
static __global__ void dequantize_block_q8_0_f16(const void * __restrict__ vx, half * __restrict__ y, const int64_t k,
const int32_t * __restrict__ rows, const int64_t n_rows) {
template <bool need_check>
static __global__ void dequantize_block_q8_0_f16(const void * __restrict__ vx, half * __restrict__ y, const int64_t k) {
#if __CUDA_ARCH__ >= GGML_CUDA_CC_PASCAL
constexpr int nint = CUDA_Q8_0_NE_ALIGN/sizeof(int) + WARP_SIZE;
const int64_t i01 = has_rows && blockIdx.x < n_rows ? rows[blockIdx.x] : 0;
const int64_t ipart = has_rows ? blockIdx.y : blockIdx.x;
if (i01 < 0) {
return; // padding
}
const int64_t i0 = CUDA_Q8_0_NE_ALIGN*ipart;
const int * x0 = ((int *) vx) + i01*(k/QK8_0)*sizeof(block_q8_0)/sizeof(int) + ipart * nint;
half2 * y2 = (half2 *) (y + i01*k + i0);
const int64_t i0 = CUDA_Q8_0_NE_ALIGN*blockIdx.x;
const int * x0 = ((int *) vx) + blockIdx.x * nint;
half2 * y2 = (half2 *) (y + i0);
__shared__ int vals[nint];
@@ -85,7 +76,7 @@ static __global__ void dequantize_block_q8_0_f16(const void * __restrict__ vx, h
y2[iy/2 + threadIdx.x] = __hmul2(make_half2(qs.x, qs.y), __half2half2(d));
}
#else
GGML_UNUSED_VARS(vx, y, k, rows, n_rows);
GGML_UNUSED_VARS(vx, y, k);
NO_DEVICE_CODE;
#endif // __CUDA_ARCH__ >= GGML_CUDA_CC_PASCAL
}
@@ -277,31 +268,10 @@ static void dequantize_block_q8_0_f16_cuda(const void * __restrict__ vx, half *
const int num_blocks = (k + CUDA_Q8_0_NE_ALIGN - 1) / CUDA_Q8_0_NE_ALIGN;
if (k % CUDA_Q8_0_NE_ALIGN == 0) {
const bool need_check = false;
dequantize_block_q8_0_f16<need_check, false><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, k, nullptr, 0);
dequantize_block_q8_0_f16<need_check><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, k);
} else {
const bool need_check = true;
dequantize_block_q8_0_f16<need_check, false><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, k, nullptr, 0);
}
}
// for ne01 contiguous rows of ne00 elements, converts only the rows in rows[0..n_rows) and row 0
static void dequantize_block_q8_0_f16_rows_cuda(const void * vx, half * y, const int64_t ne00, const int64_t ne01,
const int32_t * rows, const int64_t n_rows, cudaStream_t stream) {
const int64_t nparts = (ne00 + CUDA_Q8_0_NE_ALIGN - 1) / CUDA_Q8_0_NE_ALIGN;
const int64_t nparts_all = (ne00*ne01 + CUDA_Q8_0_NE_ALIGN - 1) / CUDA_Q8_0_NE_ALIGN;
// convert all of the data if that needs fewer blocks (not elements), so this never launches more blocks than the full conversion
// the kernel reads int so a row has to start at a multiple of sizeof(int)
if ((n_rows + 1)*nparts >= nparts_all || nparts > 65535 || (ne00/QK8_0*sizeof(block_q8_0)) % sizeof(int) != 0) {
dequantize_block_q8_0_f16_cuda(vx, y, ne00*ne01, stream);
return;
}
const dim3 num_blocks(n_rows + 1, nparts, 1);
if (ne00 % CUDA_Q8_0_NE_ALIGN == 0) {
const bool need_check = false;
dequantize_block_q8_0_f16<need_check, true><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, ne00, rows, n_rows);
} else {
const bool need_check = true;
dequantize_block_q8_0_f16<need_check, true><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, ne00, rows, n_rows);
dequantize_block_q8_0_f16<need_check><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, k);
}
}
@@ -703,13 +673,6 @@ to_fp32_cuda_t ggml_get_to_fp32_cuda(ggml_type type) {
}
}
to_fp16_rows_cuda_t ggml_get_to_fp16_rows_cuda(ggml_type type) {
if (type == GGML_TYPE_Q8_0 && fp16_available(ggml_cuda_info().devices[ggml_cuda_get_device()].cc)) {
return dequantize_block_q8_0_f16_rows_cuda;
}
return nullptr;
}
to_fp16_nc_cuda_t ggml_get_to_fp16_nc_cuda(ggml_type type) {
switch (type) {
case GGML_TYPE_F32:
-6
View File
@@ -31,12 +31,6 @@ to_fp32_nc_cuda_t ggml_get_to_fp32_nc_cuda(ggml_type type);
to_fp16_nc_cuda_t ggml_get_to_fp16_nc_cuda(ggml_type type);
to_bf16_nc_cuda_t ggml_get_to_bf16_nc_cuda(ggml_type type);
// for ne01 contiguous rows of ne00 elements, converts only the rows in rows[0..n_rows) and row 0, negative entries are skipped
typedef void (*to_fp16_rows_cuda_t)(const void * x, half * y,
int64_t ne00, int64_t ne01, const int32_t * rows, int64_t n_rows, cudaStream_t stream);
to_fp16_rows_cuda_t ggml_get_to_fp16_rows_cuda(ggml_type type);
template<typename dst_t, typename src_t>
__host__ __device__ inline dst_t ggml_cuda_cast(src_t x) {
if constexpr (std::is_same_v<dst_t, src_t>) {
+4 -19
View File
@@ -1373,16 +1373,8 @@ void launch_fattn(
GGML_ASSERT(f16_extra.K != 0);
half * K_f16 = (half *) f16_extra.K;
if (ggml_is_contiguously_allocated(K)) {
// with kv_rows the kernel reads only the listed rows and row 0 (for padding), so convert only those
const to_fp16_rows_cuda_t to_fp16_rows = kv_rows && nb12*bs == K->ne[0]*ts && nb11 == K->ne[2]*nb12 ?
ggml_get_to_fp16_rows_cuda(K->type) : nullptr;
if (to_fp16_rows) {
to_fp16_rows(K_data, K_f16, K->ne[0]*K->ne[2], K->ne[1],
(const int32_t *) kv_rows->data, ggml_nelements(kv_rows), main_stream);
} else {
to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(K->type);
to_fp16(K_data, K_f16, ggml_nelements(K), main_stream);
}
to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(K->type);
to_fp16(K_data, K_f16, ggml_nelements(K), main_stream);
nb11 = nb11*bs*sizeof(half)/ts;
nb12 = nb12*bs*sizeof(half)/ts;
@@ -1415,15 +1407,8 @@ void launch_fattn(
GGML_ASSERT(f16_extra.V != 0);
half * V_f16 = (half *) f16_extra.V;
if (ggml_is_contiguously_allocated(V)) {
const to_fp16_rows_cuda_t to_fp16_rows = kv_rows && nb22*bs == V->ne[0]*ts && nb21 == V->ne[2]*nb22 ?
ggml_get_to_fp16_rows_cuda(V->type) : nullptr;
if (to_fp16_rows) {
to_fp16_rows(V_data, V_f16, V->ne[0]*V->ne[2], V->ne[1],
(const int32_t *) kv_rows->data, ggml_nelements(kv_rows), main_stream);
} else {
to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(V->type);
to_fp16(V_data, V_f16, ggml_nelements(V), main_stream);
}
to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(V->type);
to_fp16(V_data, V_f16, ggml_nelements(V), main_stream);
V_data = (char *) V_f16;
nb21 = nb21*bs*sizeof(half)/ts;
+2 -2
View File
@@ -754,7 +754,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
const int i = i0 + T_C_KQ::get_j(l);
const int j = ((threadIdx.y / np)*cols_per_warp + T_C_KQ::get_i(l)) / ncols2;
KQ_C[i00/(np*T_C_KQ::J)].x[l] += slope*__half2float(tile_mask[j*(nbatch_fa + 8) + i]);
KQ_C[i00/(np*T_C_KQ::J)].x[l] += __half2float(tile_mask[j*(nbatch_fa + 8) + i]);
}
#else
#pragma unroll
@@ -1913,7 +1913,7 @@ static __global__ void flash_attn_ext_f16(
#endif // __CUDA_ARCH__ == GGML_CUDA_CC_TURING
#if defined(AMD_WMMA_AVAILABLE)
if (ncols1*ncols2 < 16 || DKQ > 256) {
if (ncols1*ncols2 < 16 || ncols2 == 1 || DKQ > 256) {
NO_DEVICE_CODE;
return;
}
-6
View File
@@ -860,12 +860,6 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
return BEST_FATTN_KERNEL_MMA_F16;
}
// Mask-less attention with many queries (e.g. vision encoders) cannot use the GQA tiles above.
// The WMMA kernel is still much faster than the tile kernel for this case:
if (amd_wmma_available(cc) && !mask && Q->ne[0] <= 256 && Q->ne[1] >= 128) {
return BEST_FATTN_KERNEL_MMA_F16;
}
// If there are no tensor cores available, use the generic tile kernel:
if (can_use_vector_kernel) {
if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) {
+3 -13
View File
@@ -91,7 +91,6 @@ static constexpr __host__ __device__ int get_vdr_mmvq(ggml_type type) {
enum mmvq_parameter_table_id {
MMVQ_PARAMETERS_GENERIC = 0,
MMVQ_PARAMETERS_PASCAL_DP4A,
MMVQ_PARAMETERS_TURING,
MMVQ_PARAMETERS_GCN,
MMVQ_PARAMETERS_RDNA1,
@@ -119,8 +118,6 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() {
return MMVQ_PARAMETERS_GB10;
#elif __CUDA_ARCH__ == GGML_CUDA_CC_ORIN
return MMVQ_PARAMETERS_ORIN;
#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= GGML_CUDA_CC_DP4A && __CUDA_ARCH__ < GGML_CUDA_CC_VOLTA
return MMVQ_PARAMETERS_PASCAL_DP4A;
#else
return MMVQ_PARAMETERS_GENERIC;
#endif
@@ -151,9 +148,6 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) {
if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_ORIN) {
return MMVQ_PARAMETERS_ORIN;
}
if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_DP4A && ggml_cuda_highest_compiled_arch(cc) < GGML_CUDA_CC_VOLTA) {
return MMVQ_PARAMETERS_PASCAL_DP4A;
}
return MMVQ_PARAMETERS_GENERIC;
}
@@ -484,11 +478,7 @@ static constexpr __device__ int get_mmvq_mmid_max_batch_for_device() {
}
static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_dst, mmvq_parameter_table_id table_id, bool small_k = false, bool halve_iters = false) {
if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A) {
// Pascal cc 6.1/6.2 decode is bandwidth-bound on small SMs: 2 warps beat 4 for single-token.
if (table_id == MMVQ_PARAMETERS_PASCAL_DP4A && ncols_dst == 1) {
return 2;
}
if (table_id == MMVQ_PARAMETERS_GENERIC) {
switch (ncols_dst) {
case 1:
case 2:
@@ -651,7 +641,7 @@ static constexpr __host__ __device__ bool mmvq_two_rows_ncols1(ggml_type type) {
}
static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int ncols_dst, int table_id, bool small_k = false, int nwarps = 1) {
if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) {
if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) {
switch (ncols_dst) {
case 1:
if (small_k) {
@@ -660,7 +650,7 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int
if (table_id == MMVQ_PARAMETERS_GB10) {
return type == GGML_TYPE_IQ2_S || type == GGML_TYPE_IQ3_S ? 2 : 1;
}
return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1;
return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1;
case 2:
case 3:
case 4:
+9 -25
View File
@@ -135,11 +135,7 @@ static void unary_cuda(const T * x, T * dst, const int k, cudaStream_t stream) {
}
template <float (*op)(float), typename T>
static __global__ void unary_op_kernel_strided(
const T * x, T * dst, const int k,
const int64_t ne00, const int64_t ne01, const int64_t ne02,
const size_t nb00, const size_t nb01, const size_t nb02, const size_t nb03,
const size_t nb0, const size_t nb1, const size_t nb2, const size_t nb3) {
static __global__ void unary_op_kernel_strided(const T * x, T * dst, const int k,const int64_t ne00,const int64_t ne01,const int64_t ne02,const size_t nb00,const size_t nb01,const size_t nb02,const size_t nb03) {
ggml_cuda_pdl_lc();
const int i = blockDim.x*blockIdx.x + threadIdx.x;
@@ -153,25 +149,17 @@ static __global__ void unary_op_kernel_strided(
const int64_t i2 = rem % ne02;
const int64_t i3 = rem / ne02;
const size_t src_byte_offset = i0 * nb00 + i1 * nb01 + i2 * nb02 + i3 * nb03;
const size_t dst_byte_offset = i0 * nb0 + i1 * nb1 + i2 * nb2 + i3 * nb3;
const T * src_ptr = (const T *)((const char *)x + src_byte_offset);
T * dst_ptr = ( T *)(( char *)dst + dst_byte_offset);
const T * src_ptr = (const T *)((const char *)x + src_byte_offset);
ggml_cuda_pdl_sync();
*dst_ptr = ggml_cuda_cast<T>(op(ggml_cuda_cast<float>(*src_ptr)));
dst[i] = ggml_cuda_cast<T>(op(ggml_cuda_cast<float>(*src_ptr)));
}
template <float (*op)(float), typename T>
static void unary_cuda_strided(
const T * x, T * dst, const int k,
const int64_t ne00, const int64_t ne01, const int64_t ne02,
const size_t nb00, const size_t nb01, const size_t nb02, const size_t nb03,
const size_t nb0, const size_t nb1, const size_t nb2, const size_t nb3,
cudaStream_t stream) {
static void unary_cuda_strided(const T * x, T * dst, const int k,const int64_t ne00,const int64_t ne01,const int64_t ne02,const size_t nb00,const size_t nb01,const size_t nb02,const size_t nb03, cudaStream_t stream) {
const int num_blocks = (k + CUDA_NEG_BLOCK_SIZE - 1) / CUDA_NEG_BLOCK_SIZE;
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params((dim3)num_blocks, CUDA_NEG_BLOCK_SIZE, 0, stream);
ggml_cuda_kernel_launch(unary_op_kernel_strided<op, T>, launch_params,
x, dst, k, ne00, ne01, ne02, nb00, nb01, nb02, nb03, nb0, nb1, nb2, nb3);
ggml_cuda_kernel_launch(unary_op_kernel_strided<op, T>, launch_params, x, dst, k, ne00,ne01,ne02,nb00,nb01,nb02,nb03);
}
template <float (*op)(float)>
@@ -184,9 +172,8 @@ void ggml_cuda_op_unary(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16);
GGML_ASSERT(src0->type == dst->type);
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) {
if (ggml_is_contiguous(src0)) {
if (src0->type == GGML_TYPE_F16) {
unary_cuda<op>((const half *)src0_d, (half *)dst_d, ggml_nelements(src0), stream);
} else if (src0->type == GGML_TYPE_BF16) {
@@ -198,18 +185,15 @@ void ggml_cuda_op_unary(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
if (src0->type == GGML_TYPE_F16) {
unary_cuda_strided<op>((const half *)src0_d, (half *)dst_d, ggml_nelements(src0),
src0->ne[0], src0->ne[1], src0->ne[2],
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3],
dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3], stream);
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3], stream);
} else if (src0->type == GGML_TYPE_BF16) {
unary_cuda_strided<op>((const nv_bfloat16 *)src0_d, (nv_bfloat16 *)dst_d, ggml_nelements(src0),
src0->ne[0], src0->ne[1], src0->ne[2],
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3],
dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3], stream);
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3], stream);
} else {
unary_cuda_strided<op>((const float *)src0_d, (float *)dst_d, ggml_nelements(src0),
src0->ne[0], src0->ne[1], src0->ne[2],
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3],
dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3], stream);
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3], stream);
}
}
}
@@ -25,11 +25,32 @@
#define A_L1_START 0 // L1 SCP lines 0..15 for A (activations)
#define B_L1_START 16 // L1 SCP lines 16..31 for B (dequantized weights)
// L2 SCP layout per minion (double-buffered dequant panel).
// L2 SCP layout per minion (double-buffered dequant panel + sync counters).
// panel = BLOCK_K k-lines x TILE_M m (FP32) = 32 * 64 = 2048 bytes, in TenB
// [k][m] order: panel[k*TILE_M + m].
#define SCP_PANEL_SIZE (BLOCK_K * TILE_M * (uint64_t) sizeof(float)) // 2048
#define SCP_PER_MINION (2 * SCP_PANEL_SIZE) // 4096
#define SCP_PANEL_SIZE (BLOCK_K * TILE_M * (uint64_t) sizeof(float)) // 2048
#define SCP_READY_OFF (2 * SCP_PANEL_SIZE) // 4096
#define SCP_CONSUMED_OFF (SCP_READY_OFF + 64) // 4160
#define SCP_PER_MINION (SCP_CONSUMED_OFF + 64) // 4224
// Signal a counter value to the other hart via L2 SCP.
static inline void __attribute__((always_inline)) scp_signal(volatile uint32_t * flag, uint32_t value) {
*flag = value;
FENCE;
evict_to_l2((const void *) flag, 1, 64);
WAIT_CACHEOPS;
}
// Wait for a counter in L2 SCP to reach the expected value.
static inline void __attribute__((always_inline)) scp_wait(volatile uint32_t * flag, uint32_t expected) {
while (1) {
evict_to_l2((const void *) flag, 1, 64);
WAIT_CACHEOPS;
if (*flag >= expected) {
return;
}
}
}
// Dequantize one 32-element Q4_0 block of TILE_M weight rows into the FP32
// panel, written directly in TenB [k][m] order: panel[k*TILE_M + m].
@@ -171,17 +192,22 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
const int64_t kb_start = k_split * k_steps_per_split; // first block
const int64_t kb_end = kb_start + k_steps_per_split; // one past last
// L2 SCP pointers for this minion's double-buffered panels.
// L2 SCP pointers for this minion's double-buffered panels + sync.
uint64_t scp_base = local_minion * SCP_PER_MINION;
float * scp_panel[2] = {
(float *) et_shire_l2scp_local(scp_base),
(float *) et_shire_l2scp_local(scp_base + SCP_PANEL_SIZE),
};
volatile uint32_t * ready_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_READY_OFF);
volatile uint32_t * consumed_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_CONSUMED_OFF);
// ================================================================
// Hart 1: Q4_0 weight dequant producer
// ================================================================
if (is_hart1) {
scp_signal(ready_ctr, 0);
scp_signal(consumed_ctr, 0);
uint32_t chunk_id = 0;
for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles;
@@ -203,28 +229,22 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
for (int64_t kb = kb_start; kb < kb_end; ++kb) {
int buf = chunk_id & 1;
// Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers).
// Back-pressure: wait for hart 0 to finish with this buffer.
if (chunk_id >= 2) {
et_sem_wait(ET_BARRIER_MINION);
scp_wait(consumed_ctr, chunk_id - 1);
}
dequant_q4_0_panel(scp_panel[buf], src0_batch, mb, kb, nb1_0);
FENCE;
flush_to_l2_multi(scp_panel[buf], BLOCK_K, 64);
flush_to_l2(scp_panel[buf], BLOCK_K, 64);
WAIT_CACHEOPS;
et_sem_post(ET_BARRIER_MINION);
chunk_id++;
scp_signal(ready_ctr, chunk_id);
}
}
// Drain the up to 2 unconsumed FCC 0 credits from the wait-skip on chunks 0 and 1.
uint32_t drain = (chunk_id < 2) ? chunk_id : 2;
for (uint32_t d = 0; d < drain; ++d) {
et_sem_wait(ET_BARRIER_MINION);
}
FENCE;
return 0;
}
@@ -241,6 +261,11 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
#endif
CLEAR_TENSOR_ERROR;
evict_to_l2((const void *) ready_ctr, 1, 64);
WAIT_CACHEOPS;
evict_to_l2((const void *) consumed_ctr, 1, 64);
WAIT_CACHEOPS;
uint32_t chunk_id = 0;
for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles;
@@ -282,7 +307,8 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
int buf = chunk_id & 1;
// Wait for hart 1 to finish dequantizing this block.
et_sem_wait(ET_BARRIER_MINION);
chunk_id++;
scp_wait(ready_ctr, chunk_id);
// Two FMA passes over the 32-wide block (16 K-cols each).
for (int half = 0; half < 2; ++half) {
@@ -311,8 +337,7 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
}
// Signal that this buffer is free for hart 1 to reuse.
et_sem_post(ET_BARRIER_MINION);
chunk_id++;
scp_signal(consumed_ctr, chunk_id);
}
// K-split ring reduce.
@@ -10,7 +10,7 @@
// Hart 0: tensor engine (load A, load B from SCP, FMA, reduce, store)
// Hart 1: pack B into double-buffered L2 SCP panels, flush for tensor_load
//
// Sync: FCC 0 semaphores (et_sem_post / et_sem_wait).
// Sync: monotonic counters in L2 SCP with evict-based coherency.
// Double-buffered bpanel allows pack/FMA overlap.
//
#define NUM_COMPUTE_SHIRES 32
@@ -28,11 +28,34 @@
typedef uint16_t et_fp16_t;
// L2 SCP layout per minion (double-buffered bpanel)
// L2 SCP layout per minion (double-buffered bpanel + sync counters)
// [0..1023] bpanel buffer 0 (16 lines x 64 bytes)
// [1024..2047] bpanel buffer 1
#define SCP_BPANEL_SIZE (16 * 32 * sizeof(et_fp16_t)) // 1024 bytes
#define SCP_PER_MINION (2 * SCP_BPANEL_SIZE) // 2048 bytes
// [2048..2111] ready counter (hart1 -> hart0, own cache line)
// [2112..2175] consumed counter (hart0 -> hart1, own cache line)
#define SCP_BPANEL_SIZE (16 * 32 * sizeof(et_fp16_t)) // 1024 bytes
#define SCP_READY_OFF (2 * SCP_BPANEL_SIZE) // 2048
#define SCP_CONSUMED_OFF (SCP_READY_OFF + 64) // 2112
#define SCP_PER_MINION (SCP_CONSUMED_OFF + 64) // 2176
// Signal a counter value to the other hart via L2 SCP.
static inline void __attribute__((always_inline)) scp_signal(volatile uint32_t * flag, uint32_t value) {
*flag = value;
FENCE;
evict_to_l2((const void *) flag, 1, 64);
WAIT_CACHEOPS;
}
// Wait for a counter in L2 SCP to reach the expected value.
static inline void __attribute__((always_inline)) scp_wait(volatile uint32_t * flag, uint32_t expected) {
while (1) {
evict_to_l2((const void *) flag, 1, 64);
WAIT_CACHEOPS;
if (*flag >= expected) {
return;
}
}
}
/**
* Build the interleaved B panel that TensorFMA16A32 expects (vectorized).
@@ -147,17 +170,23 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
const int64_t k_start = k_split * k_steps_per_split * TILE_K;
const int64_t k_end = k_start + k_steps_per_split * TILE_K;
// L2 SCP pointers for this minion's double-buffered panels
// L2 SCP pointers for this minion's double-buffered panels + sync
uint64_t scp_base = local_minion * SCP_PER_MINION;
et_fp16_t * scp_bp[2] = {
(et_fp16_t *) et_shire_l2scp_local(scp_base),
(et_fp16_t *) et_shire_l2scp_local(scp_base + SCP_BPANEL_SIZE),
};
volatile uint32_t * ready_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_READY_OFF);
volatile uint32_t * consumed_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_CONSUMED_OFF);
// ================================================================
// Hart 1: B-panel packer
// ================================================================
if (is_hart1) {
// Initialize sync counters
scp_signal(ready_ctr, 0);
scp_signal(consumed_ctr, 0);
uint32_t chunk_id = 0;
for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles;
@@ -179,9 +208,9 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
for (int64_t kb = k_start; kb < k_end; kb += TILE_K) {
int buf = chunk_id & 1;
// Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers).
// Back-pressure: wait for hart 0 to finish with this buffer
if (chunk_id >= 2) {
et_sem_wait(ET_BARRIER_MINION);
scp_wait(consumed_ctr, chunk_id - 1);
}
pack_b_interleaved(scp_bp[buf], src0_batch, mb, kb, nb1_0);
@@ -190,17 +219,11 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
flush_to_l2(scp_bp[buf], 16, 64);
WAIT_CACHEOPS;
et_sem_post(ET_BARRIER_MINION);
chunk_id++;
scp_signal(ready_ctr, chunk_id);
}
}
// Drain the up to 2 unconsumed FCC 0 credits from the wait-skip on chunks 0 and 1.
uint32_t drain = (chunk_id < 2) ? chunk_id : 2;
for (uint32_t d = 0; d < drain; ++d) {
et_sem_wait(ET_BARRIER_MINION);
}
FENCE;
return 0;
}
@@ -217,6 +240,12 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
#endif
CLEAR_TENSOR_ERROR;
// Evict any stale L1D copies of sync counters
evict_to_l2((const void *) ready_ctr, 1, 64);
WAIT_CACHEOPS;
evict_to_l2((const void *) consumed_ctr, 1, 64);
WAIT_CACHEOPS;
uint32_t chunk_id = 0;
for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles;
@@ -253,7 +282,8 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
(uint64_t) nb1_1, 0);
// Wait for hart 1 to finish packing this chunk
et_sem_wait(ET_BARRIER_MINION);
chunk_id++;
scp_wait(ready_ctr, chunk_id);
// Load B from L2 SCP (hart 1 already flushed it)
tensor_load(false, false, B_L1_START, TENSOR_LOAD_PLAIN, 0, (uint64_t) scp_bp[buf], 0, 15, 64, 1);
@@ -268,8 +298,7 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
tensor_wait(TENSOR_FMA_WAIT);
// Signal that this buffer is free for hart 1 to reuse
et_sem_post(ET_BARRIER_MINION);
chunk_id++;
scp_signal(consumed_ctr, chunk_id);
}
// K-split ring reduce
@@ -476,23 +476,6 @@ static inline void __attribute__((always_inline)) flush_to_l2(const void * addr,
: "x31", "memory");
}
// Flush any number of cache lines to L2 in 16-line chunks (FlushVA hardware cap).
static inline void __attribute__((always_inline)) flush_to_l2_multi(const void * addr,
uint64_t nlines,
uint64_t stride) {
const char * p = (const char *) addr;
const uint64_t step = stride & 0xFFFFFFFFFFC0ULL;
while (nlines > 16) {
flush_to_l2(p, 16, step);
p += 16 * step;
nlines -= 16;
}
if (nlines > 0) {
flush_to_l2(p, nlines, step);
}
}
// Evict nlines cache lines at stride apart starting at addr from L1 to L2.
// Uses EvictVA (CSR 0x89F). Unlike flush_to_l2, this guarantees the line is
// NOT present in L1 after the operation - subsequent loads will miss and go
+2 -9
View File
@@ -22,18 +22,11 @@
#define HTP_TENSOR_TILE_SIZE_IQ4_NL 576
#define HTP_TENSOR_TILE_SIZE_MXFP4 544
#define HTP_TENSOR_TILE_SIZE_NVFP4 576
#define HTP_TENSOR_TILE_SIZE_IQ2_XXS 264
#define HTP_TENSOR_TILE_SIZE_IQ2_XXS 264
#define HTP_TENSOR_TILE_SCRATCH_IQ2_XXS 256
#define HTP_IQ2XXS_NIBBLE_BYTES 128 // 16 words for vlut16, padded to a vector
#define HTP_IQ2XXS_GRID_BYTES 512 // 256 entries x 8 elements x 2-bit magnitude code
#define HTP_IQ2XXS_TABLE_BYTES (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_GRID_BYTES)
#define HTP_IQ2XXS_LANE_OFF_BYTES 128 // per-lane copy offsets for grid gathers, one vector
#define HTP_IQ2XXS_GRID_COPIES 16 // gather lane h reads copy (h % 16) to spread bank conflicts
#define HTP_IQ2XXS_GRID_SKEW 4 // bank skew between copies
#define HTP_IQ2XXS_GRID_STRIDE (HTP_IQ2XXS_GRID_BYTES + HTP_IQ2XXS_GRID_SKEW)
#define HTP_IQ2XXS_GRID_REGION (HTP_IQ2XXS_GRID_COPIES * HTP_IQ2XXS_GRID_STRIDE)
#define HTP_IQ2XXS_GRID_OFF (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_LANE_OFF_BYTES)
#define HTP_IQ2XXS_LUT_BYTES ((HTP_IQ2XXS_GRID_OFF + HTP_IQ2XXS_GRID_REGION + 127) & ~127)
#define HTP_IQ2XXS_LUT_BYTES (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_GRID_BYTES)
#define HTP_TENSOR_TILE_SIZE_Q4_K 640
#define HTP_TENSOR_TILE_SIZE_Q5_K 768
#define HTP_TENSOR_TILE_SIZE_Q6_K 896
+1 -1
View File
@@ -8,7 +8,7 @@
#include <stdint.h>
#include "htp-tensor.h"
static const uint8_t __attribute__((aligned(128))) htp_iq2xxs_lut[HTP_IQ2XXS_TABLE_BYTES] = {
static const uint8_t __attribute__((aligned(128))) htp_iq2xxs_lut[HTP_IQ2XXS_LUT_BYTES] = {
0x08, 0x08, 0x00, 0x00, 0x19, 0x08, 0x00, 0x00, 0x2b, 0x08, 0x00, 0x00, 0x2b, 0x08, 0x00, 0x00,
0x08, 0x19, 0x00, 0x00, 0x19, 0x19, 0x00, 0x00, 0x2b, 0x19, 0x00, 0x00, 0x2b, 0x19, 0x00, 0x00,
0x08, 0x2b, 0x00, 0x00, 0x19, 0x2b, 0x00, 0x00, 0x2b, 0x2b, 0x00, 0x00, 0x2b, 0x2b, 0x00, 0x00,
+3 -6
View File
@@ -183,8 +183,7 @@ static inline HVX_Vector * iq2xxs_tile_scratch(const uint8_t * tile) {
// IQ2_XXS: start the 2 halfword grid-code gathers of a tile into its scratch, returns the sign/scale words
static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) {
HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_GRID_OFF;
const HVX_Vector v_lane = hvx_vmem(iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES);
const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES;
// lo: 4 grid indices per row, hi: 4 sign indices + scale per row
HVX_VectorPair p = Q6_W_vdeal_VVR(hvx_vmem(tile + VLEN), hvx_vmem(tile), -IQ2XXS_WORD_BYTES);
@@ -195,10 +194,8 @@ static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) {
Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT + IQ2XXS_IDX_BITS), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
HVX_Vector v_off1 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, 2 * IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
v_off0 = Q6_Vh_vadd_VhVh(v_off0, v_lane);
v_off1 = Q6_Vh_vadd_VhVh(v_off1, v_lane);
Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_REGION - 1, v_off0);
Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_REGION - 1, v_off1);
Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off0);
Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off1);
return Q6_V_hi_W(p);
}
+1 -21
View File
@@ -38,30 +38,10 @@ const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_lut[] = {
const uint8_t * iq2xxs_vtcm_lut;
_Static_assert((HTP_IQ2XXS_GRID_COPIES & (HTP_IQ2XXS_GRID_COPIES - 1)) == 0, "grid copies must be a power of 2");
// VTCM layout: nibble table, per-lane grid copy offsets, then HTP_IQ2XXS_GRID_COPIES skewed grid copies
void iq2xxs_lut_copy(uint8_t * restrict lut) {
uint16_t __attribute__((aligned(VLEN))) lane_off[HTP_IQ2XXS_LANE_OFF_BYTES / sizeof(uint16_t)];
for (uint32_t h = 0; h < HTP_IQ2XXS_LANE_OFF_BYTES / sizeof(uint16_t); h++) {
lane_off[h] = (h & (HTP_IQ2XXS_GRID_COPIES - 1)) * HTP_IQ2XXS_GRID_STRIDE;
}
for (uint32_t i = 0; i < HTP_IQ2XXS_NIBBLE_BYTES / VLEN; i++) {
for (uint32_t i = 0; i < HTP_IQ2XXS_LUT_BYTES / VLEN; i++) {
hvx_vmem(lut + i * VLEN) = hvx_vmem(htp_iq2xxs_lut + i * VLEN);
}
hvx_vmem(lut + HTP_IQ2XXS_NIBBLE_BYTES) = hvx_vmem(lane_off);
HVX_Vector v_grid[HTP_IQ2XXS_GRID_BYTES / VLEN];
for (uint32_t i = 0; i < HTP_IQ2XXS_GRID_BYTES / VLEN; i++) {
v_grid[i] = hvx_vmem(htp_iq2xxs_lut + HTP_IQ2XXS_NIBBLE_BYTES + i * VLEN);
}
for (uint32_t c = 0; c < HTP_IQ2XXS_GRID_COPIES; c++) {
for (uint32_t i = 0; i < HTP_IQ2XXS_GRID_BYTES / VLEN; i++) {
hvx_vmemu(lut + HTP_IQ2XXS_GRID_OFF + c * HTP_IQ2XXS_GRID_STRIDE + i * VLEN) = v_grid[i];
}
}
iq2xxs_vtcm_lut = lut;
}
+18 -31
View File
@@ -28,9 +28,6 @@
static const NSInteger MTLGPUFamilyMetal3_GGML = 5001;
static const NSInteger MTLGPUFamilyMetal4_GGML = 5002;
// overload of MTLGPUFamilyAppleX (not available in some environments)
static const NSInteger MTLGPUFamilyApple10_GGML = 1010;
// MTLLanguageVersion4_0 is not present in older SDKs
static const NSUInteger MTLLanguageVersion4_0_GGML = 4 << 16;
@@ -1112,33 +1109,6 @@ const char * ggml_metal_device_id_token(enum ggml_metal_device_id id) {
return "GGML_METAL_DEVICE_GENERIC";
}
static bool ggml_metal_has_tensor(id<MTLDevice> device) {
if (![device supportsFamily:MTLGPUFamilyMetal4_GGML]) {
return false;
}
if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) {
return false;
}
if (getenv("GGML_METAL_TENSOR_ENABLE") != NULL) {
return true;
}
// enable the tensor API by default for M5+ and A19+
// disable it for older chips because with the current implementation it is not useful
// - M2 Ultra: ~5% slower
// - M4, M4 Max: no significant difference
//
// TODO: try to update the tensor API kernels to at least match the simdgroup performance
if ([device supportsFamily:MTLGPUFamilyApple10_GGML]) {
return true;
}
GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__);
return false;
}
ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) {
ggml_metal_device_t dev = calloc(1, sizeof(struct ggml_metal_device));
@@ -1175,7 +1145,24 @@ ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) {
dev->props.has_bfloat = false;
}
dev->props.has_tensor = ggml_metal_has_tensor(dev->mtl_device);
dev->props.has_tensor = [dev->mtl_device supportsFamily:MTLGPUFamilyMetal4_GGML];
if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) {
dev->props.has_tensor = false;
}
// note: disable the tensor API by default for old chips because with the current implementation it is not useful
// - M2 Ultra: ~5% slower
// - M4, M4 Max: no significant difference
//
// TODO: try to update the tensor API kernels to at least match the simdgroup performance
if (getenv("GGML_METAL_TENSOR_ENABLE") == NULL &&
![[dev->mtl_device name] containsString:@"M5"] &&
![[dev->mtl_device name] containsString:@"M6"] &&
![[dev->mtl_device name] containsString:@"A19"] &&
![[dev->mtl_device name] containsString:@"A20"]) {
GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__);
dev->props.has_tensor = false;
}
// double-check that the tensor API compiles
if (dev->props.has_tensor) {
-1
View File
@@ -302,7 +302,6 @@ 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 {
+56 -78
View File
@@ -388,10 +388,12 @@ 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:
{
@@ -2769,59 +2771,7 @@ static int ggml_metal_op_mul_mat_mv(ggml_metal_op_t ctx, int idx) {
return 1;
}
// 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) {
int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
ggml_metal_library_t lib = ctx->lib;
@@ -3007,18 +2957,6 @@ static int ggml_metal_op_mul_mat_impl(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) {
@@ -3054,7 +2992,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);
}
static int ggml_metal_op_mul_mat_id_impl(ggml_metal_op_t ctx, int idx) {
int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
ggml_metal_library_t lib = ctx->lib;
@@ -3257,18 +3195,6 @@ static int ggml_metal_op_mul_mat_id_impl(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);
@@ -3315,6 +3241,58 @@ 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,6 +83,7 @@ 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);
+2 -5
View File
@@ -219,15 +219,12 @@ kernel void kernel_mul_mat_scale(
device const char * s = scale;
if (args.has_ids) {
// a skipped expert (id < 0) has zeroed output, do not scale it
if (args.use_ids) {
const int32_t expert = *((device const int32_t *) (ids + i1*args.ids_nb0 + i2*args.ids_nb1));
if (expert < 0) {
return;
}
if (args.use_ids) {
s += expert*args.s_nb1;
}
s += expert*args.s_nb1;
}
device float * dst_row = (device float *) (dst + i1*args.nb1 + i2*args.nb2 + i3*args.nb3);
+43 -81
View File
@@ -870,8 +870,7 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_sub, kernel_sub_row, kernel_sub_f16, kernel_sub_row_f16;
cl_kernel kernel_add_id;
cl_kernel kernel_add_id_add_id_swiglu_oai;
cl_kernel kernel_scale_f32, kernel_scale_f32_4, kernel_scale_f32_nc;
cl_kernel kernel_scale_f16, kernel_scale_f16_4, kernel_scale_f16_nc;
cl_kernel kernel_scale_f32, kernel_scale_f32_4;
cl_kernel kernel_sqr_cont_f32, kernel_sqr_cont_f32_4, kernel_sqr_cont_f16, kernel_sqr_cont_f16_4;
cl_kernel kernel_sqrt_cont_f32, kernel_sqrt_cont_f32_4, kernel_sqrt_cont_f16, kernel_sqrt_cont_f16_4;
cl_kernel kernel_mean_f32, kernel_mean_f32_4;
@@ -1173,7 +1172,6 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_ceil_f32, kernel_ceil_f32_4, kernel_ceil_f32_nc, kernel_ceil_f16, kernel_ceil_f16_4, kernel_ceil_f16_nc;
cl_kernel kernel_round_f32, kernel_round_f32_4, kernel_round_f32_nc, kernel_round_f16, kernel_round_f16_4, kernel_round_f16_nc;
cl_kernel kernel_trunc_f32, kernel_trunc_f32_4, kernel_trunc_f32_nc, kernel_trunc_f16, kernel_trunc_f16_4, kernel_trunc_f16_nc;
cl_kernel kernel_log_f32, kernel_log_f32_4, kernel_log_f32_nc, kernel_log_f16, kernel_log_f16_4, kernel_log_f16_nc;
cl_kernel kernel_softplus_f32, kernel_softplus_f32_4, kernel_softplus_f32_nc;
cl_kernel kernel_softplus_f16, kernel_softplus_f16_4, kernel_softplus_f16_nc;
cl_kernel kernel_upscale;
@@ -4695,12 +4693,8 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
cl_program prog =
build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts);
CL_CHECK((backend_ctx->kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err));
CL_CHECK((backend_ctx->kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err));
CL_CHECK((backend_ctx->kernel_scale_f32_nc = clCreateKernel(prog, "kernel_scale_f32_nc", &err), err));
CL_CHECK((backend_ctx->kernel_scale_f16 = clCreateKernel(prog, "kernel_scale_f16", &err), err));
CL_CHECK((backend_ctx->kernel_scale_f16_4 = clCreateKernel(prog, "kernel_scale_f16_4", &err), err));
CL_CHECK((backend_ctx->kernel_scale_f16_nc = clCreateKernel(prog, "kernel_scale_f16_nc", &err), err));
CL_CHECK((backend_ctx->kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err));
CL_CHECK((backend_ctx->kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
@@ -5198,7 +5192,6 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
CL_UNARY_EXT_K(ceil)
CL_UNARY_EXT_K(round)
CL_UNARY_EXT_K(trunc)
CL_UNARY_EXT_K(log)
#undef CL_UNARY_EXT_K
CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err));
CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err));
@@ -12836,8 +12829,7 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
op->type == op->src[1]->type;
}
case GGML_OP_SCALE:
return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
op->src[0]->type == op->type && ggml_is_contiguous_rows(op->src[0]);
return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]);
case GGML_OP_ADD:
if (op->type == GGML_TYPE_F16) {
const bool src0_ok = op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32;
@@ -12854,8 +12846,6 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
(op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16);
case GGML_OP_ADD_ID:
return op->src[0]->type == GGML_TYPE_F32;
case GGML_OP_LOG:
return op->src[0]->type == op->type && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
case GGML_OP_SQR:
case GGML_OP_SQRT:
return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
@@ -21903,7 +21893,6 @@ GGML_CL_UNARY_EXT_WRAP(ggml_cl_floor, floor)
GGML_CL_UNARY_EXT_WRAP(ggml_cl_ceil, ceil)
GGML_CL_UNARY_EXT_WRAP(ggml_cl_round, round)
GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc)
GGML_CL_UNARY_EXT_WRAP(ggml_cl_log, log)
#undef GGML_CL_UNARY_EXT_WRAP
@@ -39874,75 +39863,54 @@ static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0
}
static void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
GGML_ASSERT(src0 && src0->extra);
GGML_ASSERT(dst && dst->extra);
GGML_ASSERT(src0);
GGML_ASSERT(src0->extra);
GGML_ASSERT(dst);
GGML_ASSERT(dst->extra);
GGML_UNUSED(src1);
auto * backend_ctx = (ggml_backend_opencl_context *) backend->context;
const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra;
const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra;
GGML_ASSERT(ggml_is_contiguous(src0));
const cl_ulong offset0 = extra0->offset + src0->view_offs;
const cl_ulong offsetd = extrad->offset + dst->view_offs;
const float scale = ggml_get_op_params_f32(dst, 0);
const float bias = ggml_get_op_params_f32(dst, 1);
const bool is_f16 = src0->type == GGML_TYPE_F16;
ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context;
float scale;
float bias;
memcpy(&scale, ((int32_t *) dst->op_params) + 0, sizeof(float));
memcpy(&bias, ((int32_t *) dst->op_params) + 1, sizeof(float));
ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra;
ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra;
cl_ulong offset0 = extra0->offset + src0->view_offs;
cl_ulong offsetd = extrad->offset + dst->view_offs;
cl_kernel kernel;
if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) {
size_t n = ggml_nelements(dst);
const size_t alignment = 4 * ggml_element_size(src0);
if (n % 4 == 0 && offset0 % alignment == 0 && offsetd % alignment == 0) {
kernel = is_f16 ? backend_ctx->kernel_scale_f16_4 : backend_ctx->kernel_scale_f32_4;
n /= 4;
} else {
kernel = is_f16 ? backend_ctx->kernel_scale_f16 : backend_ctx->kernel_scale_f32;
}
int n = ggml_nelements(dst);
CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device));
CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0));
CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device));
CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale));
CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias));
size_t global_work_size[] = {n, 1, 1};
size_t local_work_size[] = {64, 1, 1};
size_t * local_work_size_ptr = local_work_size;
if (n % local_work_size[0] != 0 && !backend_ctx->non_uniform_workgroups) {
local_work_size_ptr = nullptr;
}
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst);
if (n % 4 == 0) {
kernel = backend_ctx->kernel_scale_f32_4;
n /= 4;
} else {
kernel = is_f16 ? backend_ctx->kernel_scale_f16_nc : backend_ctx->kernel_scale_f32_nc;
const cl_ulong ne00 = src0->ne[0];
GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb);
GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb);
CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device));
CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0));
CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device));
CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale));
CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias));
CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &ne00));
CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00));
CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01));
CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02));
CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03));
CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0));
CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1));
CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2));
CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb3));
const size_t nth = 64;
size_t global_work_size[] = {(size_t)src0->ne[1] * nth, (size_t)src0->ne[2], (size_t)src0->ne[3]};
size_t local_work_size[] = {nth, 1, 1};
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst);
kernel = backend_ctx->kernel_scale_f32;
}
CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device));
CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0));
CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device));
CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale));
CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias));
size_t global_work_size[] = {(size_t)n, 1, 1};
size_t local_work_size[] = {64, 1, 1};
size_t * local_work_size_ptr = local_work_size;
if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) {
local_work_size_ptr = nullptr; // Let driver choose the work-group sizes.
}
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst);
}
static void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
@@ -41891,12 +41859,6 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor
}
func = ggml_cl_sub;
break;
case GGML_OP_LOG:
if (!any_on_device) {
return false;
}
func = ggml_cl_log;
break;
case GGML_OP_SQR:
if (!any_on_device) {
return false;
+18 -96
View File
@@ -1,105 +1,27 @@
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
kernel void kernel_scale_f32(
global const float * src0,
ulong offset0,
global float * dst,
ulong offsetd,
float scale,
float bias
global float * src0,
ulong offset0,
global float * dst,
ulong offsetd,
float scale,
float bias
) {
src0 = (global const float *)((global const char *)src0 + offset0);
dst = (global float *)((global char *)dst + offsetd);
const size_t i = get_global_id(0);
dst[i] = src0[i] * scale + bias;
src0 = (global float*)((global char*)src0 + offset0);
dst = (global float*)((global char*)dst + offsetd);
dst[get_global_id(0)] = src0[get_global_id(0)] * scale + bias;
}
kernel void kernel_scale_f32_4(
global const float4 * src0,
ulong offset0,
global float4 * dst,
ulong offsetd,
float scale,
float bias
global float4 * src0,
ulong offset0,
global float4 * dst,
ulong offsetd,
float scale,
float bias
) {
src0 = (global const float4 *)((global const char *)src0 + offset0);
dst = (global float4 *)((global char *)dst + offsetd);
const size_t i = get_global_id(0);
dst[i] = src0[i] * scale + bias;
}
kernel void kernel_scale_f16(
global const half * src0,
ulong offset0,
global half * dst,
ulong offsetd,
float scale,
float bias
) {
src0 = (global const half *)((global const char *)src0 + offset0);
dst = (global half *)((global char *)dst + offsetd);
const size_t i = get_global_id(0);
dst[i] = convert_half(convert_float(src0[i]) * scale + bias);
}
kernel void kernel_scale_f16_4(
global const half4 * src0,
ulong offset0,
global half4 * dst,
ulong offsetd,
float scale,
float bias
) {
src0 = (global const half4 *)((global const char *)src0 + offset0);
dst = (global half4 *)((global char *)dst + offsetd);
const size_t i = get_global_id(0);
dst[i] = convert_half4(convert_float4(src0[i]) * scale + bias);
}
kernel void kernel_scale_f32_nc(
global const char * src0,
ulong offset0,
global char * dst,
ulong offsetd,
float scale,
float bias,
ulong ne00,
ulong nb00, ulong nb01, ulong nb02, ulong nb03,
ulong nb0, ulong nb1, ulong nb2, ulong nb3
) {
const size_t i1 = get_group_id(0);
const size_t i2 = get_group_id(1);
const size_t i3 = get_group_id(2);
src0 += offset0 + i1*nb01 + i2*nb02 + i3*nb03;
dst += offsetd + i1*nb1 + i2*nb2 + i3*nb3;
for (size_t i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
global const float * x = (global const float *)(src0 + i0*nb00);
global float * y = (global float *)(dst + i0*nb0);
*y = *x * scale + bias;
}
}
kernel void kernel_scale_f16_nc(
global const char * src0,
ulong offset0,
global char * dst,
ulong offsetd,
float scale,
float bias,
ulong ne00,
ulong nb00, ulong nb01, ulong nb02, ulong nb03,
ulong nb0, ulong nb1, ulong nb2, ulong nb3
) {
const size_t i1 = get_group_id(0);
const size_t i2 = get_group_id(1);
const size_t i3 = get_group_id(2);
src0 += offset0 + i1*nb01 + i2*nb02 + i3*nb03;
dst += offsetd + i1*nb1 + i2*nb2 + i3*nb3;
for (size_t i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) {
global const half * x = (global const half *)(src0 + i0*nb00);
global half * y = (global half *)(dst + i0*nb0);
*y = convert_half(convert_float(*x) * scale + bias);
}
src0 = (global float4*)((global char*)src0 + offset0);
dst = (global float4*)((global char*)dst + offsetd);
dst[get_global_id(0)] = src0[get_global_id(0)] * scale + bias;
}
@@ -74,7 +74,6 @@ kernel void kernel_##NAME##_f16_nc( \
} \
}
UNARY_EXT(log, log(x), log(x))
UNARY_EXT(sgn, sign(x), sign(x))
UNARY_EXT(step, x > 0.0f ? 1.0f : 0.0f, select((float4)0.0f, (float4)1.0f, x > 0.0f))
UNARY_EXT(elu, x > 0.0f ? x : expm1(x), select(expm1(x), x, x > 0.0f))
@@ -614,15 +614,8 @@ struct vk_op_soft_max_push_constants {
uint32_t n_head_log2;
uint32_t nrows_x;
uint32_t has_sinks;
uint32_t ne0_1mp, ne0_1L;
uint32_t ne0_12mp, ne0_12L;
};
template <> inline void init_pushconst_fastdiv(vk_op_soft_max_push_constants &p) {
init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
}
struct vk_op_argsort_push_constants {
uint32_t ncols;
uint32_t ncols_padded;
-11
View File
@@ -234,13 +234,6 @@ static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
#define MAX_PARAMETER_COUNT 12
// binding of the IQ1/IQ2/IQ3 grid tables (see vk_iq_grids), after the regular parameters.
// It is written once per descriptor set and never changes.
#define IQ_GRID_BINDING MAX_PARAMETER_COUNT
// bindings in the descriptor set layout shared by all pipelines
#define NUM_DESCRIPTOR_BINDINGS (MAX_PARAMETER_COUNT + 1)
#define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
#define GGML_VK_GDN_CM_V 64u
@@ -978,7 +971,6 @@ struct vk_device_struct {
vk_pipeline pipeline_silu_back_f32;
vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
vk_pipeline pipeline_soft_max_short_f32, pipeline_soft_max_short_f32_f16;
vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
vk_pipeline pipeline_soft_max_back_f32;
@@ -996,7 +988,6 @@ struct vk_device_struct {
vk_pipeline pipeline_topk_radix_f32;
vk_pipeline pipeline_topk_radix_qsa; // qwen4 QSA indexer fusion (f16 mask)
vk_pipeline pipeline_sum_rows_f32;
vk_pipeline pipeline_sum_rows_short_f32;
vk_pipeline pipeline_cross_entropy_loss_f32, pipeline_cross_entropy_loss_f32_wg512;
vk_pipeline pipeline_cross_entropy_loss_back_f32, pipeline_cross_entropy_loss_back_f32_wg512;
vk_pipeline pipeline_fwht_f32[num_fwht_pipelines];
@@ -1079,8 +1070,6 @@ struct vk_device_struct {
vk::Fence fence;
vk_buffer sync_staging;
vk_buffer iq_grid_buf;
ggml_backend_buffer_type buffer_type;
bool disable_fusion;
+13 -79
View File
@@ -1,9 +1,5 @@
#include "ggml-vulkan-common.h"
#define GGML_COMMON_DECL_CPP
#define GGML_COMMON_IMPL_CPP
#include "ggml-common.h"
static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
vk::PhysicalDeviceProperties props = device.getProperties();
@@ -580,45 +576,6 @@ static bool ggml_vk_roll_bk_loop(const uint32_t * code, size_t word_count, std::
return true;
}
// Grid tables of the IQ1/IQ2/IQ3 types, read by the shaders at IQ_GRID_BINDING.
// The offsets must match the IQ*_GRID_OFFSET values in types.glsl (bytes).
struct vk_iq_grids {
uint32_t iq1s[NGRID_IQ1S/2]; // 2 bits per value (v & 3), two grid entries per uint32
uint32_t iq1s_gpu[NGRID_IQ1S]; // 4 bits per value (v + 1), values 0-3 in the low nibbles
uint64_t iq2xxs[256];
uint64_t iq2xs[512];
uint64_t iq2s[1024];
uint32_t iq3xxs[256];
uint32_t iq3s[512];
};
static_assert(offsetof(vk_iq_grids, iq1s_gpu) == 4096);
static_assert(offsetof(vk_iq_grids, iq2xxs) == 12288);
static_assert(offsetof(vk_iq_grids, iq2xs) == 14336);
static_assert(offsetof(vk_iq_grids, iq2s) == 18432);
static_assert(offsetof(vk_iq_grids, iq3xxs) == 26624);
static_assert(offsetof(vk_iq_grids, iq3s) == 27648);
static void ggml_vk_init_iq_grids(vk_device & device) {
auto grids = std::make_unique<vk_iq_grids>(); // zero-initialized
for (int i = 0; i < NGRID_IQ1S; ++i) {
const int8_t * g = (const int8_t *) &iq1s_grid[i];
uint32_t gpu = 0;
for (int j = 0; j < 8; ++j) {
grids->iq1s[i / 2] |= (uint32_t)(g[j] & 3) << (16 * (i % 2) + 2 * j);
gpu |= (uint32_t)(g[j] + 1) << (8 * (j % 4) + 4 * (j / 4));
}
grids->iq1s_gpu[i] = gpu;
}
memcpy(grids->iq2xxs, iq2xxs_grid, sizeof(grids->iq2xxs));
memcpy(grids->iq2xs, iq2xs_grid, sizeof(grids->iq2xs));
memcpy(grids->iq2s, iq2s_grid, sizeof(grids->iq2s));
memcpy(grids->iq3xxs, iq3xxs_grid, sizeof(grids->iq3xxs));
memcpy(grids->iq3s, iq3s_grid, sizeof(grids->iq3s));
device->iq_grid_buf = ggml_vk_create_buffer_device(device, sizeof(vk_iq_grids));
ggml_vk_buffer_write(device->iq_grid_buf, 0, grids.get(), sizeof(vk_iq_grids));
}
static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint,
uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
@@ -920,7 +877,7 @@ void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
if (pool_idx >= ctx->descriptor_pools.size()) {
vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, NUM_DESCRIPTOR_BINDINGS * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
}
@@ -931,15 +888,6 @@ void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
}
vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
// the IQ grid tables live at the same binding in every set; shaders that don't use them ignore it
const vk::DescriptorBufferInfo iq_grid_info{ device->iq_grid_buf->buffer, 0, VK_WHOLE_SIZE };
std::vector<vk::WriteDescriptorSet> iq_grid_writes;
for (const vk::DescriptorSet & set : sets) {
iq_grid_writes.push_back({ set, IQ_GRID_BINDING, 0, 1, vk::DescriptorType::eStorageBuffer, nullptr, &iq_grid_info });
}
device->device.updateDescriptorSets(iq_grid_writes, {});
ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
pool_idx++;
@@ -4108,8 +4056,6 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
ggml_vk_create_pipeline(device, device->pipeline_soft_max_short_f32, "soft_max_short_f32", soft_max_short_f32_len, soft_max_short_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {256, 1, 1}, { 256 }, 1);
ggml_vk_create_pipeline(device, device->pipeline_soft_max_short_f32_f16, "soft_max_short_f32_f16", soft_max_short_f32_f16_len, soft_max_short_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {256, 1, 1}, { 256 }, 1);
ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true);
ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32, "soft_max_large1_f32", soft_max_large1_f32_len, soft_max_large1_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
@@ -4181,7 +4127,6 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true);
ggml_vk_create_pipeline(device, device->pipeline_sum_rows_short_f32, "sum_rows_short_f32", sum_rows_short_f32_len, sum_rows_short_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256 }, 1, true);
ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32, "cross_entropy_loss_f32", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32_wg512, "cross_entropy_loss_f32_wg512", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { 512 }, 1);
ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_back_f32, "cross_entropy_loss_back_f32", cross_entropy_loss_back_f32_len, cross_entropy_loss_back_f32_data, "main", 4, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
@@ -5732,7 +5677,7 @@ vk_device ggml_vk_get_device(size_t idx) {
std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
for (uint32_t i = 0; i < NUM_DESCRIPTOR_BINDINGS; i++) {
for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
dsl_binding_flags.push_back({});
}
@@ -5774,8 +5719,6 @@ vk_device ggml_vk_get_device(size_t idx) {
device->fence = device->device.createFence({});
ggml_vk_init_iq_grids(device);
device->buffer_type = {
/* .iface = */ ggml_backend_vk_buffer_type_interface,
/* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
@@ -9677,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) {
} else if (gqa_ratio > 1 && workgroups_x <= Br) {
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;
@@ -10623,15 +10566,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
}
if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
if (src0->ne[0] <= 8) {
return ctx->device->pipeline_soft_max_short_f32;
}
return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
}
if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
if (src0->ne[0] <= 8) {
return ctx->device->pipeline_soft_max_short_f32_f16;
}
return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
}
return nullptr;
@@ -10693,9 +10630,6 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
case GGML_OP_SUM_ROWS:
case GGML_OP_MEAN:
if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
if (op != GGML_OP_SUM && src0->ne[0] <= 8) {
return ctx->device->pipeline_sum_rows_short_f32;
}
return ctx->device->pipeline_sum_rows_f32;
}
return nullptr;
@@ -12512,14 +12446,16 @@ 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);
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));
}
memcpy(&p.param1, &s01_packed, sizeof(float));
memcpy(&p.param2, &s23_packed, sizeof(float));
ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
}
@@ -12957,8 +12893,7 @@ void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const g
m0, m1,
n_head_log2,
nrows_x,
src2 != nullptr,
0, 0, 0, 0,
src2 != nullptr
};
if (ncols <= 16384) {
@@ -18484,7 +18419,6 @@ vk_device_struct::~vk_device_struct() {
device.destroyFence(fence);
ggml_vk_destroy_buffer(sync_staging);
ggml_vk_destroy_buffer(iq_grid_buf);
if (compute_queue) compute_queue->cmd_pool.destroy(device);
if (transfer_queue) transfer_queue->cmd_pool.destroy(device);
@@ -84,7 +84,6 @@ layout (constant_id = 8) const uint TN = 16;
layout (constant_id = 9) const uint TK = 16;
layout (constant_id = 10) const uint WARP = 32;
layout (constant_id = 11) const uint DEVICE_ARCH = 0; // vk_device_architecture (ggml-vulkan.cpp)
#define VK_ARCH_AMD_RDNA3 4u
#define VK_ARCH_AMD_RDNA4 5u
#define BK 32
@@ -104,8 +103,7 @@ shared vec2 buf_a_dm[BM * BK_STEP]; // .x = d, .y = m
shared float buf_a_d[BM * BK_STEP * KSCALES];
#endif
// uvec4 so that the B stores and fragment loads move 16 bytes per access
shared uvec4 buf_b_qs[BN * QPITCH / 4];
shared uint32_t buf_b_qs[BN * QPITCH];
shared float buf_b_d[BN * BK_STEP];
#if defined(DATA_A_Q4_1) || defined(DATA_A_Q5_1) || defined(DATA_A_Q4_K) || defined(DATA_A_Q5_K)
@@ -126,8 +124,7 @@ shared int8_t cm1_kvalues[16];
const uint CM_ELEMS = (TM * TN) / WARP;
#define ACC_BIAS_BITS 0x4B400000
#define ACC_BIAS_F 12582912.0f
// wave32: the bias measured faster on RDNA3 for all tested models, but slower on RDNA4 for MoE models
#define USE_MAGIC_BIAS (WARP != 32 || DEVICE_ARCH == VK_ARCH_AMD_RDNA3)
const bool USE_MAGIC_BIAS = WARP != 32;
// Accumulator row for element e: RDNA4 blocked, RDNA3/3.5 interleaved.
uint cm_elem_row(uint e) {
@@ -135,13 +132,13 @@ uint cm_elem_row(uint e) {
return (DEVICE_ARCH == VK_ARCH_AMD_RDNA4) ? (e + row_half * CM_ELEMS) : (row_half + 2u * e);
}
// min_term = asymmetric-quant min*b_sum correction; pass -0.0 for symmetric types so prev + min_term folds away.
// min_term = asymmetric-quant min*b_sum correction (0 for symmetric types).
ACC_TYPE cm1_accumulate(ACC_TYPE prev, int acc_e, float scale_a, float nbias_a, float scale_b, float min_term) {
if (USE_MAGIC_BIAS) {
const float t = fma(intBitsToFloat(acc_e), scale_a, nbias_a);
return ACC_TYPE(fma(t, scale_b, float(prev) + min_term));
}
return ACC_TYPE(fma(float(acc_e) * scale_a, scale_b, float(prev) + min_term));
return prev + ACC_TYPE(fma(float(acc_e) * scale_a, scale_b, min_term));
}
#ifdef MUL_MAT_ID
@@ -322,7 +319,7 @@ void main() {
[[unroll]] for (uint c = 0; c < cms_per_col; c++) {
coopmat<int8_t, gl_ScopeSubgroup, TK, TN, gl_MatrixUseB> cache_b;
coopMatLoad(cache_b, buf_b_qs, ((b_col0 + c * TN) * QPITCH + ks * (BK / 4) + h * (TK / 4)) / 4, QPITCH / 4, gl_CooperativeMatrixLayoutColumnMajor);
coopMatLoad(cache_b, buf_b_qs, (b_col0 + c * TN) * QPITCH + ks * (BK / 4) + h * (TK / 4), QPITCH, gl_CooperativeMatrixLayoutColumnMajor);
const float scale_b_v = buf_b_d[ks * BN + b_col0 + c * TN + elem_col0];
@@ -335,7 +332,7 @@ void main() {
[[unroll]] for (uint e = 0; e < CM_ELEMS; e++) {
sums[tile_idx * CM_ELEMS + e] = cm1_accumulate(
sums[tile_idx * CM_ELEMS + e], int(acc[e]),
scale_a[e], nbias_a[e], scale_b_v, -0.0);
scale_a[e], nbias_a[e], scale_b_v, 0.0);
}
}
}
@@ -352,7 +349,7 @@ void main() {
}
[[unroll]] for (uint c = 0; c < cms_per_col; c++) {
[[unroll]] for (uint h = 0; h < K_SUB; h++) {
coopMatLoad(cache_b[c * K_SUB + h], buf_b_qs, ((b_col0 + c * TN) * QPITCH + ks * (BK / 4) + h * (TK / 4)) / 4, QPITCH / 4, gl_CooperativeMatrixLayoutColumnMajor);
coopMatLoad(cache_b[c * K_SUB + h], buf_b_qs, (b_col0 + c * TN) * QPITCH + ks * (BK / 4) + h * (TK / 4), QPITCH, gl_CooperativeMatrixLayoutColumnMajor);
}
}
@@ -405,7 +402,7 @@ void main() {
}
[[unroll]] for (uint c = 0; c < cms_per_col; c++) {
[[unroll]] for (uint h = 0; h < K_SUB; h++) {
coopMatLoad(cache_b[c * K_SUB + h], buf_b_qs, ((b_col0 + c * TN) * QPITCH + ks * (BK / 4) + h * (TK / 4)) / 4, QPITCH / 4, gl_CooperativeMatrixLayoutColumnMajor);
coopMatLoad(cache_b[c * K_SUB + h], buf_b_qs, (b_col0 + c * TN) * QPITCH + ks * (BK / 4) + h * (TK / 4), QPITCH, gl_CooperativeMatrixLayoutColumnMajor);
}
}
@@ -437,7 +434,7 @@ void main() {
[[unroll]] for (uint e = 0; e < CM_ELEMS; e++) {
sums[tile_idx * CM_ELEMS + e] = cm1_accumulate(
sums[tile_idx * CM_ELEMS + e], int(acc[e]),
scale_a[e], nbias_a[e], scale_b[c], -0.0);
scale_a[e], nbias_a[e], scale_b[c], 0.0);
}
}
}
@@ -528,7 +528,11 @@ block_b_prefetch block_b_load(uint ib_outer, uint ib_inner, uint loadr) {
void block_b_to_shmem(block_b_prefetch blk, uint buf_ib, uint ks, uint loadr, bool in_bounds) {
const ivec4 v = in_bounds ? blk.qs : ivec4(0);
buf_b_qs[(buf_ib * QPITCH + ks * (BK / 4)) / 4 + loadr] = uvec4(v);
const uint base = buf_ib * QPITCH + ks * (BK / 4) + loadr * 4;
buf_b_qs[base ] = v.x;
buf_b_qs[base + 1] = v.y;
buf_b_qs[base + 2] = v.z;
buf_b_qs[base + 3] = v.w;
if (loadr == 0) {
buf_b_d[ks * BN + buf_ib] = in_bounds ? float(blk.d) : 0.0f;
#if defined(DATA_A_Q4_1) || defined(DATA_A_Q5_1) || defined(DATA_A_Q4_K) || defined(DATA_A_Q5_K)
+18 -6
View File
@@ -5,8 +5,13 @@
layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
uint roll_idx(uint i, uint shift, uint ne) {
return i >= shift ? i - shift : ne - (shift - i);
uint wrap_idx(int i, uint ne) {
if (i < 0) {
return i + ne;
} else if (i >= ne) {
return i - ne;
}
return i;
}
void main() {
@@ -22,10 +27,17 @@ 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 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 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 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;
@@ -1,94 +0,0 @@
#version 450
#extension GL_EXT_control_flow_attributes : enable
layout (push_constant) uniform parameter
{
uint KX;
uint KY;
uint ne00;
uint ne01;
uint ne02;
uint ne12;
uint ne13;
uint nb11;
uint nb12;
uint nb13;
float scale;
float max_bias;
float m0;
float m1;
uint n_head_log2;
uint nrows_x;
uint has_sinks;
uint ne0_1mp, ne0_1L;
uint ne0_12mp, ne0_12L;
} p;
#include "types.glsl"
#include "utils.glsl"
layout(constant_id = 0) const uint BLOCK_SIZE = 256;
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
layout (binding = 1) readonly buffer Y {B_TYPE data_b[];};
layout (binding = 2) readonly buffer Z {float data_c[];};
layout (binding = 3) buffer D {D_TYPE data_d[];};
const uint MAX_COLS = 8;
void main() {
const uint rowx = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x;
if (rowx >= p.nrows_x) {
return;
}
const uint i03 = fastdiv(rowx, p.ne0_12mp, p.ne0_12L);
const uint i012 = rowx - i03 * p.ne01 * p.ne02;
const uint i02 = fastdiv(i012, p.ne0_1mp, p.ne0_1L);
const uint i01 = i012 - i02 * p.ne01;
uint rowy_start = 0;
if (p.KY > 0) {
rowy_start = i01 * p.nb11 + fastmod(i02, p.ne12) * p.nb12 + fastmod(i03, p.ne13) * p.nb13;
}
float slope = 1.0f;
if (p.max_bias > 0.0f) {
const float base = i02 < p.n_head_log2 ? p.m0 : p.m1;
const uint exp = i02 < p.n_head_log2 ? i02 + 1 : 2*(i02 - p.n_head_log2) + 1;
slope = pow(base, exp);
}
FLOAT_TYPE vals[MAX_COLS];
FLOAT_TYPE max_val = p.has_sinks == 0 ? uintBitsToFloat(0xFF800000) : data_c[i02];
[[unroll]] for (uint col = 0; col < MAX_COLS; ++col) {
if (col < p.KX) {
const FLOAT_TYPE b = p.KY > 0 ? FLOAT_TYPE(data_b[rowy_start + col]) : FLOAT_TYPE(0.0f);
vals[col] = FLOAT_TYPE(data_a[rowx * p.KX + col]) * p.scale + slope * b;
max_val = max(max_val, vals[col]);
}
}
FLOAT_TYPE sum = p.has_sinks == 0 ? FLOAT_TYPE(0.0f) : FLOAT_TYPE(exp(FLOAT_TYPE(data_c[i02]) - max_val));
[[unroll]] for (uint col = 0; col < MAX_COLS; ++col) {
if (col < p.KX) {
vals[col] = exp(vals[col] - max_val);
sum += vals[col];
}
}
const FLOAT_TYPE rcpdivisor = 1.0/sum;
[[unroll]] for (uint col = 0; col < MAX_COLS; ++col) {
if (col < p.KX) {
data_d[rowx * p.KX + col] = D_TYPE(vals[col] * rcpdivisor);
}
}
}
@@ -1,35 +0,0 @@
#version 450
#include "types.glsl"
#include "sum_rows.glsl"
#extension GL_EXT_control_flow_attributes : enable
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
layout (constant_id = 0) const uint BLOCK_SIZE = 256;
void main() {
const uint row = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x;
if (row >= p.ne01 * p.ne02 * p.ne03) { return; }
const uint i03 = fastdiv(row, p.ne0_12mp, p.ne0_12L);
const uint i03_offset = i03 * p.ne01*p.ne02;
const uint i02 = fastdiv(row - i03_offset, p.ne0_1mp, p.ne0_1L);
const uint i01 = row - i03_offset - i02*p.ne01;
const uint src_idx = get_aoffset() + i01 * p.nb01 + i02 * p.nb02 + i03 * p.nb03;
const uint dst_idx = get_doffset() + i01 * p.nb11 + i02 * p.nb12 + i03 * p.nb13;
FLOAT_TYPE sum = FLOAT_TYPE(0.0);
for (uint i = 0; i < p.n_cols; ++i) {
sum += FLOAT_TYPE(data_a[src_idx + i]);
}
data_d[dst_idx] = D_TYPE(sum * p.weight);
}
File diff suppressed because it is too large Load Diff
@@ -1059,8 +1059,6 @@ void process_shaders() {
string_to_spv("soft_max_f32", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("soft_max_f32_f16", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}}));
string_to_spv("soft_max_short_f32", "soft_max_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("soft_max_short_f32_f16", "soft_max_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}}));
string_to_spv("soft_max_back_f32", "soft_max_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("soft_max_large1_f32", "soft_max_large1.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
@@ -1095,7 +1093,6 @@ void process_shaders() {
string_to_spv("argmax_f32", "argmax.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "int"}}));
string_to_spv("sum_rows_f32", "sum_rows.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("sum_rows_short_f32", "sum_rows_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("cross_entropy_loss_f32", "cross_entropy_loss.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("cross_entropy_loss_back_f32", "cross_entropy_loss_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("fwht_f32", "fwht.comp", {{"A_TYPE", "float"}});
@@ -86,7 +86,6 @@ 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;
@@ -449,26 +448,16 @@ 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_split == other.replay_split;
replay == other.replay;
}
};
@@ -479,7 +468,6 @@ 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;
}
};
@@ -1332,16 +1320,12 @@ 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>
@@ -2063,8 +2047,6 @@ 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()) {
@@ -2092,10 +2074,7 @@ class ggml_webgpu_shader_lib {
variant += "_fused_cache";
}
if (key.replay_split) {
defines.push_back("REPLAY_SPLIT");
variant += "_replay_split";
} else if (key.replay) {
if (key.replay) {
defines.push_back("REPLAY");
variant += "_replay";
}
@@ -2109,43 +2088,6 @@ 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()) {
+24 -56
View File
@@ -1569,6 +1569,11 @@ 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,
@@ -1586,8 +1591,7 @@ 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_storage_buffers = ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage;
shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
webgpu_pipeline pipeline = ctx->shader_lib->get_gated_delta_net_pipeline(shader_lib_ctx);
@@ -1631,8 +1635,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, // n_pend
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0, // keep
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) (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,
@@ -1650,63 +1654,23 @@ 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, dst),
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),
};
if (dst_fuse) {
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 6, dst_fuse));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse));
}
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);
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));
}
// 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 } },
});
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs);
}
static std::optional<webgpu_encoded_op> ggml_webgpu_set_rows(webgpu_context & ctx,
@@ -3946,7 +3910,9 @@ 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_can_fuse_gdn_cache(ctx->global_ctx, cgraph, node_idx, num_encoded_ops)) {
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)) {
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);
@@ -5493,7 +5459,9 @@ 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_are_same_stride(src0, src1) &&
ggml_webgpu_gated_delta_net_n_storage_buffers(op, false) <=
ctx->webgpu_global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage;
}
break;
case GGML_OP_CLAMP:
@@ -14,44 +14,40 @@ 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(6)
@group(0) @binding(7)
var<storage, read_write> dst_fuse: array<f32>;
#define DST_SNAP dst_fuse
#define NEXT_BINDING 7
#define NEXT_BINDING 8
#else
#define DST_SNAP dst
#define NEXT_BINDING 6
#define NEXT_BINDING 7
#endif
// 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)
// pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
@group(0) @binding(NEXT_BINDING)
var<storage, read_write> pend_k: array<f32>;
@group(0) @binding(NEXT_BINDING + 2)
@group(0) @binding(NEXT_BINDING + 1)
var<storage, read_write> pend_v: array<f32>;
@group(0) @binding(NEXT_BINDING + 3)
@group(0) @binding(NEXT_BINDING + 2)
var<storage, read_write> pend_gb: array<f32>;
@group(0) @binding(NEXT_BINDING + 4)
@group(0) @binding(NEXT_BINDING + 3)
var<storage, read_write> n_rep: array<i32>;
var<workgroup> wg_n_rep: u32;
#define PARAMS_BINDING (NEXT_BINDING + 5)
#define PARAMS_BINDING (NEXT_BINDING + 4)
#else
#define PARAMS_BINDING (NEXT_BINDING + 1)
#endif
#define PARAMS_BINDING NEXT_BINDING
#endif
struct Params {
@@ -129,12 +125,7 @@ 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
@@ -265,7 +256,7 @@ fn main(
workgroupBarrier();
}
#if defined(REPLAY) || defined(REPLAY_SPLIT)
#ifdef REPLAY
// replay with keep: the state output is the state after the replay
let write_state = params.K == 1u && params.keep == 0u;
#else
@@ -1,118 +0,0 @@
@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];
}
}
+71 -51
View File
@@ -107,7 +107,6 @@ 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"
@@ -207,6 +206,7 @@ class Keys:
CAUSAL = "{arch}.attention.causal"
Q_LORA_RANK = "{arch}.attention.q_lora_rank"
KV_LORA_RANK = "{arch}.attention.kv_lora_rank"
TPA_RANK = "{arch}.attention.tpa_rank"
DECAY_LORA_RANK = "{arch}.attention.decay_lora_rank"
ICLR_LORA_RANK = "{arch}.attention.iclr_lora_rank"
VALUE_RESIDUAL_MIX_LORA_RANK = "{arch}.attention.value_residual_mix_lora_rank"
@@ -349,6 +349,7 @@ class Keys:
STATE_SIZE = "{arch}.ssm.state_size"
TIME_STEP_RANK = "{arch}.ssm.time_step_rank"
GROUP_COUNT = "{arch}.ssm.group_count"
MIMO_RANK = "{arch}.ssm.mimo_rank"
DT_B_C_RMS = "{arch}.ssm.dt_b_c_rms"
NORM_EPSILON = "{arch}.ssm.norm_epsilon"
@@ -653,7 +654,6 @@ class MODEL_ARCH(IntEnum):
QWEN35MOE = auto()
CLEF = auto()
VLLM_DECISION2 = auto()
CLEF_OMNI = auto()
CLOVER_MOE = auto()
QWEN4EXP = auto()
PHI2 = auto()
@@ -752,6 +752,7 @@ class MODEL_ARCH(IntEnum):
LFM2MOE = auto()
LFM3 = auto()
ZAYA1 = auto()
OLALA = auto()
DREAM = auto()
SMALLTHINKER = auto()
LLADA = auto()
@@ -1590,6 +1591,21 @@ class MODEL_TENSOR(IntEnum):
ROUTER_FC1 = auto()
ROUTER_FC2 = auto()
ROUTER_OUT = auto()
# olala
SSM_B = auto()
SSM_C = auto()
SSM_MIMO_X = auto()
SSM_MIMO_Z = auto()
SSM_MIMO_OUT = auto()
ATTN_TPA_K_A = auto()
ATTN_TPA_K_B = auto()
ATTN_TPA_V_A = auto()
ATTN_TPA_V_B = auto()
ATTN_SHIFT_K = auto()
ATTN_SHIFT_V = auto()
ATTN_DIFF_LAMBDA = auto()
ATTN_GEO = auto()
FFN_GEO = auto()
# lfm2 audio
A_ENC_NORM_CONV = auto()
A_ENC_LINEAR_POS = auto()
@@ -1685,7 +1701,6 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
MODEL_ARCH.QWEN35MOE: "qwen35moe",
MODEL_ARCH.CLEF: "clef",
MODEL_ARCH.VLLM_DECISION2: "vllm-decision2",
MODEL_ARCH.CLEF_OMNI: "clef-omni",
MODEL_ARCH.CLOVER_MOE: "clover_moe",
MODEL_ARCH.QWEN4EXP: "qwen4exp",
MODEL_ARCH.PHI2: "phi2",
@@ -1785,6 +1800,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
MODEL_ARCH.LFM2MOE: "lfm2moe",
MODEL_ARCH.LFM3: "lfm3",
MODEL_ARCH.ZAYA1: "zaya1",
MODEL_ARCH.OLALA: "olala",
MODEL_ARCH.DREAM: "dream",
MODEL_ARCH.SMALLTHINKER: "smallthinker",
MODEL_ARCH.LLADA: "llada",
@@ -2660,12 +2676,64 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
MODEL_TENSOR.ROUTER_FC1: "blk.{bid}.ffn_router_fc1",
MODEL_TENSOR.ROUTER_FC2: "blk.{bid}.ffn_router_fc2",
MODEL_TENSOR.ROUTER_OUT: "blk.{bid}.ffn_router_out",
MODEL_TENSOR.SSM_B: "blk.{bid}.ssm_b",
MODEL_TENSOR.SSM_C: "blk.{bid}.ssm_c",
MODEL_TENSOR.SSM_MIMO_X: "blk.{bid}.ssm_mimo_x",
MODEL_TENSOR.SSM_MIMO_Z: "blk.{bid}.ssm_mimo_z",
MODEL_TENSOR.SSM_MIMO_OUT: "blk.{bid}.ssm_mimo_out",
MODEL_TENSOR.ATTN_TPA_K_A: "blk.{bid}.attn_tpa_k_a",
MODEL_TENSOR.ATTN_TPA_K_B: "blk.{bid}.attn_tpa_k_b",
MODEL_TENSOR.ATTN_TPA_V_A: "blk.{bid}.attn_tpa_v_a",
MODEL_TENSOR.ATTN_TPA_V_B: "blk.{bid}.attn_tpa_v_b",
MODEL_TENSOR.ATTN_SHIFT_K: "blk.{bid}.attn_shift_k",
MODEL_TENSOR.ATTN_SHIFT_V: "blk.{bid}.attn_shift_v",
MODEL_TENSOR.ATTN_DIFF_LAMBDA: "blk.{bid}.attn_diff_lambda",
MODEL_TENSOR.ATTN_GEO: "blk.{bid}.attn_geo",
MODEL_TENSOR.FFN_GEO: "blk.{bid}.ffn_geo",
MODEL_TENSOR.D2T: "d2t",
MODEL_TENSOR.ATTN_V_GATE: "blk.{bid}.attn_v_gate",
MODEL_TENSOR.ATTN_V_EXP: "blk.{bid}.attn_v_exps",
}
MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_ARCH.OLALA: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT,
MODEL_TENSOR.SSM_IN,
MODEL_TENSOR.SSM_DT,
MODEL_TENSOR.SSM_B_NORM,
MODEL_TENSOR.SSM_C_NORM,
MODEL_TENSOR.SSM_B,
MODEL_TENSOR.SSM_C,
MODEL_TENSOR.SSM_D,
MODEL_TENSOR.SSM_MIMO_X,
MODEL_TENSOR.SSM_MIMO_Z,
MODEL_TENSOR.SSM_MIMO_OUT,
MODEL_TENSOR.SSM_OUT,
MODEL_TENSOR.ATTN_Q,
MODEL_TENSOR.ATTN_Q_NORM,
MODEL_TENSOR.ATTN_K_NORM,
MODEL_TENSOR.ATTN_TPA_K_A,
MODEL_TENSOR.ATTN_TPA_K_B,
MODEL_TENSOR.ATTN_TPA_V_A,
MODEL_TENSOR.ATTN_TPA_V_B,
MODEL_TENSOR.ATTN_SHIFT_K,
MODEL_TENSOR.ATTN_SHIFT_V,
MODEL_TENSOR.ATTN_SSMAX,
MODEL_TENSOR.ATTN_DIFF_LAMBDA,
MODEL_TENSOR.ATTN_GATE,
MODEL_TENSOR.ATTN_OUT,
MODEL_TENSOR.ATTN_GEO,
MODEL_TENSOR.FFN_GATE_INP,
MODEL_TENSOR.FFN_EXP_PROBS_B,
MODEL_TENSOR.MOE_LATENT_DOWN,
MODEL_TENSOR.FFN_UP_EXP,
MODEL_TENSOR.FFN_DOWN_EXP,
MODEL_TENSOR.MOE_LATENT_UP,
MODEL_TENSOR.FFN_UP_SHEXP,
MODEL_TENSOR.FFN_DOWN_SHEXP,
MODEL_TENSOR.FFN_GEO,
],
MODEL_ARCH.MMPROJ: [
MODEL_TENSOR.V_MMPROJ,
MODEL_TENSOR.V_MMPROJ_FC,
@@ -3777,53 +3845,6 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.DECISION_SCORER,
MODEL_TENSOR.DECISION_SCORER_OUT,
],
MODEL_ARCH.CLEF_OMNI: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
MODEL_TENSOR.OUTPUT,
MODEL_TENSOR.ATTN_NORM,
MODEL_TENSOR.ATTN_Q,
MODEL_TENSOR.ATTN_Q_NORM,
MODEL_TENSOR.ATTN_K,
MODEL_TENSOR.ATTN_K_NORM,
MODEL_TENSOR.ATTN_V,
MODEL_TENSOR.ATTN_OUT,
MODEL_TENSOR.ATTN_QKV,
MODEL_TENSOR.FFN_NORM,
MODEL_TENSOR.FFN_GATE_INP,
MODEL_TENSOR.FFN_DOWN_EXP,
MODEL_TENSOR.FFN_UP_EXP,
MODEL_TENSOR.FFN_GATE_EXP,
# decision head
MODEL_TENSOR.TOKEN_TYPES,
MODEL_TENSOR.DEC_ATTN_NORM,
MODEL_TENSOR.DEC_ATTN_Q,
MODEL_TENSOR.DEC_ATTN_K,
MODEL_TENSOR.DEC_ATTN_V,
MODEL_TENSOR.DEC_ATTN_OUT,
MODEL_TENSOR.DEC_CROSS_ATTN_NORM,
MODEL_TENSOR.DEC_CROSS_ATTN_NORM_KV,
MODEL_TENSOR.DEC_CROSS_ATTN_Q,
MODEL_TENSOR.DEC_CROSS_ATTN_K,
MODEL_TENSOR.DEC_CROSS_ATTN_V,
MODEL_TENSOR.DEC_CROSS_ATTN_OUT,
MODEL_TENSOR.DEC_FFN_NORM,
MODEL_TENSOR.DEC_FFN_DOWN,
MODEL_TENSOR.DEC_FFN_UP,
MODEL_TENSOR.DECISION_HIDDEN_NORM,
MODEL_TENSOR.DECISION_PROJ_MEMORY,
MODEL_TENSOR.DECISION_PROJ_QUESTION,
MODEL_TENSOR.DECISION_PROJ_OPTION_QUESTION,
MODEL_TENSOR.DECISION_PROJ_GLOBAL,
MODEL_TENSOR.DECISION_PROJ_OPTION_CONTEXT,
MODEL_TENSOR.DECISION_PROJ_OPTION_LEXICAL,
MODEL_TENSOR.DECISION_OPTION_SUMMARY_NORM,
MODEL_TENSOR.DECISION_FIELD_NORM,
MODEL_TENSOR.DECISION_OPTION_NORM,
MODEL_TENSOR.DECISION_SCALES,
MODEL_TENSOR.DECISION_SCORER,
MODEL_TENSOR.DECISION_SCORER_OUT,
],
MODEL_ARCH.VLLM_DECISION2: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
@@ -7703,7 +7724,6 @@ class DecisionType:
GRANITE_SWITCH = "granite-switch" # same as openjev, run by the decision aLoRA of granite switch
H2O_LIGHTNING = "h2o-lightning" # same as openjev, labels read after an answer prefill
MINICPM_OCR_JEV = "openbmb-minicpm-ocr-jev" # class scores of a value head read at the last token, one fixed task
CLEF_OMNI = "cloudflare-clef-omni" # same as clef on the Qwen3-Omni thinker, with audio input and no video input
class VisionProjectorType:
+6 -3
View File
@@ -705,9 +705,6 @@ 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)
@@ -1078,6 +1075,9 @@ class GGUFWriter:
def add_kv_lora_rank(self, length: int) -> None:
self.add_uint32(Keys.Attention.KV_LORA_RANK.format(arch=self.arch), length)
def add_tpa_rank(self, length: int) -> None:
self.add_uint32(Keys.Attention.TPA_RANK.format(arch=self.arch), length)
def add_decay_lora_rank(self, length: int) -> None:
self.add_uint32(Keys.Attention.DECAY_LORA_RANK.format(arch=self.arch), length)
@@ -1346,6 +1346,9 @@ class GGUFWriter:
def add_ssm_group_count(self, value: int) -> None:
self.add_uint32(Keys.SSM.GROUP_COUNT.format(arch=self.arch), value)
def add_ssm_mimo_rank(self, value: int) -> None:
self.add_uint32(Keys.SSM.MIMO_RANK.format(arch=self.arch), value)
def add_ssm_dt_b_c_rms(self, value: bool) -> None:
self.add_bool(Keys.SSM.DT_B_C_RMS.format(arch=self.arch), value)
+35
View File
@@ -3435,6 +3435,41 @@ class TensorNameMap:
# architecture-specific block mappings
arch_block_mappings_cfg: dict[MODEL_ARCH, dict[MODEL_TENSOR, tuple[str, ...]]] = {
MODEL_ARCH.OLALA: {
# the converter appends mixer.in_proj_dyn (B, C and the rotary angles) to ssm_in
MODEL_TENSOR.SSM_IN: ("model.layers.{bid}.mixer.in_proj",),
MODEL_TENSOR.SSM_DT: ("model.layers.{bid}.mixer.dt",),
MODEL_TENSOR.SSM_B_NORM: ("model.layers.{bid}.mixer.B_norm.norm",),
MODEL_TENSOR.SSM_C_NORM: ("model.layers.{bid}.mixer.C_norm.norm",),
MODEL_TENSOR.SSM_B: ("model.layers.{bid}.mixer.B",),
MODEL_TENSOR.SSM_C: ("model.layers.{bid}.mixer.C",),
MODEL_TENSOR.SSM_D: ("model.layers.{bid}.mixer.D",),
MODEL_TENSOR.SSM_MIMO_X: ("model.layers.{bid}.mixer.in_proj_mimo_x",),
MODEL_TENSOR.SSM_MIMO_Z: ("model.layers.{bid}.mixer.in_proj_mimo_z",),
MODEL_TENSOR.SSM_MIMO_OUT: ("model.layers.{bid}.mixer.out_proj_mimo",),
MODEL_TENSOR.ATTN_Q: ("model.layers.{bid}.mixer.c_q",),
MODEL_TENSOR.ATTN_Q_NORM: ("model.layers.{bid}.mixer.q_norm.norm",),
MODEL_TENSOR.ATTN_K_NORM: ("model.layers.{bid}.mixer.k_norm.norm",),
MODEL_TENSOR.ATTN_TPA_K_A: ("model.layers.{bid}.mixer.W_A_k",),
MODEL_TENSOR.ATTN_TPA_K_B: ("model.layers.{bid}.mixer.W_B_k",),
MODEL_TENSOR.ATTN_TPA_V_A: ("model.layers.{bid}.mixer.W_A_v",),
MODEL_TENSOR.ATTN_TPA_V_B: ("model.layers.{bid}.mixer.W_B_v",),
MODEL_TENSOR.ATTN_SHIFT_K: ("model.layers.{bid}.mixer.shift_proj_k",),
MODEL_TENSOR.ATTN_SHIFT_V: ("model.layers.{bid}.mixer.shift_proj_v",),
MODEL_TENSOR.ATTN_SSMAX: ("model.layers.{bid}.mixer.softmax_scaler",),
MODEL_TENSOR.ATTN_DIFF_LAMBDA: ("model.layers.{bid}.mixer.lambda_proj",),
MODEL_TENSOR.ATTN_GATE: ("model.layers.{bid}.gate_proj",),
MODEL_TENSOR.ATTN_GEO: ("model.layers.{bid}.geodesic_mixer",),
MODEL_TENSOR.FFN_GATE_INP: ("model.layers.{bid}.mlp.moe_gate",),
MODEL_TENSOR.FFN_EXP_PROBS_B: ("model.layers.{bid}.mlp.expert",),
MODEL_TENSOR.MOE_LATENT_DOWN: ("model.layers.{bid}.mlp.down_proj",),
MODEL_TENSOR.FFN_UP_EXP: ("model.layers.{bid}.mlp.experts.experts",),
MODEL_TENSOR.FFN_DOWN_EXP: ("model.layers.{bid}.mlp.experts.output_experts",),
MODEL_TENSOR.MOE_LATENT_UP: ("model.layers.{bid}.mlp.up_proj",),
MODEL_TENSOR.FFN_UP_SHEXP: ("model.layers.{bid}.mlp.shared_experts.fc_1",),
MODEL_TENSOR.FFN_DOWN_SHEXP: ("model.layers.{bid}.mlp.shared_experts.fc_2",),
MODEL_TENSOR.FFN_GEO: ("model.layers.{bid}.geodesic_mlp",),
},
MODEL_ARCH.ZAYA1: {
MODEL_TENSOR.ATTN_Q: ("model.layers.{bid}.self_attn.qkv_proj.q_proj",),
MODEL_TENSOR.ATTN_K: ("model.layers.{bid}.self_attn.qkv_proj.k_proj",),
@@ -1,365 +0,0 @@
{%- 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 -%}
+35 -4
View File
@@ -45,7 +45,6 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
{ LLM_ARCH_QWEN35, "qwen35" },
{ LLM_ARCH_QWEN35MOE, "qwen35moe" },
{ LLM_ARCH_CLEF, "clef" },
{ LLM_ARCH_CLEF_OMNI, "clef-omni" },
{ LLM_ARCH_VLLM_DECISION2, "vllm-decision2" },
{ LLM_ARCH_QWEN4EXP, "qwen4exp" },
{ LLM_ARCH_PHI2, "phi2" },
@@ -143,6 +142,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
{ LLM_ARCH_LFM2MOE, "lfm2moe" },
{ LLM_ARCH_LFM3, "lfm3" },
{ LLM_ARCH_ZAYA1, "zaya1" },
{ LLM_ARCH_OLALA, "olala" },
{ LLM_ARCH_DREAM, "dream" },
{ LLM_ARCH_SMALLTHINKER, "smallthinker" },
{ LLM_ARCH_LLADA, "llada" },
@@ -224,7 +224,6 @@ 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" },
@@ -319,6 +318,7 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
{ LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
{ LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
{ LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
{ LLM_KV_ATTENTION_TPA_RANK, "%s.attention.tpa_rank" },
{ LLM_KV_ATTENTION_DECAY_LORA_RANK, "%s.attention.decay_lora_rank" },
{ LLM_KV_ATTENTION_ICLR_LORA_RANK, "%s.attention.iclr_lora_rank" },
{ LLM_KV_ATTENTION_VALUE_RESIDUAL_MIX_LORA_RANK, "%s.attention.value_residual_mix_lora_rank" },
@@ -424,6 +424,7 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
{ LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
{ LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
{ LLM_KV_SSM_GROUP_COUNT, "%s.ssm.group_count" },
{ LLM_KV_SSM_MIMO_RANK, "%s.ssm.mimo_rank" },
{ LLM_KV_SSM_DT_B_C_RMS, "%s.ssm.dt_b_c_rms" },
{ LLM_KV_SSM_NORM_EPS, "%s.ssm.norm_epsilon" },
@@ -966,6 +967,20 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
{ LLM_TENSOR_ROUTER_FC1, "blk.%d.ffn_router_fc1" },
{ LLM_TENSOR_ROUTER_FC2, "blk.%d.ffn_router_fc2" },
{ LLM_TENSOR_ROUTER_OUT, "blk.%d.ffn_router_out" },
{ LLM_TENSOR_SSM_B, "blk.%d.ssm_b" },
{ LLM_TENSOR_SSM_C, "blk.%d.ssm_c" },
{ LLM_TENSOR_SSM_MIMO_X, "blk.%d.ssm_mimo_x" },
{ LLM_TENSOR_SSM_MIMO_Z, "blk.%d.ssm_mimo_z" },
{ LLM_TENSOR_SSM_MIMO_OUT, "blk.%d.ssm_mimo_out" },
{ LLM_TENSOR_ATTN_TPA_K_A, "blk.%d.attn_tpa_k_a" },
{ LLM_TENSOR_ATTN_TPA_K_B, "blk.%d.attn_tpa_k_b" },
{ LLM_TENSOR_ATTN_TPA_V_A, "blk.%d.attn_tpa_v_a" },
{ LLM_TENSOR_ATTN_TPA_V_B, "blk.%d.attn_tpa_v_b" },
{ LLM_TENSOR_ATTN_SHIFT_K, "blk.%d.attn_shift_k" },
{ LLM_TENSOR_ATTN_SHIFT_V, "blk.%d.attn_shift_v" },
{ LLM_TENSOR_ATTN_DIFF_LAMBDA, "blk.%d.attn_diff_lambda" },
{ LLM_TENSOR_ATTN_GEO, "blk.%d.attn_geo" },
{ LLM_TENSOR_FFN_GEO, "blk.%d.ffn_geo" },
{ LLM_TENSOR_ATTN_V_GATE, "blk.%d.attn_v_gate" },
{ LLM_TENSOR_ATTN_V_EXPS, "blk.%d.attn_v_exps" },
{ LLM_TENSOR_OUTPUT_LEXICAL, "output" },
@@ -1409,6 +1424,21 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
{LLM_TENSOR_ROUTER_FC2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ROUTER_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
{LLM_TENSOR_SSM_C, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
{LLM_TENSOR_SSM_MIMO_X, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_SSM_MIMO_Z, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_SSM_MIMO_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_ATTN_TPA_K_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_TPA_K_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_TPA_V_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_TPA_V_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_SHIFT_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_SHIFT_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_DIFF_LAMBDA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_GEO, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_FFN_GEO, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_ATTN_V_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_V_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
{LLM_TENSOR_OUTPUT_LEXICAL, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}},
@@ -1499,6 +1529,7 @@ bool llm_arch_is_hybrid(const llm_arch & arch) {
case LLM_ARCH_LFM2MOE:
case LLM_ARCH_LFM3:
case LLM_ARCH_ZAYA1:
case LLM_ARCH_OLALA:
case LLM_ARCH_NEMOTRON_H:
case LLM_ARCH_NEMOTRON_H_MOE:
case LLM_ARCH_METIS16:
@@ -1584,9 +1615,9 @@ 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_OLALA:
case LLM_ARCH_GROK:
case LLM_ARCH_MPT:
case LLM_ARCH_BLOOM: // ALiBi
@@ -1654,9 +1685,9 @@ 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_CLEF_OMNI:
case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load
case LLM_ARCH_VLLM_DECISION2:
return false;
+17 -2
View File
@@ -48,7 +48,6 @@ enum llm_arch {
LLM_ARCH_QWEN35,
LLM_ARCH_QWEN35MOE,
LLM_ARCH_CLEF,
LLM_ARCH_CLEF_OMNI,
LLM_ARCH_VLLM_DECISION2,
LLM_ARCH_CLOVER_MOE,
LLM_ARCH_QWEN4EXP,
@@ -147,6 +146,7 @@ enum llm_arch {
LLM_ARCH_LFM2MOE,
LLM_ARCH_LFM3,
LLM_ARCH_ZAYA1,
LLM_ARCH_OLALA,
LLM_ARCH_DREAM,
LLM_ARCH_SMALLTHINKER,
LLM_ARCH_LLADA,
@@ -228,7 +228,6 @@ 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,
@@ -325,6 +324,7 @@ enum llm_kv {
LLM_KV_ATTENTION_CAUSAL,
LLM_KV_ATTENTION_Q_LORA_RANK,
LLM_KV_ATTENTION_KV_LORA_RANK,
LLM_KV_ATTENTION_TPA_RANK,
LLM_KV_ATTENTION_DECAY_LORA_RANK,
LLM_KV_ATTENTION_ICLR_LORA_RANK,
LLM_KV_ATTENTION_VALUE_RESIDUAL_MIX_LORA_RANK,
@@ -428,6 +428,7 @@ enum llm_kv {
LLM_KV_SSM_STATE_SIZE,
LLM_KV_SSM_TIME_STEP_RANK,
LLM_KV_SSM_GROUP_COUNT,
LLM_KV_SSM_MIMO_RANK,
LLM_KV_SSM_DT_B_C_RMS,
LLM_KV_SSM_NORM_EPS,
@@ -969,6 +970,20 @@ enum llm_tensor {
LLM_TENSOR_ROUTER_FC1,
LLM_TENSOR_ROUTER_FC2,
LLM_TENSOR_ROUTER_OUT,
LLM_TENSOR_SSM_B,
LLM_TENSOR_SSM_C,
LLM_TENSOR_SSM_MIMO_X,
LLM_TENSOR_SSM_MIMO_Z,
LLM_TENSOR_SSM_MIMO_OUT,
LLM_TENSOR_ATTN_TPA_K_A,
LLM_TENSOR_ATTN_TPA_K_B,
LLM_TENSOR_ATTN_TPA_V_A,
LLM_TENSOR_ATTN_TPA_V_B,
LLM_TENSOR_ATTN_SHIFT_K,
LLM_TENSOR_ATTN_SHIFT_V,
LLM_TENSOR_ATTN_DIFF_LAMBDA,
LLM_TENSOR_ATTN_GEO,
LLM_TENSOR_FFN_GEO,
LLM_TENSOR_ATTN_V_GATE,
LLM_TENSOR_ATTN_V_EXPS,
LLM_TENSOR_OUTPUT_LEXICAL, // Clef: Maps to the same tensor as LLM_TENSOR_OUTPUT but uses GET_ROWS operation
-3
View File
@@ -529,9 +529,6 @@ 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);
+5
View File
@@ -226,6 +226,11 @@ uint32_t llama_hparams::n_embd_r() const {
return 2 * (ssm_d_conv - 1) * n_cca_qk;
}
if (ssm_mimo_rank != 0) {
// for Mamba-3 MIMO layers: the cumulative rotary angles, then the B and x of the previous token
return ssm_dt_rank * n_rot() / 2 + ssm_mimo_rank * ssm_dt_rank * ssm_d_state + ssm_d_inner;
}
if (n_embd_head_kda != 0) {
// for Kimi KDA layers
// Conv state for Q, K, V: 3 * (d_conv - 1) * n_head * head_dim
+2 -3
View File
@@ -121,6 +121,7 @@ struct llama_hparams {
uint32_t n_layer_dense_lead = 0;
uint32_t n_lora_q = 0;
uint32_t n_lora_kv = 0;
uint32_t n_tpa_rank = 0; // tensor product attention: rank of the K/V factors
uint32_t n_ff_shexp = 0;
uint32_t n_ff_chexp = 0;
uint32_t n_expert_shared = 0;
@@ -213,6 +214,7 @@ struct llama_hparams {
uint32_t ssm_d_state = 0;
uint32_t ssm_dt_rank = 0;
uint32_t ssm_n_group = 0;
uint32_t ssm_mimo_rank = 0; // Mamba-3 MIMO rank, 0 for the other SSMs
float ssm_norm_eps = 0.0f; // 0 = use f_norm_rms_eps
// for MiniMax-Text-01 linear attention
@@ -300,9 +302,6 @@ 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;
+6 -8
View File
@@ -188,9 +188,6 @@ 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) {
@@ -282,6 +279,7 @@ void llama_model_saver::add_kv_from_model() {
add_kv(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
add_kv(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
add_kv(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
add_kv(LLM_KV_ATTENTION_TPA_RANK, hparams.n_tpa_rank);
add_kv(LLM_KV_ATTENTION_DECAY_LORA_RANK, hparams.n_lora_decay);
add_kv(LLM_KV_ATTENTION_ICLR_LORA_RANK, hparams.n_lora_iclr);
add_kv(LLM_KV_ATTENTION_VALUE_RESIDUAL_MIX_LORA_RANK, hparams.n_lora_value_res_mix);
@@ -441,6 +439,7 @@ void llama_model_saver::add_kv_from_model() {
add_kv(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
add_kv(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
add_kv(LLM_KV_SSM_GROUP_COUNT, hparams.ssm_n_group);
add_kv(LLM_KV_SSM_MIMO_RANK, hparams.ssm_mimo_rank);
add_kv(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms);
add_kv(LLM_KV_SSM_NORM_EPS, hparams.ssm_norm_eps);
@@ -500,11 +499,10 @@ void llama_model_saver::add_kv_from_model() {
add_kv(LLM_KV_SHORTCONV_L_CACHE, hparams.n_shortconv_l_cache);
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_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);
add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, hparams.attn_res_block_size);
add_kv(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta);
+7 -5
View File
@@ -343,6 +343,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
return new llama_model_lfm3(params);
case LLM_ARCH_ZAYA1:
return new llama_model_zaya1(params);
case LLM_ARCH_OLALA:
return new llama_model_olala(params);
case LLM_ARCH_SMALLTHINKER:
return new llama_model_smallthinker(params);
case LLM_ARCH_GROVEMOE:
@@ -373,8 +375,6 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
return new llama_model_qwen35moe(params);
case LLM_ARCH_CLEF:
return new llama_model_clef(params);
case LLM_ARCH_CLEF_OMNI:
return new llama_model_clef_omni(params);
case LLM_ARCH_VLLM_DECISION2:
return new llama_model_vllm_decision2(params);
case LLM_ARCH_CLOVER_MOE:
@@ -1604,7 +1604,6 @@ 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);
@@ -3046,7 +3045,6 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
case LLM_ARCH_LLADA_MOE:
case LLM_ARCH_RND1:
case LLM_ARCH_CLEF:
case LLM_ARCH_CLEF_OMNI:
case LLM_ARCH_KOKORO:
case LLM_ARCH_TINY_VOCA:
{
@@ -3432,6 +3430,10 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
} else if (arch == LLM_ARCH_FALCON_H1 || arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP || arch == LLM_ARCH_ZAYA1) {
filter_attn = [&](uint32_t) { return true; };
filter_recr = [&](uint32_t) { return true; };
} else if (arch == LLM_ARCH_OLALA) {
// the attention layers keep the raw K/V of the previous token for the token shift
filter_attn = [&](uint32_t il) { return !hparams.is_recr(il); };
filter_recr = [&](uint32_t) { return true; };
} else if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) {
filter_attn = [&](uint32_t il) {
return !hparams.is_recr(il) && hparams.n_ff(il) == 0;
@@ -3798,6 +3800,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
case LLM_ARCH_RWKV7:
case LLM_ARCH_ARWKV7:
case LLM_ARCH_WAVTOKENIZER_DEC:
case LLM_ARCH_OLALA:
case LLM_ARCH_NEMOTRON_H:
case LLM_ARCH_NEMOTRON_H_MOE:
case LLM_ARCH_METIS16:
@@ -3980,7 +3983,6 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
case LLM_ARCH_QWEN35:
case LLM_ARCH_QWEN35MOE:
case LLM_ARCH_CLEF:
case LLM_ARCH_CLEF_OMNI:
case LLM_ARCH_QWEN4EXP:
case LLM_ARCH_QWEN3TTS:
return LLAMA_ROPE_TYPE_IMROPE;
+26
View File
@@ -244,6 +244,30 @@ struct llama_layer_zaya1 {
struct ggml_tensor * router_out = nullptr;
};
struct llama_layer_olala {
// Mamba-3 MIMO
struct ggml_tensor * ssm_b_b = nullptr;
struct ggml_tensor * ssm_c_b = nullptr;
struct ggml_tensor * ssm_mimo_x = nullptr;
struct ggml_tensor * ssm_mimo_z = nullptr;
struct ggml_tensor * ssm_mimo_out = nullptr;
// differential tensor product attention
struct ggml_tensor * tpa_k_a = nullptr;
struct ggml_tensor * tpa_k_b = nullptr;
struct ggml_tensor * tpa_v_a = nullptr;
struct ggml_tensor * tpa_v_b = nullptr;
struct ggml_tensor * shift_k = nullptr;
struct ggml_tensor * shift_v = nullptr;
struct ggml_tensor * diff_lambda = nullptr;
// geodesic residual updates
struct ggml_tensor * attn_geo = nullptr;
struct ggml_tensor * attn_geo_b = nullptr;
struct ggml_tensor * ffn_geo = nullptr;
struct ggml_tensor * ffn_geo_b = nullptr;
};
struct llama_layer_nextn {
struct ggml_tensor * eh_proj = nullptr;
struct ggml_tensor * embed_tokens = nullptr;
@@ -683,6 +707,8 @@ struct llama_layer {
struct llama_layer_zaya1 zaya1;
struct llama_layer_olala olala;
struct llama_layer_nextn nextn;
struct llama_layer_switch_lora switch_lora;
+12 -7
View File
@@ -340,6 +340,17 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param
quantize &= name.find(".loop_") == std::string::npos;
}
// olala: the Mamba-3 B/C biases and MIMO projections are elementwise, they stay F32
// the inputs of ssm_out, ffn_down_exps and ffn_latent_up overflow the F16 scales of the Q8 activation blocks, they stay BF16
if (arch == LLM_ARCH_OLALA) {
quantize &= name.find("ssm_b.") == std::string::npos;
quantize &= name.find("ssm_c.") == std::string::npos;
quantize &= name.find("ssm_mimo_") == std::string::npos;
quantize &= name.find("ssm_out") == std::string::npos;
quantize &= name.find("ffn_down_exps") == std::string::npos;
quantize &= name.find("ffn_latent_up") == std::string::npos;
}
// zaya1: the top-1 router and the grouped conv kernels stay F32
if (arch == LLM_ARCH_ZAYA1) {
quantize &= name.find("ffn_router_") == std::string::npos;
@@ -528,13 +539,7 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type
if (n_expert > 1) {
// Experts may not be consecutive and simply dividing i_ffn_down by n_expert does not work,
// so we need to parse the tensor name
if (sscanf(tname, "blk.%d.", &i_layer) != 1) {
// the blocks of a decision head use their own numbering, block N is treated like backbone layer N
if (sscanf(tname, "dec.blk.%d.", &i_layer) == 1) {
return std::make_pair(i_layer, n_layer);
}
throw std::runtime_error(format("Failed to determine layer for tensor %s", tname));
}
if (sscanf(tname, "blk.%d.", &i_layer) != 1) { throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); }
if (i_layer < 0 || i_layer >= n_layer) { throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, tname, n_layer)); }
}
+1 -19
View File
@@ -1,5 +1,4 @@
#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);
@@ -11,7 +10,6 @@ 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;
}
}
@@ -19,16 +17,11 @@ 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_out }, 0);
output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, 0);
for (int i = 0; i < n_layer; ++i) {
auto & layer = layers[i];
@@ -165,17 +158,6 @@ 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;
}
-96
View File
@@ -1,96 +0,0 @@
#include "models.h"
void llama_model_clef_omni::load_arch_hparams(llama_model_loader & ml) {
llama_model_qwen3vlmoe::load_arch_hparams(ml);
head.load_hparams(ml, hparams);
}
void llama_model_clef_omni::load_arch_tensors(llama_model_loader & ml) {
llama_model_qwen3vlmoe::load_arch_tensors(ml);
head.load_tensors(ml, *this);
}
std::unique_ptr<llm_graph_context> llama_model_clef_omni::build_arch_graph(const llm_graph_params & params) const {
return std::make_unique<graph>(params);
}
// the backbone is copied from llama_model_qwen3vlmoe::graph, without the memory module
// it also drops inp_out_ids (the head reads all tokens) and build_cvec(), as clef does
llama_model_clef_omni::graph::graph(const llm_graph_params & params) : llm_graph_context(params) {
const auto & model = static_cast<const llama_model_clef_omni &>(*params.model);
const int64_t n_embd_head = hparams.n_embd_head_v();
GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
GGML_ASSERT(n_embd_head == n_rot);
ggml_tensor * cur;
ggml_tensor * inpL;
inpL = build_inp_embd(model.tok_embd);
ggml_tensor * inp_pos = build_inp_pos();
auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this);
for (int il = 0; il < n_layer; ++il) {
ggml_tensor * inpSA = inpL;
cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);
cb(cur, "attn_norm", il);
auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il);
Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il);
cb(Qcur, "Qcur_normed", il);
Qcur = build_rope(Qcur, inp_pos, il);
Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il);
cb(Kcur, "Kcur_normed", il);
Kcur = build_rope(Kcur, inp_pos, il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
cb(ffn_inp, "ffn_inp", il);
cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il);
cb(cur, "ffn_norm", il);
cur = build_moe_ffn(cur,
model.layers[il].ffn_gate_inp,
model.layers[il].ffn_up_exps,
model.layers[il].ffn_gate_exps,
model.layers[il].ffn_down_exps,
nullptr,
n_expert, n_expert_used,
LLM_FFN_SILU, true,
hparams.expert_weights_scale,
LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
il);
cb(cur, "ffn_moe_out", il);
cur = ggml_add(ctx0, cur, ffn_inp);
cb(cur, "l_out", il);
if (il < (int) hparams.n_deepstack_layers) {
ggml_tensor * ds = ggml_view_2d(ctx0, res->t_inp_embd, n_embd, n_tokens, res->t_inp_embd->nb[1], (il + 1) * n_embd * sizeof(float));
cur = ggml_add(ctx0, cur, ds);
cb(cur, "deepstack_out", il);
}
inpL = cur;
}
cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1);
cb(cur, "result_norm", -1);
// the head is always evaluated, so that the graph has the same nodes for every batch
cur = model.head.build(*this, cur);
res->t_embd = cur;
}
+72 -92
View File
@@ -5,7 +5,9 @@
#include <algorithm>
#include <cmath>
void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hparams) {
void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
llama_model_qwen35::load_arch_hparams(ml);
ml.get_key(LLM_KV_DECISION_ROUTING_BLOCK_COUNT, n_layer_routing);
ml.get_key(LLM_KV_DECISION_BLOCK_COUNT, n_layer_joint);
ml.get_key(LLM_KV_DECISION_HEAD_COUNT, n_head_decision);
@@ -21,18 +23,10 @@ void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hpar
hparams.n_embd_out_impl = 1;
}
void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
llama_model_qwen35::load_arch_hparams(ml);
head.load_hparams(ml, hparams);
}
void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
llama_model_qwen35::load_arch_tensors(ml);
void llama_clef_head::load_tensors(llama_model_loader & ml, llama_model_base & model) {
const auto & tn = model.tn;
const int64_t n_embd = model.hparams.n_embd;
auto create_tensor = [&](const LLM_TN_IMPL & name, const std::initializer_list<int64_t> & ne, int flags) {
return model.create_tensor(ml, name, ne, flags);
};
LLAMA_LOAD_LOCALS;
const auto * w_memory = ml.get_weight(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight").str().c_str());
const auto * w_ffn = ml.get_weight(tn(LLM_TENSOR_DEC_FFN_UP, "weight", 0).str().c_str());
@@ -88,10 +82,10 @@ void llama_clef_head::load_tensors(llama_model_loader & ml, llama_model_base & m
load_norm(field_norm, LLM_TENSOR_DECISION_FIELD_NORM, n_embd_h);
load_norm(option_norm, LLM_TENSOR_DECISION_OPTION_NORM, n_embd_h);
output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, model.vocab.n_tokens()}, model.TENSOR_NOT_REQUIRED);
output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
if (output_lexical == nullptr) {
output_lexical = model.tok_embd;
output_lexical = tok_embd;
}
proj_memory = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight"), {n_embd, n_embd_h}, 0);
@@ -110,11 +104,6 @@ void llama_clef_head::load_tensors(llama_model_loader & ml, llama_model_base & m
scorer_out_b = create_tensor(tn(LLM_TENSOR_DECISION_SCORER_OUT, "bias"), {1}, 0);
}
void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
llama_model_qwen35::load_arch_tensors(ml);
head.load_tensors(ml, *this);
}
std::unique_ptr<llm_graph_context> llama_model_clef::build_arch_graph(const llm_graph_params & params) const {
return std::make_unique<graph>(params);
}
@@ -196,7 +185,7 @@ static size_t clef_n_questions(int64_t n_tokens) { return n_tokens / 2 + 1; }
static size_t clef_n_options (int64_t n_tokens) { return std::max<int64_t>(n_tokens - 1, 1); }
// pooling matrices and indices computed from the spans
class llama_clef_head::input_decision : public llm_graph_input_i {
class llama_model_clef::input_decision : public llm_graph_input_i {
public:
input_decision(const llama_ubatch & ubatch) :
n_tokens(ubatch.n_tokens), n_questions(clef_n_questions(n_tokens)), n_options(clef_n_options(n_tokens)) {}
@@ -288,7 +277,11 @@ llama_model_clef::graph::graph(const llm_graph_params & params) :
ggml_tensor * inp_pos = build_inp_pos();
auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this);
auto * inp_attn = build_attn_inp_causal();
auto inp_decision_ptr = std::make_unique<input_decision>(ubatch);
auto * inp_decision = inp_decision_ptr.get();
res->add_input(std::move(inp_decision_ptr));
for (int il = 0; il < n_layer; ++il) {
ggml_tensor * inpSA = inpL;
@@ -328,9 +321,16 @@ llama_model_clef::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
// the head is always evaluated, so that the graph has the same nodes for every batch
cur = model.head.build(*this, cur);
cur = build_head(cur, inp_decision);
// row i of the output is the score of option i
cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0);
cur = ggml_add(ctx0, cur, inp_decision->status);
cb(cur, "result_decision", -1);
res->t_embd = cur;
ggml_build_forward_expand(gf, cur);
}
// causal mask by batch order: the tokens of an image share the same position
@@ -361,16 +361,16 @@ public:
};
// same as build_attn_inp_no_cache(), with a causal mask even if the batch is processed by the encoder path
llm_graph_input_attn_no_cache * llama_clef_head::build_attn_inp_causal(const llm_graph_context & ctx) {
auto inp = std::make_unique<llm_graph_input_attn_clef>(ctx.hparams, ctx.cparams);
llm_graph_input_attn_no_cache * llama_model_clef::graph::build_attn_inp_causal() {
auto inp = std::make_unique<llm_graph_input_attn_clef>(hparams, cparams);
const auto type_mask = ctx.cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32;
const auto type_mask = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32;
inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx.ctx0, type_mask, GGML_PAD(ctx.n_tokens, 256), ctx.n_tokens, 1, 1);
inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx0, type_mask, GGML_PAD(n_tokens, 256), n_tokens, 1, 1);
ggml_set_input(inp->self_attn_mask.raw);
ctx.cb(inp->self_attn_mask.raw, "self_kq_mask", -1);
cb(inp->self_attn_mask.raw, "self_kq_mask", -1);
return (llm_graph_input_attn_no_cache *) ctx.res->add_input(std::move(inp));
return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp));
}
ggml_tensor * llama_model_clef::graph::build_layer_attn(
@@ -496,23 +496,21 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear(
return ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
}
ggml_tensor * llama_clef_head::build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const {
return ctx.build_norm(cur, n.w, n.b, LLM_NORM, -1);
ggml_tensor * llama_model_clef::graph::build_head_norm(ggml_tensor * cur, const norm & n) {
return build_norm(cur, n.w, n.b, LLM_NORM, -1);
}
// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null
ggml_tensor * llama_clef_head::build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) const {
ggml_context * ctx0 = ctx.ctx0;
ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) {
const int64_t n_embd_h = q->ne[0];
const int64_t n_head_h = n_head_decision;
const int64_t n_head_h = model.n_head_decision;
const int64_t d_head = n_embd_h / n_head_h;
const int64_t n_q = q->ne[1];
const int64_t n_kv = kv->ne[1];
ggml_tensor * Qcur = ggml_add(ctx0, ctx.build_lora_mm(a.wq, q), a.bq);
ggml_tensor * Kcur = ggml_add(ctx0, ctx.build_lora_mm(a.wk, kv), a.bk);
ggml_tensor * Vcur = ggml_add(ctx0, ctx.build_lora_mm(a.wv, kv), a.bv);
ggml_tensor * Qcur = ggml_add(ctx0, build_lora_mm(a.wq, q), a.bq);
ggml_tensor * Kcur = ggml_add(ctx0, build_lora_mm(a.wk, kv), a.bk);
ggml_tensor * Vcur = ggml_add(ctx0, build_lora_mm(a.wv, kv), a.bv);
Qcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Qcur, d_head, n_head_h, n_q), 0, 2, 1, 3); // [d_head, n_q, n_head]
Kcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Kcur, d_head, n_head_h, n_kv), 0, 2, 1, 3); // [d_head, n_kv, n_head]
@@ -525,29 +523,18 @@ ggml_tensor * llama_clef_head::build_head_attn(const llm_graph_context & ctx, gg
ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head]
cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q);
return ggml_add(ctx0, ctx.build_lora_mm(a.wo, cur), a.bo);
return ggml_add(ctx0, build_lora_mm(a.wo, cur), a.bo);
}
ggml_tensor * llama_clef_head::build_head_ffn(const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const {
ggml_context * ctx0 = ctx.ctx0;
cur = build_head_norm(ctx, cur, layer.ffn_norm);
cur = ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b);
ggml_tensor * llama_model_clef::graph::build_head_ffn(ggml_tensor * cur, const head_layer & layer) {
cur = build_head_norm(cur, layer.ffn_norm);
cur = ggml_add(ctx0, build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b);
cur = ggml_gelu_erf(ctx0, cur);
return ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b);
return ggml_add(ctx0, build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b);
}
// ref: JointSchemaHead in joint_schema_model.py of the model repo
ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor * hidden) const {
ggml_context * ctx0 = ctx.ctx0;
const int64_t n_embd = hidden->ne[0];
const int64_t n_tokens = hidden->ne[1];
auto inp_ptr = std::make_unique<input_decision>(ctx.ubatch);
auto * inp = inp_ptr.get();
ctx.res->add_input(std::move(inp_ptr));
ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_decision * inp) {
const int64_t n_questions = inp->n_questions;
const int64_t n_options = inp->n_options;
@@ -563,9 +550,9 @@ ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor
ggml_set_input(t);
}
hidden = build_head_norm(ctx, hidden, hidden_norm);
hidden = build_head_norm(hidden, model.hidden_norm);
ggml_tensor * memory = ctx.build_lora_mm(proj_memory, hidden); // [n_embd_h, n_tokens]
ggml_tensor * memory = build_lora_mm(model.proj_memory, hidden); // [n_embd_h, n_tokens]
const int64_t n_embd_h = memory->ne[0];
@@ -578,29 +565,29 @@ ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor
ggml_tensor * opt_ctx = ggml_mul_mat(ctx0, hidden_t, inp->pool_o); // [n_embd, n_options]
// mean of the output embeddings of the tokens of each option
ggml_tensor * lexical = ggml_get_rows(ctx0, output_lexical, inp->tokens);
ggml_tensor * lexical = ggml_get_rows(ctx0, model.output_lexical, inp->tokens);
lexical = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, lexical)), inp->pool_o); // [n_embd, n_options]
// one query per option
ggml_tensor * options = ctx.build_lora_mm(proj_option_context, opt_ctx);
options = ggml_add(ctx0, options, ctx.build_lora_mm(proj_option_lexical, lexical));
options = ggml_add(ctx0, options, ggml_get_rows(ctx0, ctx.build_lora_mm(proj_option_question, question), inp->option_question));
ggml_tensor * options = build_lora_mm(model.proj_option_context, opt_ctx);
options = ggml_add(ctx0, options, build_lora_mm(model.proj_option_lexical, lexical));
options = ggml_add(ctx0, options, ggml_get_rows(ctx0, build_lora_mm(model.proj_option_question, question), inp->option_question));
// the options read the prompt
for (uint32_t il = 0; il < n_layer_routing; ++il) {
const auto & layer = head_layers[il];
for (uint32_t il = 0; il < model.n_layer_routing; ++il) {
const auto & layer = model.head_layers[il];
ggml_tensor * cur = build_head_attn(ctx,
build_head_norm(ctx, options, layer.cross_norm),
build_head_norm(ctx, memory, layer.cross_norm_kv),
ggml_tensor * cur = build_head_attn(
build_head_norm(options, layer.cross_norm),
build_head_norm(memory, layer.cross_norm_kv),
layer.cross_attn);
options = ggml_add(ctx0, options, cur);
options = ggml_add(ctx0, options, build_head_ffn(ctx, options, layer));
options = ggml_add(ctx0, options, build_head_ffn(options, layer));
}
ctx.cb(options, "decision_options", -1);
cb(options, "decision_options", -1);
// one vector per question: its text, a summary of its options, the end of the prompt and its type
ggml_tensor * fields = ctx.build_lora_mm(proj_question, question); // [n_embd_h, n_questions]
ggml_tensor * fields = build_lora_mm(model.proj_question, question); // [n_embd_h, n_questions]
{
// each question weights its own options
ggml_tensor * weights = ggml_mul_mat(ctx0, options, fields); // [n_options, n_questions]
@@ -609,25 +596,25 @@ ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor
ggml_tensor * summary = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, options)), weights);
fields = ggml_add(ctx0, fields, build_head_norm(ctx, summary, option_summary_norm));
fields = ggml_add(ctx0, fields, ctx.build_lora_mm(proj_global, global));
fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, type_embd, inp->question_type));
fields = ggml_add(ctx0, fields, build_head_norm(summary, model.option_summary_norm));
fields = ggml_add(ctx0, fields, build_lora_mm(model.proj_global, global));
fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, model.type_embd, inp->question_type));
}
// the questions read each other and the prompt
for (uint32_t il = n_layer_routing; il < head_layers.size(); ++il) {
const auto & layer = head_layers[il];
for (uint32_t il = model.n_layer_routing; il < model.head_layers.size(); ++il) {
const auto & layer = model.head_layers[il];
ggml_tensor * cur = build_head_norm(ctx, fields, layer.self_norm);
fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, cur, layer.self_attn, inp->question_mask));
ggml_tensor * cur = build_head_norm(fields, layer.self_norm);
fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn, inp->question_mask));
cur = build_head_norm(ctx, fields, layer.cross_norm);
fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, memory, layer.cross_attn));
cur = build_head_norm(fields, layer.cross_norm);
fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn));
fields = ggml_add(ctx0, fields, build_head_ffn(ctx, fields, layer));
fields = ggml_add(ctx0, fields, build_head_ffn(fields, layer));
}
fields = build_head_norm(ctx, fields, field_norm);
ctx.cb(fields, "decision_fields", -1);
fields = build_head_norm(fields, model.field_norm);
cb(fields, "decision_fields", -1);
const float eps = 1e-12f;
@@ -637,7 +624,7 @@ ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor
ggml_tensor * prior = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, lexical, eps), anchor)); // [1, n_options]
// joint: each option against the vector of its question
options = build_head_norm(ctx, options, option_norm);
options = build_head_norm(options, model.option_norm);
ggml_tensor * field = ggml_get_rows(ctx0, fields, inp->option_question); // [n_embd_h, n_options]
ggml_tensor * cosine = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, field, eps), ggml_l2_norm(ctx0, options, eps)));
@@ -646,22 +633,15 @@ ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor
features = ggml_concat(ctx0, features, ggml_mul(ctx0, field, options), 0);
features = ggml_concat(ctx0, features, ggml_abs(ctx0, ggml_sub(ctx0, field, options)), 0);
ggml_tensor * residual = ggml_add(ctx0, ctx.build_lora_mm(scorer, features), scorer_b);
ggml_tensor * residual = ggml_add(ctx0, build_lora_mm(model.scorer, features), model.scorer_b);
residual = ggml_gelu_erf(ctx0, residual);
residual = ggml_add(ctx0, ctx.build_lora_mm(scorer_out, residual), scorer_out_b); // [1, n_options]
residual = ggml_add(ctx0, build_lora_mm(model.scorer_out, residual), model.scorer_out_b); // [1, n_options]
auto scale = [&](int i) {
return ggml_view_1d(ctx0, scales, 1, i * ggml_element_size(scales));
return ggml_view_1d(ctx0, model.scales, 1, i * ggml_element_size(model.scales));
};
ggml_tensor * joint = ggml_add(ctx0, ggml_mul(ctx0, cosine, scale(1)), residual);
ggml_tensor * cur = ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2)));
// row i of the output is the score of option i
cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0);
cur = ggml_add(ctx0, cur, inp->status);
ctx.cb(cur, "result_decision", -1);
return cur;
return ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2)));
}
+37 -45
View File
@@ -701,8 +701,6 @@ struct llama_model_qwen3vlmoe : public llama_model_base {
graph(const llm_graph_params & params);
};
// if false, the derived model does not use the LM head and builds its own output
virtual bool has_lm_head() const { return true; }
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
@@ -2805,6 +2803,26 @@ struct llama_model_zaya1 : public llama_model_base {
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
struct llama_model_olala : public llama_model_base {
llama_model_olala(const struct llama_model_params & params) : llama_model_base(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
void load_arch_tensors(llama_model_loader & ml) override;
// the Mamba-3 scan and the geodesic updates are built from many small ops
uint32_t graph_nodes_per_tensor() const override { return 32; }
struct graph : public llm_graph_context {
graph(const llama_model & model, const llm_graph_params & params);
ggml_tensor * build_mamba3_layer(const llama_model & model, ggml_tensor * cur, llm_graph_input_rs * inp, int il);
ggml_tensor * build_attn_layer(const llama_model & model, ggml_tensor * cur, ggml_tensor * ssmax_pos,
llm_graph_input_mem_hybrid * inp, int il);
ggml_tensor * build_geodesic(ggml_tensor * x, ggml_tensor * g, ggml_tensor * scale, ggml_tensor * bias, int il);
};
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
struct llama_model_smallthinker : public llama_model_base {
llama_model_smallthinker(const struct llama_model_params & params) : llama_model_base(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
@@ -3006,8 +3024,12 @@ struct llama_model_qwen35 : public llama_model_base {
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
// joint decision head of clef, on top of the final hidden states of a backbone evaluated without memory
struct llama_clef_head {
// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states
struct llama_model_clef : public llama_model_qwen35 {
llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
void load_arch_tensors(llama_model_loader & ml) override;
struct attn {
ggml_tensor * wq = nullptr;
ggml_tensor * bq = nullptr;
@@ -3056,7 +3078,6 @@ struct llama_clef_head {
ggml_tensor * proj_option_context = nullptr;
ggml_tensor * proj_option_lexical = nullptr;
ggml_tensor * scales = nullptr; // prior scale, joint scale, residual gate
ggml_tensor * type_embd = nullptr;
ggml_tensor * scorer = nullptr;
ggml_tensor * scorer_b = nullptr;
ggml_tensor * scorer_out = nullptr;
@@ -3065,33 +3086,11 @@ struct llama_clef_head {
class input_decision;
void load_hparams(llama_model_loader & ml, llama_hparams & hparams);
void load_tensors(llama_model_loader & ml, llama_model_base & model);
// causal mask by batch order, for the attention layers of the backbone
static llm_graph_input_attn_no_cache * build_attn_inp_causal(const llm_graph_context & ctx);
// hidden: [n_embd, n_tokens]
// returns [1, n_tokens], row i is the score of option i
ggml_tensor * build(const llm_graph_context & ctx, ggml_tensor * hidden) const;
private:
ggml_tensor * build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const;
ggml_tensor * build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr) const;
ggml_tensor * build_head_ffn (const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const;
};
// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states
struct llama_model_clef : public llama_model_qwen35 {
llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
void load_arch_tensors(llama_model_loader & ml) override;
llama_clef_head head;
struct graph : public llm_build_delta_net_base {
graph(const llm_graph_params & params);
private:
llm_graph_input_attn_no_cache * build_attn_inp_causal();
ggml_tensor * build_layer_attn(
llm_graph_input_attn_no_cache * inp_attn,
ggml_tensor * cur,
@@ -3102,6 +3101,15 @@ struct llama_model_clef : public llama_model_qwen35 {
ggml_tensor * cur,
int il);
// hidden: [n_embd, n_tokens], returns one score per option: [1, n_options]
ggml_tensor * build_head(
ggml_tensor * hidden,
input_decision * inp);
ggml_tensor * build_head_norm(ggml_tensor * cur, const norm & n);
ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr);
ggml_tensor * build_head_ffn (ggml_tensor * cur, const head_layer & layer);
const llama_model_clef & model;
};
@@ -3109,22 +3117,6 @@ struct llama_model_clef : public llama_model_qwen35 {
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
// Qwen3-Omni thinker (Qwen3 MoE) backbone evaluated without memory, with the clef decision head
struct llama_model_clef_omni : public llama_model_qwen3vlmoe {
llama_model_clef_omni(const struct llama_model_params & params) : llama_model_qwen3vlmoe(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
void load_arch_tensors(llama_model_loader & ml) override;
llama_clef_head head;
struct graph : public llm_graph_context {
graph(const llm_graph_params & params);
};
bool has_lm_head() const override { return false; }
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
struct llama_model_qwen4exp : public llama_model_base {
llama_model_qwen4exp(const struct llama_model_params & params) : llama_model_base(params) {}
+607
View File
@@ -0,0 +1,607 @@
#include "models.h"
#include "llama-memory-recurrent.h"
#include <cmath>
static constexpr float OLALA_PI = 3.14159265358979323846f;
// Mamba-3 keeps the decay rate away from zero
static constexpr float OLALA_A_FLOOR = 1e-4f;
// the geodesic residual update rotates the stream by at most this angle
static constexpr float OLALA_GEO_MAX_ANGLE = OLALA_PI / 4.0f;
// tokens per chunk of the Mamba-3 scan
static constexpr int64_t OLALA_CHUNK = 64;
void llama_model_olala::load_arch_hparams(llama_model_loader & ml) {
ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping);
ml.get_key(LLM_KV_ATTENTION_SCALE, hparams.f_attention_scale);
ml.get_key(LLM_KV_ATTENTION_TPA_RANK, hparams.n_tpa_rank);
ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
ml.get_key(LLM_KV_SSM_GROUP_COUNT, hparams.ssm_n_group);
ml.get_key(LLM_KV_SSM_MIMO_RANK, hparams.ssm_mimo_rank);
ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all, false);
ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp);
ml.get_key(LLM_KV_MOE_LATENT_SIZE, hparams.moe_latent_size);
ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm);
ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func);
hparams.attn_soft_cap = true;
// the scalable softmax and the token shift read log(pos + 1) from the attention temperature input
hparams.n_attn_temp_floor_scale = 1;
hparams.f_attn_temp_scale = 1.0f;
hparams.f_attn_temp_offset = 0.0f;
// the Mamba-3 layers have no kv head
for (uint32_t il = 0; il < hparams.n_layer(); ++il) {
hparams.is_recr_impl[il] = hparams.n_head_kv(il) == 0;
}
if (hparams.ssm_n_group != 1) {
throw std::runtime_error("olala: only ssm.group_count == 1 is supported");
}
// the attention layers keep the raw K and V of the previous token in the same recurrent row
for (uint32_t il = 0; il < hparams.n_layer(); ++il) {
if (!hparams.is_recr(il) && 2*hparams.n_embd_k_gqa(il) > hparams.n_embd_r()) {
throw std::runtime_error("olala: the token shift state does not fit in the recurrent row");
}
}
switch (hparams.n_layer()) {
case 36: type = LLM_TYPE_7B_A1B; break;
default: type = LLM_TYPE_UNKNOWN;
}
}
void llama_model_olala::load_arch_tensors(llama_model_loader &) {
LLAMA_LOAD_LOCALS;
const int64_t d_inner = hparams.ssm_d_inner;
const int64_t d_state = hparams.ssm_d_state;
const int64_t n_ssm_head = hparams.ssm_dt_rank;
const int64_t head_dim = d_inner / n_ssm_head;
const int64_t n_mimo = hparams.ssm_mimo_rank;
const int64_t n_angle = n_rot / 2;
// z, x, dt, A and trap per head, then B, C and the angles
const int64_t d_in_proj = 2*d_inner + 3*n_ssm_head + 2*n_mimo*d_state + n_angle;
const int64_t n_tpa = hparams.n_tpa_rank;
const int64_t n_embd_moe = hparams.moe_latent_size;
const int64_t n_ff_exp = hparams.n_ff_exp();
const int64_t n_ff_shexp = hparams.n_ff_shexp;
tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
for (int i = 0; i < n_layer; ++i) {
auto & layer = layers[i];
auto & o = layer.olala;
if (hparams.is_recr(i)) {
layer.ssm_in = create_tensor(tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, d_in_proj}, 0);
layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {n_ssm_head}, 0);
layer.ssm_b_norm = create_tensor(tn(LLM_TENSOR_SSM_B_NORM, "weight", i), {d_state}, 0);
layer.ssm_c_norm = create_tensor(tn(LLM_TENSOR_SSM_C_NORM, "weight", i), {d_state}, 0);
o.ssm_b_b = create_tensor(tn(LLM_TENSOR_SSM_B, "bias", i), {d_state, n_mimo, n_ssm_head}, 0);
o.ssm_c_b = create_tensor(tn(LLM_TENSOR_SSM_C, "bias", i), {d_state, n_mimo, n_ssm_head}, 0);
layer.ssm_d = create_tensor(tn(LLM_TENSOR_SSM_D, i), {n_ssm_head}, 0);
o.ssm_mimo_x = create_tensor(tn(LLM_TENSOR_SSM_MIMO_X, i), {head_dim, n_mimo, n_ssm_head}, 0);
o.ssm_mimo_z = create_tensor(tn(LLM_TENSOR_SSM_MIMO_Z, i), {head_dim, n_mimo, n_ssm_head}, 0);
o.ssm_mimo_out = create_tensor(tn(LLM_TENSOR_SSM_MIMO_OUT, i), {head_dim, n_mimo, n_ssm_head}, 0);
layer.ssm_out = create_tensor(tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd}, 0);
} else {
const int64_t n_head_kv_l = hparams.n_head_kv(i);
const int64_t n_signal = n_head - n_head_kv_l;
layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, 0);
layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, 0);
o.tpa_k_a = create_tensor(tn(LLM_TENSOR_ATTN_TPA_K_A, "weight", i), {n_embd, n_tpa * n_head_kv_l}, 0);
o.tpa_k_b = create_tensor(tn(LLM_TENSOR_ATTN_TPA_K_B, "weight", i), {n_embd, n_tpa * n_embd_head_k}, 0);
o.tpa_v_a = create_tensor(tn(LLM_TENSOR_ATTN_TPA_V_A, "weight", i), {n_embd, n_tpa * n_head_kv_l}, 0);
o.tpa_v_b = create_tensor(tn(LLM_TENSOR_ATTN_TPA_V_B, "weight", i), {n_embd, n_tpa * n_embd_head_v}, 0);
o.shift_k = create_tensor(tn(LLM_TENSOR_ATTN_SHIFT_K, "weight", i), {n_embd, n_head_kv_l}, 0);
o.shift_v = create_tensor(tn(LLM_TENSOR_ATTN_SHIFT_V, "weight", i), {n_embd, n_head_kv_l}, 0);
layer.attn_ssmax_s = create_tensor(tn(LLM_TENSOR_ATTN_SSMAX, "weight", i), {n_head}, 0);
o.diff_lambda = create_tensor(tn(LLM_TENSOR_ATTN_DIFF_LAMBDA, "weight", i), {n_embd, n_head_kv_l}, 0);
layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_embd_head_v * n_signal}, 0);
layer.wqkv_gate_b = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "bias", i), {n_embd_head_v * n_signal}, 0);
layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_v * n_signal, n_embd}, 0);
}
o.attn_geo = create_tensor(tn(LLM_TENSOR_ATTN_GEO, "weight", i), {1}, 0);
o.attn_geo_b = create_tensor(tn(LLM_TENSOR_ATTN_GEO, "bias", i), {1}, 0);
o.ffn_geo = create_tensor(tn(LLM_TENSOR_FFN_GEO, "weight", i), {1}, 0);
o.ffn_geo_b = create_tensor(tn(LLM_TENSOR_FFN_GEO, "bias", i), {1}, 0);
// the router reads the full stream, the experts run in the latent space
layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0);
layer.ffn_latent_down = create_tensor(tn(LLM_TENSOR_FFN_LATENT_DOWN, "weight", i), {n_embd, n_embd_moe}, 0);
layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd_moe, n_ff_exp, n_expert}, 0);
layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd_moe, n_expert}, 0);
layer.ffn_latent_up = create_tensor(tn(LLM_TENSOR_FFN_LATENT_UP, "weight", i), {n_embd_moe, n_embd}, 0);
layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0);
layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0);
}
}
std::unique_ptr<llm_graph_context> llama_model_olala::build_arch_graph(const llm_graph_params & params) const {
return std::make_unique<graph>(*this, params);
}
// rotates x towards g on the sphere of radius |x|
ggml_tensor * llama_model_olala::graph::build_geodesic(ggml_tensor * x, ggml_tensor * g, ggml_tensor * scale, ggml_tensor * bias, int il) {
ggml_tensor * xx = ggml_sum_rows(ctx0, ggml_sqr(ctx0, x));
ggml_tensor * xg = ggml_sum_rows(ctx0, ggml_mul(ctx0, x, g));
ggml_tensor * tangent = ggml_sub(ctx0, g, ggml_mul(ctx0, x, ggml_div(ctx0, xg, ggml_clamp(ctx0, xx, 1e-12f, INFINITY))));
ggml_tensor * t_norm = ggml_clamp(ctx0, ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, tangent))), 1e-8f, INFINITY);
ggml_tensor * r = ggml_clamp(ctx0, ggml_sqrt(ctx0, xx), 1e-6f, INFINITY);
ggml_tensor * theta = ggml_clamp(ctx0, ggml_div(ctx0, t_norm, r), -INFINITY, OLALA_GEO_MAX_ANGLE);
theta = ggml_add(ctx0, ggml_mul(ctx0, theta, scale), bias);
theta = ggml_clamp(ctx0, theta, -INFINITY, OLALA_GEO_MAX_ANGLE);
cb(theta, "geo_theta", il);
ggml_tensor * step = ggml_div(ctx0, ggml_mul(ctx0, r, ggml_sin(ctx0, theta)), t_norm);
return ggml_add(ctx0, ggml_mul(ctx0, x, ggml_cos(ctx0, theta)), ggml_mul(ctx0, tangent, step));
}
ggml_tensor * llama_model_olala::graph::build_mamba3_layer(const llama_model & model, ggml_tensor * cur, llm_graph_input_rs * inp, int il) {
const auto & layer = model.layers[il];
const auto & o = layer.olala;
const auto * mctx_cur = inp->mctx;
const uint32_t kv_head = mctx_cur->get_head();
const int64_t d_inner = hparams.ssm_d_inner;
const int64_t d_state = hparams.ssm_d_state;
const int64_t n_head = hparams.ssm_dt_rank;
const int64_t head_dim = d_inner / n_head;
const int64_t n_mimo = hparams.ssm_mimo_rank;
const int64_t n_angle = hparams.n_rot() / 2;
const int64_t n_inp_h = 2*head_dim + 3;
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
const int64_t n_seqs = ubatch.n_seqs;
GGML_ASSERT(n_seqs != 0);
GGML_ASSERT(ubatch.equal_seqs());
GGML_ASSERT(ubatch.n_tokens == n_seq_tokens * n_seqs);
// heads and sequences share one dim, heads first
const int64_t n_hs = n_head * n_seqs;
// recurrent row: the cumulative angles, then the B and x of the previous token
ggml_tensor * r_all = mctx_cur->get_r_l(il);
ggml_tensor * s_all = mctx_cur->get_s_l(il);
ggml_tensor * r_rs = build_rs(inp, r_all, hparams.n_embd_r(), n_seqs);
ggml_tensor * s_rs = build_rs(inp, s_all, hparams.n_embd_s(), n_seqs);
const size_t es_r = ggml_element_size(r_all);
const size_t off_k = n_angle*n_head*es_r;
const size_t off_x = off_k + n_mimo*n_head*d_state*es_r;
ggml_tensor * angle_state = ggml_cont(ctx0, ggml_view_2d(ctx0, r_rs, n_angle*n_head, n_seqs, r_rs->nb[1], 0));
ggml_tensor * k_state = ggml_cont(ctx0, ggml_view_2d(ctx0, r_rs, n_mimo*n_head*d_state, n_seqs, r_rs->nb[1], off_k));
ggml_tensor * x_state = ggml_cont(ctx0, ggml_view_2d(ctx0, r_rs, head_dim*n_head, n_seqs, r_rs->nb[1], off_x));
angle_state = ggml_reshape_3d(ctx0, angle_state, 1, n_angle, n_hs);
k_state = ggml_reshape_4d(ctx0, k_state, d_state, n_mimo, 1, n_hs);
x_state = ggml_reshape_3d(ctx0, x_state, head_dim, 1, n_hs);
ggml_tensor * ssm_state = ggml_reshape_3d(ctx0, s_rs, d_state, head_dim, n_hs);
ggml_tensor * zxbc = build_lora_mm(layer.ssm_in, cur);
cb(zxbc, "ssm_in", il);
zxbc = ggml_reshape_3d(ctx0, zxbc, zxbc->ne[0], n_seq_tokens, n_seqs);
const size_t es = ggml_element_size(zxbc);
// per head inputs, {ne0, n_seq_tokens, n_hs}
auto head_input = [&](int64_t ne0, int64_t off) {
ggml_tensor * t = ggml_view_4d(ctx0, zxbc, ne0, n_head, n_seq_tokens, n_seqs, n_inp_h*es, zxbc->nb[1], zxbc->nb[2], off*es);
t = ggml_cont(ctx0, ggml_permute(ctx0, t, 0, 2, 1, 3));
return ggml_reshape_3d(ctx0, t, ne0, n_seq_tokens, n_hs);
};
ggml_tensor * z = head_input(head_dim, 0);
ggml_tensor * x = head_input(head_dim, head_dim);
ggml_tensor * dt = head_input(1, 2*head_dim);
ggml_tensor * a = head_input(1, 2*head_dim + 1);
ggml_tensor * trap = head_input(1, 2*head_dim + 2);
dt = ggml_softplus(ctx0, ggml_add(ctx0, dt, ggml_reshape_3d(ctx0, layer.ssm_dt_b, 1, 1, n_head)));
a = ggml_clamp(ctx0, ggml_neg(ctx0, ggml_softplus(ctx0, a)), -INFINITY, -OLALA_A_FLOOR);
// log decay of the state, and the trapezoid weights of B_t x_t and B_{t-1} x_{t-1}
ggml_tensor * adt = ggml_mul(ctx0, a, dt);
ggml_tensor * gam = ggml_mul(ctx0, ggml_sigmoid(ctx0, trap), dt);
ggml_tensor * dlt = ggml_mul(ctx0, ggml_sub(ctx0, dt, gam), ggml_exp(ctx0, adt));
cb(adt, "ssm_adt", il);
const int64_t off_bc = n_head*n_inp_h;
// B and C are shared by the heads, {d_state, n_mimo, n_seq_tokens, n_hs} with a per head bias
auto build_bc = [&](int64_t off, ggml_tensor * norm, ggml_tensor * bias) {
ggml_tensor * t = ggml_view_4d(ctx0, zxbc, d_state, n_mimo, n_seq_tokens, n_seqs, d_state*es, zxbc->nb[1], zxbc->nb[2], off*es);
t = build_norm(ggml_cont(ctx0, t), norm, nullptr, LLM_NORM_RMS, il);
t = ggml_reshape_3d(ctx0, t, d_state*n_mimo*n_seq_tokens, 1, n_seqs);
t = ggml_repeat_4d(ctx0, t, t->ne[0], n_head, n_seqs, 1);
t = ggml_reshape_4d(ctx0, t, d_state, n_mimo, n_seq_tokens, n_hs);
return ggml_add(ctx0, t, ggml_reshape_4d(ctx0, bias, d_state, n_mimo, 1, n_head));
};
ggml_tensor * k = build_bc(off_bc, layer.ssm_b_norm, o.ssm_b_b);
ggml_tensor * q = build_bc(off_bc + n_mimo*d_state, layer.ssm_c_norm, o.ssm_c_b);
// data-dependent rotary angles, accumulated along the sequence, {n_seq_tokens, n_angle, n_hs}
ggml_tensor * angle = ggml_view_3d(ctx0, zxbc, n_angle, n_seq_tokens, n_seqs, zxbc->nb[1], zxbc->nb[2], (off_bc + 2*n_mimo*d_state)*es);
angle = ggml_tanh(ctx0, ggml_cont(ctx0, angle));
angle = ggml_reshape_3d(ctx0, angle, n_angle*n_seq_tokens, 1, n_seqs);
angle = ggml_repeat_4d(ctx0, angle, angle->ne[0], n_head, n_seqs, 1);
angle = ggml_reshape_3d(ctx0, angle, n_angle, n_seq_tokens, n_hs);
angle = ggml_mul(ctx0, angle, ggml_scale(ctx0, dt, OLALA_PI));
angle = ggml_cumsum(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, angle, 1, 0, 2, 3)));
angle = ggml_add(ctx0, angle, angle_state);
cb(angle, "ssm_angle", il);
ggml_tensor * angle_last = ggml_view_3d(ctx0, angle, 1, n_angle, n_hs, angle->nb[1], angle->nb[2], (n_seq_tokens - 1)*ggml_element_size(angle));
angle_last = ggml_cont(ctx0, angle_last);
angle_last = ggml_sub(ctx0, angle_last, ggml_scale(ctx0, ggml_floor(ctx0, ggml_scale(ctx0, angle_last, 0.5f/OLALA_PI)), 2.0f*OLALA_PI));
angle = ggml_cont(ctx0, ggml_permute(ctx0, angle, 1, 0, 2, 3));
ggml_tensor * cos_a = ggml_reshape_4d(ctx0, ggml_cos(ctx0, angle), n_angle, 1, n_seq_tokens, n_hs);
ggml_tensor * sin_a = ggml_reshape_4d(ctx0, ggml_sin(ctx0, angle), n_angle, 1, n_seq_tokens, n_hs);
// rotates the pairs (i, i + d_state/2) for i < n_angle
auto rotate = [&](ggml_tensor * t) {
const size_t off_hi = (d_state/2)*ggml_element_size(t);
ggml_tensor * t0 = ggml_view_4d(ctx0, t, n_angle, t->ne[1], t->ne[2], t->ne[3], t->nb[1], t->nb[2], t->nb[3], 0);
ggml_tensor * t1 = ggml_view_4d(ctx0, t, n_angle, t->ne[1], t->ne[2], t->ne[3], t->nb[1], t->nb[2], t->nb[3], off_hi);
ggml_tensor * r0 = ggml_sub(ctx0, ggml_mul(ctx0, t0, cos_a), ggml_mul(ctx0, t1, sin_a));
ggml_tensor * r1 = ggml_add(ctx0, ggml_mul(ctx0, t0, sin_a), ggml_mul(ctx0, t1, cos_a));
t = ggml_set(ctx0, t, r0, t->nb[1], t->nb[2], t->nb[3], 0);
return ggml_set_inplace(ctx0, t, r1, t->nb[1], t->nb[2], t->nb[3], off_hi);
};
k = rotate(k);
q = rotate(q);
cb(k, "ssm_k", il);
cb(q, "ssm_q", il);
// the MIMO ranks see x and z through per rank scales, {head_dim, n_mimo, n, n_hs}
auto expand_mimo = [&](ggml_tensor * t, ggml_tensor * w) {
t = ggml_reshape_4d(ctx0, t, head_dim, 1, t->ne[1], n_hs);
t = ggml_repeat_4d(ctx0, t, head_dim, n_mimo, t->ne[2], n_hs);
return ggml_mul(ctx0, t, ggml_reshape_4d(ctx0, w, head_dim, n_mimo, 1, n_head));
};
// B and x of the previous token, the state for the first one
ggml_tensor * k_prev = k_state;
ggml_tensor * x_prev = x_state;
if (n_seq_tokens > 1) {
k_prev = ggml_concat(ctx0, ggml_reshape_3d(ctx0, k_state, d_state*n_mimo, 1, n_hs),
ggml_view_3d(ctx0, k, d_state*n_mimo, n_seq_tokens - 1, n_hs, k->nb[2], k->nb[3], 0), 1);
x_prev = ggml_concat(ctx0, x_state, ggml_view_3d(ctx0, x, head_dim, n_seq_tokens - 1, n_hs, x->nb[1], x->nb[2], 0), 1);
}
ggml_tensor * v = expand_mimo(x, o.ssm_mimo_x);
ggml_tensor * v_prev = expand_mimo(x_prev, o.ssm_mimo_x);
// the trapezoid rule makes the state update a rank 2*n_mimo product, {ne0, 2*n_mimo, n_seq_tokens*n_hs}
const int64_t n_kx = 2*n_mimo;
ggml_tensor * gam4 = ggml_reshape_4d(ctx0, gam, 1, 1, n_seq_tokens, n_hs);
ggml_tensor * dlt4 = ggml_reshape_4d(ctx0, dlt, 1, 1, n_seq_tokens, n_hs);
ggml_tensor * kx = ggml_concat(ctx0,
ggml_reshape_3d(ctx0, k, d_state, n_mimo, n_seq_tokens*n_hs),
ggml_reshape_3d(ctx0, k_prev, d_state, n_mimo, n_seq_tokens*n_hs), 1);
ggml_tensor * vx = ggml_concat(ctx0,
ggml_reshape_3d(ctx0, ggml_mul(ctx0, v, gam4), head_dim, n_mimo, n_seq_tokens*n_hs),
ggml_reshape_3d(ctx0, ggml_mul(ctx0, v_prev, dlt4), head_dim, n_mimo, n_seq_tokens*n_hs), 1);
ggml_tensor * y;
ggml_tensor * state;
if (n_seq_tokens == 1) {
// one step: h = exp(adt) h + kx vx^T, y = h^T q
kx = ggml_cont(ctx0, ggml_transpose(ctx0, kx));
vx = ggml_cont(ctx0, ggml_transpose(ctx0, vx));
state = ggml_mul(ctx0, ssm_state, ggml_reshape_3d(ctx0, ggml_exp(ctx0, adt), 1, 1, n_hs));
state = ggml_add(ctx0, state, ggml_mul_mat(ctx0, kx, vx));
y = ggml_mul_mat(ctx0, state, ggml_reshape_3d(ctx0, q, d_state, n_mimo, n_hs));
y = ggml_reshape_4d(ctx0, y, head_dim, n_mimo, 1, n_hs);
} else {
// chunked scan, the zero padding leaves the state unchanged
const int64_t chunk = std::min(n_seq_tokens, OLALA_CHUNK);
const int64_t n_chunks = (n_seq_tokens + chunk - 1)/chunk;
const int64_t n_pad = n_chunks*chunk - n_seq_tokens;
const int64_t n_b = n_chunks*n_hs;
ggml_tensor * qc = q;
kx = ggml_reshape_4d(ctx0, kx, d_state, n_kx, n_seq_tokens, n_hs);
vx = ggml_reshape_4d(ctx0, vx, head_dim, n_kx, n_seq_tokens, n_hs);
if (n_pad > 0) {
qc = ggml_pad(ctx0, qc, 0, 0, n_pad, 0);
kx = ggml_pad(ctx0, kx, 0, 0, n_pad, 0);
vx = ggml_pad(ctx0, vx, 0, 0, n_pad, 0);
adt = ggml_pad(ctx0, adt, 0, n_pad, 0, 0);
}
qc = ggml_reshape_3d(ctx0, qc, d_state, n_mimo*chunk, n_b);
kx = ggml_reshape_3d(ctx0, kx, d_state, n_kx*chunk, n_b);
vx = ggml_reshape_4d(ctx0, vx, head_dim, n_kx, chunk, n_b);
vx = ggml_cont(ctx0, ggml_permute(ctx0, vx, 2, 0, 1, 3));
vx = ggml_reshape_3d(ctx0, vx, n_kx*chunk, head_dim, n_b);
// decay[s, t] = exp(cs_t - cs_s) for s <= t, from the cumulated log decays cs {n, nb}
auto build_decay = [&](ggml_tensor * cs) {
const int64_t n = cs->ne[0];
const int64_t nb = cs->ne[1];
ggml_tensor * decay = ggml_repeat_4d(ctx0, ggml_reshape_3d(ctx0, cs, 1, n, nb), n, n, nb, 1);
decay = ggml_sub(ctx0, decay, ggml_reshape_3d(ctx0, cs, n, 1, nb));
return ggml_tri(ctx0, ggml_exp(ctx0, ggml_tri(ctx0, decay, GGML_TRI_TYPE_LOWER_DIAG)), GGML_TRI_TYPE_LOWER_DIAG);
};
ggml_tensor * cs = ggml_cumsum(ctx0, ggml_reshape_2d(ctx0, adt, chunk, n_b));
ggml_tensor * decay = build_decay(cs);
// within the chunk
ggml_tensor * kq = ggml_mul_mat(ctx0, kx, qc);
kq = ggml_reshape_4d(ctx0, kq, n_kx, chunk, n_mimo, chunk*n_b);
kq = ggml_mul(ctx0, kq, ggml_reshape_4d(ctx0, decay, 1, chunk, 1, chunk*n_b));
kq = ggml_reshape_3d(ctx0, kq, n_kx*chunk, n_mimo*chunk, n_b);
y = ggml_mul_mat(ctx0, vx, kq);
// state that each chunk alone leaves at its end
ggml_tensor * cs_end = ggml_view_2d(ctx0, cs, 1, n_b, cs->nb[1], (chunk - 1)*ggml_element_size(cs));
ggml_tensor * to_end = ggml_exp(ctx0, ggml_neg(ctx0, ggml_sub(ctx0, cs, cs_end)));
ggml_tensor * kw = ggml_mul(ctx0, ggml_reshape_4d(ctx0, kx, d_state, n_kx, chunk, n_b), ggml_reshape_4d(ctx0, to_end, 1, 1, chunk, n_b));
kw = ggml_cont(ctx0, ggml_permute(ctx0, kw, 2, 0, 1, 3));
kw = ggml_reshape_3d(ctx0, kw, n_kx*chunk, d_state, n_b);
ggml_tensor * s_chunk = ggml_mul_mat(ctx0, kw, vx);
// the state at the start of each chunk and at the end, as the same decay product over the chunks:
// the initial state is a source with no decay, then each chunk alone with the decay up to its end
ggml_tensor * cs_chunk = ggml_cumsum(ctx0, ggml_reshape_2d(ctx0, ggml_cont(ctx0, cs_end), n_chunks, n_hs));
cs_chunk = ggml_concat(ctx0, ggml_scale(ctx0, ggml_view_2d(ctx0, cs_chunk, 1, n_hs, cs_chunk->nb[1], 0), 0.0f), cs_chunk, 0);
ggml_tensor * sources = ggml_concat(ctx0,
ggml_reshape_3d(ctx0, ssm_state, d_state*head_dim, 1, n_hs),
ggml_reshape_3d(ctx0, s_chunk, d_state*head_dim, n_chunks, n_hs), 1);
sources = ggml_cont(ctx0, ggml_transpose(ctx0, sources));
ggml_tensor * states = ggml_mul_mat(ctx0, sources, build_decay(cs_chunk));
state = ggml_view_3d(ctx0, states, d_state, head_dim, n_hs, ggml_row_size(states->type, d_state), states->nb[2], n_chunks*states->nb[1]);
states = ggml_cont(ctx0, ggml_view_3d(ctx0, states, d_state*head_dim, n_chunks, n_hs, states->nb[1], states->nb[2], 0));
// from the state at the chunk start
states = ggml_reshape_3d(ctx0, states, d_state, head_dim, n_b);
ggml_tensor * y_state = ggml_mul_mat(ctx0, states, qc);
y_state = ggml_mul(ctx0, ggml_reshape_4d(ctx0, y_state, head_dim, n_mimo, chunk, n_b), ggml_reshape_4d(ctx0, ggml_exp(ctx0, cs), 1, 1, chunk, n_b));
y = ggml_add(ctx0, ggml_reshape_4d(ctx0, y, head_dim, n_mimo, chunk, n_b), y_state);
y = ggml_reshape_4d(ctx0, y, head_dim, n_mimo, n_seq_tokens + n_pad, n_hs);
if (n_pad > 0) {
y = ggml_view_4d(ctx0, y, head_dim, n_mimo, n_seq_tokens, n_hs, y->nb[1], y->nb[2], y->nb[3], 0);
}
}
cb(state, "ssm_state", il);
// skip connection, gate and the sum over the ranks
y = ggml_add(ctx0, y, ggml_mul(ctx0, v, ggml_reshape_4d(ctx0, layer.ssm_d, 1, 1, 1, n_head)));
y = ggml_mul(ctx0, y, ggml_silu(ctx0, expand_mimo(z, o.ssm_mimo_z)));
y = ggml_mul(ctx0, y, ggml_reshape_4d(ctx0, o.ssm_mimo_out, head_dim, n_mimo, 1, n_head));
y = ggml_sum_rows(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, y, 1, 0, 2, 3)));
y = ggml_reshape_4d(ctx0, y, head_dim, n_seq_tokens, n_head, n_seqs);
y = ggml_cont(ctx0, ggml_permute(ctx0, y, 0, 2, 1, 3));
y = ggml_reshape_2d(ctx0, y, d_inner, n_seq_tokens*n_seqs);
cb(y, "ssm_y", il);
cur = build_lora_mm(layer.ssm_out, y);
cb(cur, "ssm_out", il);
// the states are read in place: store the new ones once the output is built
ggml_build_forward_expand(gf, cur);
ggml_tensor * k_last = ggml_view_4d(ctx0, k, d_state, n_mimo, 1, n_hs, k->nb[1], k->nb[2], k->nb[3], (n_seq_tokens - 1)*k->nb[2]);
ggml_tensor * x_last = ggml_view_3d(ctx0, x, head_dim, 1, n_hs, x->nb[1], x->nb[2], (n_seq_tokens - 1)*x->nb[1]);
auto store_r = [&](ggml_tensor * t, int64_t n, size_t off) {
t = ggml_reshape_2d(ctx0, ggml_cont(ctx0, t), n, n_seqs);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, t, ggml_view_2d(ctx0, r_all, n, n_seqs, r_all->nb[1], kv_head*r_all->nb[1] + off)));
};
store_r(angle_last, n_angle*n_head, 0);
store_r(k_last, n_mimo*n_head*d_state, off_k);
store_r(x_last, head_dim*n_head, off_x);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, state,
ggml_view_1d(ctx0, s_all, hparams.n_embd_s()*n_seqs, kv_head*s_all->nb[1])));
return cur;
}
ggml_tensor * llama_model_olala::graph::build_attn_layer(const llama_model & model, ggml_tensor * cur, ggml_tensor * ssmax_pos,
llm_graph_input_mem_hybrid * inp, int il) {
const auto & layer = model.layers[il];
const auto & o = layer.olala;
const auto * mctx_cur = inp->get_recr()->mctx;
const uint32_t kv_head = mctx_cur->get_head();
const int64_t n_embd_head = hparams.n_embd_head_k();
const int64_t n_head_kv = hparams.n_head_kv(il);
const int64_t n_embd_kv = n_embd_head*n_head_kv;
const int64_t n_tpa = hparams.n_tpa_rank;
// each kv group holds its signal heads, then one noise head
const int64_t n_group = n_head/n_head_kv;
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
const int64_t n_seqs = ubatch.n_seqs;
GGML_ASSERT(n_seqs != 0);
GGML_ASSERT(ubatch.equal_seqs());
GGML_ASSERT(ubatch.n_tokens == n_seq_tokens * n_seqs);
ggml_tensor * Qcur = build_lora_mm(layer.wq, cur);
Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
Qcur = build_norm(Qcur, layer.attn_q_norm, nullptr, LLM_NORM_RMS, il);
// scalable softmax: s * log(pos + 1) per head
ggml_tensor * ssmax = ggml_repeat_4d(ctx0, ssmax_pos, 1, n_head, n_tokens, 1);
ssmax = ggml_mul(ctx0, ssmax, ggml_reshape_3d(ctx0, layer.attn_ssmax_s, 1, n_head, 1));
Qcur = ggml_mul(ctx0, Qcur, ssmax);
cb(Qcur, "Qcur", il);
// tensor product K and V: per head factors times shared bases, {n_embd_head, n_head_kv, n_tokens}
auto build_tpa = [&](ggml_tensor * wa, ggml_tensor * wb) {
ggml_tensor * fa = ggml_reshape_3d(ctx0, build_lora_mm(wa, cur), n_tpa, n_head_kv, n_tokens);
ggml_tensor * fb = ggml_reshape_3d(ctx0, build_lora_mm(wb, cur), n_embd_head, n_tpa, n_tokens);
fb = ggml_cont(ctx0, ggml_transpose(ctx0, fb));
return ggml_mul_mat(ctx0, fb, fa);
};
ggml_tensor * k_raw = build_tpa(o.tpa_k_a, o.tpa_k_b);
ggml_tensor * v_raw = build_tpa(o.tpa_v_a, o.tpa_v_b);
cb(k_raw, "k_raw", il);
cb(v_raw, "v_raw", il);
// recurrent row: the raw K and V of the previous token
ggml_tensor * r_all = mctx_cur->get_r_l(il);
ggml_tensor * r_rs = build_rs(inp->get_recr(), r_all, hparams.n_embd_r(), n_seqs);
const size_t es_r = ggml_element_size(r_all);
// no shift on the first token of a sequence
ggml_tensor * not_first = ggml_step(ctx0, ssmax_pos);
// mixes in the previous token: t + alpha * (t_prev - t)
auto token_shift = [&](ggml_tensor * t, size_t off, ggml_tensor * w) {
t = ggml_reshape_4d(ctx0, t, n_embd_head, n_head_kv, n_seq_tokens, n_seqs);
ggml_tensor * prev = ggml_view_4d(ctx0, r_rs, n_embd_head, n_head_kv, 1, n_seqs, n_embd_head*es_r, n_embd_kv*es_r, r_rs->nb[1], off);
prev = ggml_cont(ctx0, prev);
if (n_seq_tokens > 1) {
prev = ggml_concat(ctx0, prev, ggml_view_4d(ctx0, t, n_embd_head, n_head_kv, n_seq_tokens - 1, n_seqs, t->nb[1], t->nb[2], t->nb[3], 0), 2);
}
ggml_tensor * alpha = ggml_sigmoid(ctx0, build_lora_mm(w, cur));
alpha = ggml_mul(ctx0, ggml_reshape_3d(ctx0, alpha, 1, n_head_kv, n_tokens), not_first);
alpha = ggml_reshape_4d(ctx0, alpha, 1, n_head_kv, n_seq_tokens, n_seqs);
t = ggml_add(ctx0, t, ggml_mul(ctx0, ggml_sub(ctx0, prev, t), alpha));
return ggml_reshape_3d(ctx0, t, n_embd_head, n_head_kv, n_tokens);
};
ggml_tensor * Kcur = token_shift(k_raw, 0, o.shift_k);
ggml_tensor * Vcur = token_shift(v_raw, n_embd_kv*es_r, o.shift_v);
Kcur = build_norm(Kcur, layer.attn_k_norm, nullptr, LLM_NORM_RMS, il);
cb(Kcur, "Kcur", il);
cb(Vcur, "Vcur", il);
ggml_tensor * attn = build_attn(inp->get_attn(),
nullptr, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, hparams.f_attention_scale, il);
// differential attention: signal heads minus the weighted noise head of their group
attn = ggml_reshape_4d(ctx0, attn, n_embd_head, n_group, n_head_kv, n_tokens);
ggml_tensor * sig = ggml_view_4d(ctx0, attn, n_embd_head, n_group - 1, n_head_kv, n_tokens, attn->nb[1], attn->nb[2], attn->nb[3], 0);
ggml_tensor * noi = ggml_view_4d(ctx0, attn, n_embd_head, 1, n_head_kv, n_tokens, attn->nb[1], attn->nb[2], attn->nb[3], (n_group - 1)*attn->nb[1]);
ggml_tensor * lambda = ggml_sigmoid(ctx0, build_lora_mm(o.diff_lambda, cur));
noi = ggml_mul(ctx0, noi, ggml_reshape_4d(ctx0, lambda, 1, 1, n_head_kv, n_tokens));
attn = ggml_sub(ctx0, sig, noi);
attn = ggml_reshape_2d(ctx0, attn, n_embd_head*(n_group - 1)*n_head_kv, n_tokens);
cb(attn, "attn_diff", il);
ggml_tensor * gate = ggml_add(ctx0, build_lora_mm(layer.wqkv_gate, cur), layer.wqkv_gate_b);
attn = ggml_mul(ctx0, attn, ggml_silu(ctx0, gate));
cur = build_lora_mm(layer.wo, attn);
cb(cur, "attn_out", il);
// the state is read in place: store the new one once the output is built
ggml_build_forward_expand(gf, cur);
auto store_last = [&](ggml_tensor * t, size_t off) {
t = ggml_reshape_4d(ctx0, t, n_embd_kv, n_seq_tokens, n_seqs, 1);
t = ggml_cont(ctx0, ggml_view_2d(ctx0, t, n_embd_kv, n_seqs, t->nb[2], (n_seq_tokens - 1)*t->nb[1]));
ggml_build_forward_expand(gf, ggml_cpy(ctx0, t, ggml_view_2d(ctx0, r_all, n_embd_kv, n_seqs, r_all->nb[1], kv_head*r_all->nb[1] + off)));
};
store_last(k_raw, 0);
store_last(v_raw, n_embd_kv*es_r);
return cur;
}
llama_model_olala::graph::graph(const llama_model & model, const llm_graph_params & params) :
llm_graph_context(params) {
// the residual stream lives on the unit sphere
ggml_tensor * inpL = build_inp_embd(model.tok_embd);
inpL = ggml_l2_norm(ctx0, inpL, 1e-12f);
cb(inpL, "inp_norm", -1);
auto * inp = build_inp_mem_hybrid();
// log(pos + 1), {1, 1, n_tokens}
ggml_tensor * ssmax_pos = ggml_scale_bias(ctx0, build_inp_attn_scale(), 1.0f, -1.0f);
cb(ssmax_pos, "ssmax_pos", -1);
ggml_tensor * inp_out_ids = build_inp_out_ids();
for (int il = 0; il < n_layer; ++il) {
const auto & layer = model.layers[il];
const auto & o = layer.olala;
res->t_layer_inp[il] = inpL;
ggml_tensor * cur = hparams.is_recr(il)
? build_mamba3_layer(model, inpL, inp->get_recr(), il)
: build_attn_layer(model, inpL, ssmax_pos, inp, il);
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
}
inpL = build_geodesic(inpL, cur, o.attn_geo, o.attn_geo_b, il);
cb(inpL, "attn_geo_out", il);
ggml_tensor * logits = build_lora_mm(layer.ffn_gate_inp, inpL);
cb(logits, "ffn_moe_logits", il);
ggml_tensor * latent = build_lora_mm(layer.ffn_latent_down, inpL);
cb(latent, "ffn_latent_down", il);
ggml_tensor * moe = build_moe_ffn(latent,
layer.ffn_gate_inp,
layer.ffn_up_exps,
nullptr,
layer.ffn_down_exps,
layer.ffn_exp_probs_b,
n_expert, n_expert_used,
LLM_FFN_RELU_SQR, hparams.expert_weights_norm,
hparams.expert_weights_scale,
(llama_expert_gating_func_type) hparams.expert_gating_func,
il,
logits);
moe = build_lora_mm(layer.ffn_latent_up, moe);
cb(moe, "ffn_moe_out", il);
ggml_tensor * shexp = build_ffn(inpL,
layer.ffn_up_shexp, nullptr,
nullptr, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr,
LLM_FFN_RELU_SQR, LLM_FFN_SEQ, il);
cb(shexp, "ffn_shexp", il);
cur = ggml_add(ctx0, moe, shexp);
cb(cur, "ffn_out", il);
inpL = build_geodesic(inpL, cur, o.ffn_geo, o.ffn_geo_b, il);
inpL = build_cvec(inpL, il);
cb(inpL, "l_out", il);
}
res->t_embd = inpL;
ggml_tensor * cur = build_lora_mm(model.output, inpL);
cb(cur, "result_output", -1);
res->t_logits = cur;
ggml_build_forward_expand(gf, cur);
}
+4 -8
View File
@@ -20,14 +20,10 @@ void llama_model_qwen3vlmoe::load_arch_tensors(llama_model_loader &) {
// output
output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
if (has_lm_head()) {
output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
// if output is NULL, init from the input tok embed
if (output == NULL) {
output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
}
output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
// if output is NULL, init from the input tok embed
if (output == NULL) {
output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
}
for (int i = 0; i < n_layer; ++i) {
+3 -1
View File
@@ -4,7 +4,6 @@ afmoe ,1 ,any ,MUL+ADD , 2
afmoe ,1 ,any ,RMS_NORM+MUL , 10
afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3
afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
apertus ,0 ,any ,RMS_NORM+MUL , 9
arcee ,0 ,any ,RMS_NORM+MUL , 5
arctic ,1 ,any ,MUL+ADD , 4
arctic ,1 ,any ,RMS_NORM+MUL , 7
@@ -281,6 +280,9 @@ nanbeige ,0 ,any ,RMS_NORM+MUL , 5
nemotron ,0 ,any ,NORM+MUL+ADD , 5
nemotron_h ,0 ,any ,RMS_NORM+MUL , 5
nemotron_h_moe ,0 ,any ,RMS_NORM+MUL , 5
olala ,1 ,any ,MUL+ADD , 6
olala ,1 ,any ,RMS_NORM+MUL , 6
olala ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV+SCALE, 3
olmo2 ,0 ,any ,RMS_NORM+MUL , 5
olmo2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
olmoe ,1 ,any ,MUL+ADD , 4
1 # test-fusion baseline for device MTL
4 afmoe ,1 ,any ,RMS_NORM+MUL , 10
5 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3
6 afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
apertus ,0 ,any ,RMS_NORM+MUL , 9
7 arcee ,0 ,any ,RMS_NORM+MUL , 5
8 arctic ,1 ,any ,MUL+ADD , 4
9 arctic ,1 ,any ,RMS_NORM+MUL , 7
280 nemotron ,0 ,any ,NORM+MUL+ADD , 5
281 nemotron_h ,0 ,any ,RMS_NORM+MUL , 5
282 nemotron_h_moe ,0 ,any ,RMS_NORM+MUL , 5
283 olala ,1 ,any ,MUL+ADD , 6
284 olala ,1 ,any ,RMS_NORM+MUL , 6
285 olala ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV+SCALE, 3
286 olmo2 ,0 ,any ,RMS_NORM+MUL , 5
287 olmo2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
288 olmoe ,1 ,any ,MUL+ADD , 4
+6 -25
View File
@@ -2160,10 +2160,9 @@ struct test_unary : public test_case {
const ggml_type type;
const std::array<int64_t, 4> ne_a;
int v; // view (1 : non-contiguous a)
bool inplace;
std::string vars() override {
return VARS_TO_STR4(type, ne_a, v, inplace);
return VARS_TO_STR3(type, ne_a, v);
}
double max_nmse_err(ggml_backend_t backend) override {
@@ -2178,14 +2177,13 @@ struct test_unary : public test_case {
test_unary(ggml_unary_op op,
ggml_type type = GGML_TYPE_F32,
std::array<int64_t, 4> ne_a = {128, 2, 2, 2},
int v = 0,
bool inplace = false)
: op(op), type(type), ne_a(ne_a), v(v), inplace(inplace) {}
int v = 0)
: op(op), type(type), ne_a(ne_a), v(v) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
const bool grad_supported = !inplace && (op == GGML_UNARY_OP_ABS || op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_NEG ||
const bool grad_supported = op == GGML_UNARY_OP_ABS || op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_NEG ||
op == GGML_UNARY_OP_STEP || op == GGML_UNARY_OP_RELU || op == GGML_UNARY_OP_SILU ||
op == GGML_UNARY_OP_EXPM1 || op == GGML_UNARY_OP_SOFTPLUS || op == GGML_UNARY_OP_SIGMOID || op == GGML_UNARY_OP_TANH);
op == GGML_UNARY_OP_EXPM1 || op == GGML_UNARY_OP_SOFTPLUS || op == GGML_UNARY_OP_SIGMOID || op == GGML_UNARY_OP_TANH;
ggml_tensor * a;
if (v & 1) {
@@ -2210,7 +2208,7 @@ struct test_unary : public test_case {
ggml_set_name(a, "a");
}
ggml_tensor * out = inplace ? ggml_unary_inplace(ctx, a, op) : ggml_unary(ctx, a, op);
ggml_tensor * out = ggml_unary(ctx, a, op);
ggml_set_name(out, "out");
return out;
@@ -12072,11 +12070,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
continue; // need extra params, separate test
}
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 128, 2, 2, 2 }, v));
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 128, 2, 2, 2 }, v, true));
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 5, 7, 11, 13 }, v));
if (v == 1) {
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 5, 7, 2, 2 }, v, true));
}
if (type == GGML_TYPE_F16) {
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 33, 2, 2, 2 }, v));
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 65, 2, 2, 2 }, v));
@@ -14810,8 +14804,6 @@ 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());
@@ -15080,8 +15072,6 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_flash_attn_ext_kv_rows( 64, 4, 2, 3000, 768, nb, n_slices, GGML_TYPE_Q8_0));
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(512, 2, 8, 4096, 1024, nb, n_slices));
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 8, 2, 4096, 1280, nb, n_slices));
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(512, 2, 8, 4096, 1024, nb, n_slices, GGML_TYPE_Q8_0));
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 8, 2, 8192, 1280, nb, n_slices, GGML_TYPE_Q8_0));
}
}
// decode: one token per slice, non-f16 K/V take the vec kernel
@@ -15240,9 +15230,6 @@ 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));
@@ -16067,8 +16054,6 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
test_cases.emplace_back(new test_flash_attn_ext(72, 72, 16, {1, 1}, 5776, 5776, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
// Same non-causal vision-encoder shape for the other head size padded in-kernel by the CUDA MMA kernels
test_cases.emplace_back(new test_flash_attn_ext(40, 40, 16, {1, 1}, 5776, 5776, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
// Same for the Qwen2.5-VL head size
test_cases.emplace_back(new test_flash_attn_ext(80, 80, 16, {1, 1}, 4096, 4096, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16));
// GCN sparse attention break-even for multiple query tokens.
for (int64_t kv : {16384, 32768, 65536}) {
@@ -16382,10 +16367,6 @@ 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,7 +2479,6 @@ 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,113 +6637,6 @@ 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>
{
@@ -7924,13 +7817,6 @@ 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)
@@ -8589,161 +8475,6 @@ 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");
+2 -14
View File
@@ -30,7 +30,6 @@ enum handcrafted_file_type {
HANDCRAFTED_KV_BAD_TYPE = 20 + offset_has_kv,
// HANDCRAFTED_KV_BAD_VALUE_SIZE = 30 + offset_has_kv, // removed because it can result in allocations > 1 TB (default sanitizer limit)
HANDCRAFTED_KV_DUPLICATE_KEY = 40 + offset_has_kv,
HANDCRAFTED_KV_NUL_KEY = 45 + offset_has_kv,
HANDCRAFTED_KV_BAD_ALIGN = 50 + offset_has_kv,
HANDCRAFTED_KV_WRONG_TYPE_ALIGN = 55 + offset_has_kv,
HANDCRAFTED_KV_SUCCESS = 800 + offset_has_kv,
@@ -45,7 +44,6 @@ enum handcrafted_file_type {
HANDCRAFTED_TENSORS_BAD_TYPE = 50 + offset_has_tensors,
HANDCRAFTED_TENSORS_BAD_OFFSET = 60 + offset_has_tensors,
HANDCRAFTED_TENSORS_DUPLICATE_NAME = 70 + offset_has_tensors,
HANDCRAFTED_TENSORS_NUL_NAME = 72 + offset_has_tensors,
HANDCRAFTED_TENSORS_BAD_ALIGN = 75 + offset_has_tensors,
HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN = 80 + offset_has_tensors,
HANDCRAFTED_TENSORS_SUCCESS = 800 + offset_has_tensors,
@@ -73,7 +71,6 @@ static std::string handcrafted_file_type_name(const enum handcrafted_file_type h
case HANDCRAFTED_KV_EMPTY_KEY: return "KV_EMPTY_KEY";
case HANDCRAFTED_KV_BAD_TYPE: return "KV_BAD_TYPE";
case HANDCRAFTED_KV_DUPLICATE_KEY: return "KV_DUPLICATE_KEY";
case HANDCRAFTED_KV_NUL_KEY: return "KV_NUL_KEY";
case HANDCRAFTED_KV_BAD_ALIGN: return "KV_BAD_ALIGN";
case HANDCRAFTED_KV_WRONG_TYPE_ALIGN: return "KV_WRONG_TYPE_ALIGN";
case HANDCRAFTED_KV_SUCCESS: return "KV_RANDOM_KV";
@@ -88,7 +85,6 @@ static std::string handcrafted_file_type_name(const enum handcrafted_file_type h
case HANDCRAFTED_TENSORS_BAD_TYPE: return "TENSORS_BAD_TYPE";
case HANDCRAFTED_TENSORS_BAD_OFFSET: return "TENSORS_BAD_OFFSET";
case HANDCRAFTED_TENSORS_DUPLICATE_NAME: return "TENSORS_DUPLICATE_NAME";
case HANDCRAFTED_TENSORS_NUL_NAME: return "TENSORS_NUL_NAME";
case HANDCRAFTED_TENSORS_BAD_ALIGN: return "TENSORS_BAD_ALIGN";
case HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN: return "TENSORS_INCONSISTENT_ALIGN";
case HANDCRAFTED_TENSORS_SUCCESS: return "TENSORS_SUCCESS";
@@ -306,12 +302,9 @@ static FILE * get_handcrafted_file(const unsigned int seed, const enum handcraft
const enum gguf_type type = gguf_type(hft == HANDCRAFTED_KV_BAD_TYPE ? GGUF_TYPE_COUNT : kv_types[i].first);
const enum gguf_type type_arr = gguf_type(hft == HANDCRAFTED_KV_BAD_TYPE ? GGUF_TYPE_COUNT : kv_types[i].second);
std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY
const std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY
? ""
: "my_key_" + std::to_string((hft == HANDCRAFTED_KV_DUPLICATE_KEY || hft == HANDCRAFTED_KV_NUL_KEY ? i/2 : i));
if (hft == HANDCRAFTED_KV_NUL_KEY && i % 2 == 0) {
key += std::string("\0x", 2);
}
: "my_key_" + std::to_string((hft == HANDCRAFTED_KV_DUPLICATE_KEY ? i/2 : i));
if (hft == HANDCRAFTED_KV_BAD_KEY_SIZE) {
const uint64_t n = -1;
@@ -408,9 +401,6 @@ static FILE * get_handcrafted_file(const unsigned int seed, const enum handcraft
const std::array<int64_t, GGML_MAX_DIMS> shape = tensor_configs[i].second;
std::string name = "my_tensor";
if (hft == HANDCRAFTED_TENSORS_NUL_NAME) {
name += '\0';
}
if (hft != HANDCRAFTED_TENSORS_DUPLICATE_NAME) {
name += "_" + std::to_string(i);
}
@@ -783,7 +773,6 @@ static std::pair<int, int> test_handcrafted_file(const unsigned int seed) {
HANDCRAFTED_KV_EMPTY_KEY,
HANDCRAFTED_KV_BAD_TYPE,
HANDCRAFTED_KV_DUPLICATE_KEY,
HANDCRAFTED_KV_NUL_KEY,
HANDCRAFTED_KV_BAD_ALIGN,
HANDCRAFTED_KV_WRONG_TYPE_ALIGN,
HANDCRAFTED_KV_SUCCESS,
@@ -798,7 +787,6 @@ static std::pair<int, int> test_handcrafted_file(const unsigned int seed) {
HANDCRAFTED_TENSORS_BAD_TYPE,
HANDCRAFTED_TENSORS_BAD_OFFSET,
HANDCRAFTED_TENSORS_DUPLICATE_NAME,
HANDCRAFTED_TENSORS_NUL_NAME,
HANDCRAFTED_TENSORS_BAD_ALIGN,
HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN,
HANDCRAFTED_TENSORS_SUCCESS,
-92
View File
@@ -389,19 +389,6 @@ 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) {
@@ -435,62 +422,6 @@ static void test_loops(testing & t) {
"22"
);
test_template(t, "for over string",
"{% for c in 'abc' %}{{ c }}{% endfor %}",
json::object(),
"abc"
);
test_template(t, "for over string with loop metadata",
"{% for c in 'abc' %}{{ loop.index }}{{ loop.length }}{% endfor %}",
json::object(),
"132333"
);
test_template(t, "for over empty string",
"{% for c in '' %}{{ c }}{% else %}empty{% endfor %}",
json::object(),
"empty"
);
test_template(t, "for over multipart string",
"{% for c in a + 'bc' %}{{ c }}{% endfor %}",
{{"a", "a"}},
"abc"
);
test_template(t, "for over string: loop.length and loop.last",
"{% for c in 'abcd' %}{{ loop.length }}{% if loop.last %}!{% endif %}{% endfor %}",
json::object(),
"4444!"
);
test_template(t, "for over string: loop.first and revindex",
"{% for c in 'abc' %}{{ loop.first }}{{ loop.revindex }}{% endfor %}",
json::object(),
"True3False2False1"
);
// string elements are bytes, not codepoints: 'é' is 2 bytes in UTF-8,
// while python iterates codepoints -- the divergence is expected here
test_template(t, "for over multibyte string iterates bytes",
"{% for c in 'é' %}{{ loop.length }}{% endfor %}",
json::object(),
g_python_mode ? "1" : "22"
);
test_template(t, "for over string: nested loops",
"{% for a in 'ab' %}{% for b in '12' %}{{ a }}{{ b }}{{ loop.index }}{% endfor %}{% endfor %}",
json::object(),
"a11a22b11b22"
);
test_template(t, "for over string with filter recomputes length",
"{% for c in 'abc' if c != 'b' %}{{ c }}{{ loop.length }}{% endfor %}",
json::object(),
"a2c2"
);
test_template(t, "for over dict items",
"{% for k, v in data.items() %}{{ k }}={{ v }} {% endfor %}",
{{"data", {{"x", 1}, {"y", 2}}}},
@@ -1018,29 +949,6 @@ static void test_filters(testing & t) {
);
}
test_template(t, "trim and strip unicode whitespace",
"[{{ s|trim }}]|[{{ s.strip() }}]|[{{ s.lstrip() }}]|[{{ s.rstrip() }}]",
{{"s", "\u3000\u00a0hello\u2003\u202f"}},
"[hello]|[hello]|[hello\u2003\u202f]|[\u3000\u00a0hello]"
);
test_template(t, "trim and strip multibyte custom chars",
"[{{ t|trim(c) }}]|[{{ t.strip(c) }}]|[{{ u|trim(c) }}]",
{{"t", "\u3001hi\u3002"}, {"u", "\u3000\u3001hi\u3000"}, {"c", "\u3000"}},
"[\u3001hi\u3002]|[\u3001hi\u3002]|[\u3001hi]"
);
test_template(t, "trim and strip with none",
"[{{ s|trim(none) }}]|[{{ s|trim(chars=none) }}]|[{{ s.strip(none) }}]|[{{ s.lstrip(none) }}]|[{{ s.rstrip(none) }}]",
{{"s", "\u3000hello\u00a0"}},
"[hello]|[hello]|[hello]|[hello\u00a0]|[\u3000hello]"
);
test_template_error(t, "strip rejects non-string non-none chars",
"{{ 'hello'.strip(123) }}",
"strip() argument must be None or str"
);
test_template(t, "length string",
"{{ 'hello'|length }}",
json::object(),
+19 -5
View File
@@ -326,6 +326,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
n_layer = 3;
} else if (arch == LLM_ARCH_METIS16) {
n_layer = 4; // 2 passes over 2 physical layers, one attention and one Mamba-2
} else if (arch == LLM_ARCH_OLALA) {
n_layer = 3; // Mamba-3, attention, Mamba-3
} else if (arch == LLM_ARCH_CHAMELEON) {
n_vocab = 10240;
} else if (arch == LLM_ARCH_QWEN3TTS) {
@@ -343,6 +345,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
uint32_t n_head_kv = n_head;
if (arch == LLM_ARCH_QWEN3) {
n_head_kv = 1; // MQA coverage
} else if (arch == LLM_ARCH_OLALA) {
n_head_kv = 1; // one signal head and one noise head, head size 128 for the softcapped flash attention
} else if (arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_AFMOE || arch == LLM_ARCH_MAION_CODER ||
arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_LIMITE || arch == LLM_ARCH_GEMMA4 || arch == LLM_ARCH_RICURSIVE ||
arch == LLM_ARCH_ZAYA1 || arch == LLM_ARCH_MINICPM5_MOE) {
@@ -416,12 +420,12 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
} else {
ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_per_layer);
}
} else if (arch == LLM_ARCH_METIS16) {
} else if (arch == LLM_ARCH_METIS16 || arch == LLM_ARCH_OLALA) {
// the layer types repeat in every pass
std::vector<uint32_t> n_head_kv_per_layer;
n_head_kv_per_layer.reserve(n_layer);
for (uint32_t il = 0; il < n_layer; il++) {
n_head_kv_per_layer.push_back(il % 2 == 0 ? n_head_kv : 0);
n_head_kv_per_layer.push_back(il % 2 == (arch == LLM_ARCH_OLALA ? 1 : 0) ? n_head_kv : 0);
}
ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head);
ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_kv_per_layer);
@@ -771,6 +775,16 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
ms.add_kv(LLM_KV_MOE_LATENT_SIZE, n_embd/2);
}
if (arch == LLM_ARCH_OLALA) {
ms.add_kv(LLM_KV_SSM_MIMO_RANK, uint32_t(2));
ms.add_kv(LLM_KV_ATTENTION_TPA_RANK, uint32_t(2));
ms.add_kv(LLM_KV_ATTN_LOGIT_SOFTCAPPING, 50.0f);
ms.add_kv(LLM_KV_ATTENTION_SCALE, 1.0f/128);
ms.add_kv(LLM_KV_MOE_LATENT_SIZE, n_embd/2);
ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 2.0f);
ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true);
}
if (arch == LLM_ARCH_LIMITE) {
ms.add_kv(LLM_KV_ATTENTION_SCALE, 0.1f);
ms.add_kv(LLM_KV_ATTENTION_XSA_EPS, 1e-4f);
@@ -902,7 +916,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
ms.add_kv(LLM_KV_SSM_CONV_KERNEL, uint32_t(arch == LLM_ARCH_ZAYA1 ? 2 : 4)); // ZAYA CCA convs have kernel 2
ms.add_kv(LLM_KV_SSM_STATE_SIZE, uint32_t(128));
ms.add_kv(LLM_KV_SSM_TIME_STEP_RANK, n_head);
ms.add_kv(LLM_KV_SSM_GROUP_COUNT, arch == LLM_ARCH_PLAMO2 ? 0 : uint32_t(2));
ms.add_kv(LLM_KV_SSM_GROUP_COUNT, arch == LLM_ARCH_PLAMO2 ? 0 : uint32_t(arch == LLM_ARCH_OLALA ? 1 : 2));
ms.add_kv(LLM_KV_KDA_HEAD_DIM, uint32_t(128));
ms.add_kv(LLM_KV_KDA_SAFE_GATE, true);
ms.add_kv(LLM_KV_KDA_GATE_LOWER_BOUND, -5.0f);
@@ -1176,6 +1190,7 @@ static bool moe_mandatory(const llm_arch arch) {
switch (arch) {
case LLM_ARCH_FLINT:
case LLM_ARCH_ZAYA1:
case LLM_ARCH_OLALA:
case LLM_ARCH_LLAMA4:
case LLM_ARCH_MAION_CODER:
case LLM_ARCH_COHERE2MOE:
@@ -1184,7 +1199,6 @@ static bool moe_mandatory(const llm_arch arch) {
case LLM_ARCH_QWEN3MOE:
case LLM_ARCH_QWEN3NEXT:
case LLM_ARCH_QWEN3VLMOE:
case LLM_ARCH_CLEF_OMNI:
case LLM_ARCH_QWEN35MOE:
case LLM_ARCH_CLOVER_MOE:
case LLM_ARCH_QWEN4EXP:
@@ -1298,7 +1312,7 @@ static bool arch_supported(const llm_arch arch) {
if (arch == LLM_ARCH_PLM) {
return false; // TODO tensor shapes
}
if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_CLEF_OMNI || arch == LLM_ARCH_VLLM_DECISION2) {
if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_VLLM_DECISION2) {
return false; // TODO decision head tensors
}
if (arch == LLM_ARCH_DEEPSEEK2OCR) {
-152
View File
@@ -3,7 +3,6 @@
#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"
@@ -541,36 +540,6 @@ 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
//
@@ -773,40 +742,6 @@ static void test_decision_ocr_jev_validation(testing & t) {
reject_state("two images, three given", files_of(3), "this model needs exactly 2 images");
}
// server_decision_context::parse_state: "images" and "audio" are aliases of "files"
//
static void test_decision_media_fields(testing & t) {
server_decision_context ctx;
ctx.type = COMMON_DECISION_TYPE_CLEF_OMNI;
// only base64-decoded, the media itself is not parsed here
const std::string image = "data:image/png;base64,AAAA";
const std::string audio = "data:audio/wav;base64,AQID";
std::vector<raw_buffer> files;
ctx.parse_state({{"state", "x"}, {"audio", json::array({audio})}}, files);
t.assert_equal("audio is read", (size_t) 1, files.size());
t.assert_true("audio content", files[0] == raw_buffer({1, 2, 3}));
files.clear();
ctx.parse_state({{"state", "x"}, {"files", json::array({image})}, {"images", json::array({image})}, {"audio", json::array({audio})}}, files);
t.assert_equal("all fields are read", (size_t) 3, files.size());
t.assert_true("audio after files and images", files[2] == raw_buffer({1, 2, 3}));
files.clear();
ctx.parse_state({{"state", "x"}, {"audio", nullptr}}, files);
t.assert_true("null audio", files.empty());
std::string error;
try {
ctx.parse_state({{"state", "x"}, {"audio", audio}}, files);
} catch (const std::invalid_argument & e) {
error = e.what();
}
t.assert_true("audio must be an array: " + error, error.find("\"audio\" must be an array") != std::string::npos);
}
// server_decision_context: the recursive functions stop at RECURSIVE_LIMIT
//
@@ -832,90 +767,6 @@ static void test_decision_depth(testing & t) {
});
}
//
// server_decision_context: the joint head reads media grouped by kind (images, then audio, then video)
//
static std::vector<uint8_t> make_wav_16khz(size_t n_samples) {
std::vector<uint8_t> b(44 + 2 * n_samples, 0);
const auto put32 = [&](size_t o, uint32_t v) { b[o] = v; b[o + 1] = v >> 8; b[o + 2] = v >> 16; b[o + 3] = v >> 24; };
const auto put16 = [&](size_t o, uint16_t v) { b[o] = v; b[o + 1] = v >> 8; };
memcpy(b.data(), "RIFF", 4);
put32(4, 36 + (uint32_t) (2 * n_samples));
memcpy(b.data() + 8, "WAVEfmt ", 8);
put32(16, 16); // fmt chunk size
put16(20, 1); // PCM
put16(22, 1); // channels
put32(24, 16000); // sample rate
put32(28, 16000 * 2); // byte rate
put16(32, 2); // block align
put16(34, 16); // bits per sample
memcpy(b.data() + 36, "data", 4);
put32(40, (uint32_t) (2 * n_samples));
return b;
}
static void test_decision_media_order(testing & t) {
const mtmd_helper_init_opt opt = mtmd_helper_init_opt_default();
const std::vector<uint8_t> png = { // a 1x1 grayscale PNG
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x7e, 0x9b,
0x55, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, 0x00, 0x00, 0x00,
0x02, 0x00, 0x01, 0x48, 0xaf, 0xa4, 0x71, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
0x42, 0x60, 0x82,
};
const raw_buffer image = png;
const raw_buffer audio_a = make_wav_16khz(16);
const raw_buffer audio_b = make_wav_16khz(32);
// the detector recognizes the buffers, so the test exercises the real grouping
mtmd_helper_media_meta meta;
t.assert_true("image detected", mtmd_helper_get_media_meta(image.data(), image.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_IMAGE);
t.assert_true("audio detected", mtmd_helper_get_media_meta(audio_a.data(), audio_a.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_AUDIO);
// images come first even when the request lists audio first
const std::vector<raw_buffer> grouped = decision_order_media({audio_a, image}, opt);
t.assert_equal("count", (size_t) 2, grouped.size());
t.assert_true("image first", grouped[0] == image);
t.assert_true("audio last", grouped[1] == audio_a);
// the order within a kind is kept
const std::vector<raw_buffer> stable = decision_order_media({audio_b, image, audio_a}, opt);
t.assert_equal("stable count", (size_t) 3, stable.size());
t.assert_true("stable image first", stable[0] == image);
t.assert_true("stable audio order", stable[1] == audio_b && stable[2] == audio_a);
// a decoder that reads any buffer as a video, the built-in one needs ffmpeg
static int decoder_state = 0;
mtmd_helper_video_decoder decoder = {};
decoder.open = [](void *, const char *, const unsigned char *, size_t, mtmd_helper_video_stream_info * info) -> void * {
*info = {16, 16, 2.0f, 4, 2.0f};
return &decoder_state;
};
decoder.read_frame = [](void *, unsigned char *, uint32_t, uint32_t) { return false; };
decoder.close = [](void *) {};
mtmd_helper_init_opt opt_video = opt;
opt_video.video_params.decoder = &decoder;
const raw_buffer video = {'v', 'i', 'd', 'e', 'o'};
t.assert_true("video detected", mtmd_helper_get_media_meta(video.data(), video.size(), opt_video, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_VIDEO);
const std::vector<raw_buffer> with_video = decision_order_media({video, audio_a, image}, opt_video);
t.assert_true("video last", with_video.size() == 3 && with_video[0] == image && with_video[1] == audio_a && with_video[2] == video);
// cloudflare-clef-omni
std::string error;
try {
decision_order_media({image, video}, opt_video, false);
} catch (const std::invalid_argument & e) {
error = e.what();
}
t.assert_true("video rejected: " + error, error.find("video input is not supported") != std::string::npos);
t.assert_equal("no video, nothing rejected", (size_t) 2, decision_order_media({audio_a, image}, opt_video, false).size());
}
// DRY sequence breakers
//
@@ -1105,14 +956,11 @@ 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);
t.test("decision_ocr_jev_validation", test_decision_ocr_jev_validation);
t.test("decision_media_fields", test_decision_media_fields);
t.test("decision_depth", test_decision_depth);
t.test("decision_media_order", test_decision_media_order);
t.test("glob_match", test_glob_match);
t.test("dry_sequence_breakers", test_dry_sequence_breakers);
t.test("stop_strings", test_stop_strings);
-17
View File
@@ -264,23 +264,6 @@ or, if `invoke()` threw:
There is no `[DONE]` sentinel (unlike `/chat/completions`), the stream ends after the `done`
**Background tasks**
`exec_shell_command` runs every command as a task. With an `X-Conversation-Id` header, set by the client and never by the model, a task can move to the background: owned by that conversation, it keeps running after its call returns. Without the header, commands run and block as before.
- `params.background: true` runs the command with no timeout: if it still runs after `params.background_after_seconds` (default 1), it moves to the background and the call returns with the output so far and a `task_id`; a command that ends before returns like any other
- a command moved to the background, by `background` or by `POST /tools/tasks`, loses its timeout
- task ids are random, so a client can not guess the tasks of another conversation
- with `stream: true`, the first event carries the id of the command: `{"chunk": "", "exec_id": 3}`
Routes, all scoped to the conversation the request names:
- `POST /tools/tasks` with `{"conv_id": "c", "from_exec_id": 3}`: move a running command to the background, its call returns at once and the task keeps the same id
- `GET /tools/tasks/events?conv_ids=a,b`: SSE, a `snapshot` of the background tasks of these conversations, then `task_started`, `task_output` (`id` and `offset`, at most one every 500 ms per task) and `task_exited`
- `GET /tools/tasks/output?conv_id=c&id=3&from=0`: the task, its `output` since `from`, `next` for the next read, and `skipped` when older output was dropped (256 KB kept per task)
- `DELETE /tools/tasks?conv_id=c&id=3`: stop a task and everything it started
The model gets the `background_task` tool (`list`, `output`, `stop`) for the tasks of its conversation. Everything still running is stopped when the server exits.
### Router mode: how child <--> router communicates
Upon spawning a new child process using `subprocess`, both child and router listen to the stdout/stderr (combined)
+8 -12
View File
@@ -557,7 +557,7 @@ These words will not be included in the completion, so make sure to add them to
`typical_p`: Enable locally typical sampling with parameter p. Default: `1.0`, which is disabled.
`repeat_penalty`: Control the repetition of token sequences in the generated text (alias: `repetition_penalty`). Default: `1.1`
`repeat_penalty`: Control the repetition of token sequences in the generated text. Default: `1.1`
`repeat_last_n`: Last n tokens to consider for penalizing repetition. Default: `64`, where `0` is disabled.
@@ -878,7 +878,7 @@ Returns raw audio bytes (`audio/wav` by default) rather than JSON. For the list
`temperature`: Temperature for the backbone sampler and the audio frames, for models that support it. `0` is greedy sampling. Optional, absent keeps the server `--temp` for the backbone and the model defaults for the audio.
`repeat_penalty`: Repetition penalty applied to the backbone sampler over the whole generation (alias: `repetition_penalty`, default `1.05`). Without this, the backbone can loop and re-generate the same utterance.
`repeat_penalty`: Repetition penalty applied to the backbone sampler over the whole generation (default `1.05`). Without this, the backbone can loop and re-generate the same utterance.
`seed`: RNG seed for both the backbone sampler and the codec/vocoder (`-1` = random, the default). Set to a fixed value for reproducible output.
@@ -1932,8 +1932,6 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo
`images`: Optional. An alias of `files`.
`audio`: Optional. An alias of `files`.
`questions`: An object that maps a question id to a question. Each question has these fields:
- `type`: One of `choice`, `score`, `noul`.
@@ -1943,11 +1941,11 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo
- `score`: An array of 2 to 10 level descriptions, lowest level first.
- `noul`: Optional. An object with the descriptions of `true` and `false`.
The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef and cloudflare-clef-omni, which read all the questions in one prompt and decide them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass).
The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef, which reads all the questions in one prompt and decides them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass).
The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, cloudflare-clef-omni, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with.
The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with.
For laya, clef, cloudflare-clef-omni, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef or cloudflare-clef-omni only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`.
For laya, clef, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`.
openbmb-minicpm-ocr-jev answers one fixed question: is an OCR text, rendered as an image, consistent with the original image? `state` is the OCR text, as a string, special tokens written in it are escaped. `files` (or `images`) has exactly 2 images: the original, then the rendered one, both are required. The request has one question and no `instructions`: the task is part of the prompt of the model, so a request that sends one is rejected. It is either a `choice` with the `criteria` `{"0": null, "1": null}`, where `1` means consistent, or a `noul` without `criteria`, which returns the probability of `1`. The model has no LM head, so text generation is not available.
@@ -1955,16 +1953,14 @@ Its prompt carries two images, so it is much longer than a text-only one: size t
*Image input:*
Image input needs a model that supports it (for example: openjev, clef, cloudflare-clef-omni, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`.
Image input needs a model that supports it (for example: openjev, clef, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`.
Images can be given in two ways, and both can be used in the same request:
- The `files` field, or its aliases `images` and `audio`.
- The `files` field, or its alias `images`.
- A `state` made of chat messages, either an array of messages or an object with a `messages` array. An `image_url` part in the `content` of a message is taken as an image, in the same format as chat completions. Only data URLs are accepted. For lfm2-d1-omni, an `input_audio` part is taken as an audio clip, as base64 data.
All the images are placed before the state in the prompt, the ones from `files`, `images` and `audio` first. The image parts are removed from the state.
For clef and cloudflare-clef-omni, the files are grouped by kind, as the models were trained: images, then audio clips, then videos. A video is rejected by cloudflare-clef-omni.
All the images are placed before the state in the prompt, the ones from `files` and `images` first. The image parts are removed from the state.
*Response:*
-1
View File
@@ -241,7 +241,6 @@ std::vector<std::string> server_model_output_modalities(common_decision_type dec
case COMMON_DECISION_TYPE_MINICPM_OCR_JEV:
case COMMON_DECISION_TYPE_LFM3_D1:
case COMMON_DECISION_TYPE_LFM3_D1_OMNI:
case COMMON_DECISION_TYPE_CLEF_OMNI:
out = {"decisions"};
break;
case COMMON_DECISION_TYPE_GRANITE_SWITCH:
+1 -2
View File
@@ -5178,7 +5178,6 @@ 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 {
@@ -5713,7 +5712,7 @@ static json parse_tts_body(const server_http_req & req) {
body[k] = std::stoll(body[k].get<std::string>());
}
}
for (const char * k : { "top_p", "temperature", "repeat_penalty", "repetition_penalty", "speed", "loudness", "cfg_scale" }) {
for (const char * k : { "top_p", "temperature", "repeat_penalty", "speed", "loudness", "cfg_scale" }) {
if (body.contains(k) && body[k].is_string()) {
body[k] = std::stof(body[k].get<std::string>());
}
+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), readers waiting for a result get an error
// terminate main loop (will unblock start_loop)
void terminate();
// get the underlaying llama_context, can return nullptr if sleeping
+8 -46
View File
@@ -153,7 +153,7 @@ void server_decision_context::init(const llama_model * model) {
throw std::runtime_error("decision model has no valid max_head_tokens");
}
n_options_max = 255;
} else if (model_type == COMMON_DECISION_TYPE_CLEF || model_type == COMMON_DECISION_TYPE_CLEF_OMNI) {
} else if (model_type == COMMON_DECISION_TYPE_CLEF) {
n_options_max = 255;
noul_true_first = true;
choice_sorted = true;
@@ -410,40 +410,6 @@ static void decision_load_audio(const json & data, std::vector<raw_buffer> & fil
handle_media(files, data.get<std::string>(), "");
}
// the joint head reads media grouped by kind, as the model was trained: images, then audio, then video
std::vector<raw_buffer> decision_order_media(const std::vector<raw_buffer> & files, const mtmd_helper_init_opt & init_opt, bool allow_video) {
auto rank_of = [&](const raw_buffer & file) -> int {
mtmd_helper_media_meta meta;
if (mtmd_helper_get_media_meta(file.data(), file.size(), init_opt, &meta) == 0) {
switch (meta.type) {
case MTMD_HELPER_MEDIA_TYPE_IMAGE: return 0;
case MTMD_HELPER_MEDIA_TYPE_AUDIO: return 1;
case MTMD_HELPER_MEDIA_TYPE_VIDEO:
if (!allow_video) {
throw std::invalid_argument("video input is not supported by this model");
}
return 2;
default: break;
}
}
return 3; // mtmd reports the error when the prompt is tokenized
};
std::vector<std::pair<int, const raw_buffer *>> ranked;
ranked.reserve(files.size());
for (const auto & file : files) {
ranked.emplace_back(rank_of(file), &file);
}
std::stable_sort(ranked.begin(), ranked.end(), [](const auto & a, const auto & b) { return a.first < b.first; });
std::vector<raw_buffer> out;
out.reserve(files.size());
for (const auto & entry : ranked) {
out.push_back(*entry.second);
}
return out;
}
json server_decision_context::parse_state(const json & body, std::vector<raw_buffer> & files) const {
if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV && !body.at("state").is_string()) {
throw std::invalid_argument("\"state\" must be the OCR text");
@@ -451,8 +417,8 @@ json server_decision_context::parse_state(const json & body, std::vector<raw_buf
if (body.contains("videos") && !body.at("videos").is_null() && !body.at("videos").empty()) {
throw std::invalid_argument("\"videos\" is not supported");
}
// "images" and "audio" are aliases of "files"
for (const char * key : {"files", "images", "audio"}) {
// "images" is an alias of "files"
for (const char * key : {"files", "images"}) {
if (!body.contains(key) || body.at(key).is_null()) {
continue;
}
@@ -1587,15 +1553,11 @@ void server_decision_context::fill_task_joint(
};
inp = decision_replace_text(decision_sort_keys(inp), CLEF_MARKER, "<<clef ");
// the model reads media grouped by kind: images, then audio, then video
// clef-omni: mtmd lays out a video as Qwen3-VL does, the model was trained with the layout of the Qwen3-Omni processor
const std::vector<raw_buffer> media = decision_order_media(files, init_opt, type != COMMON_DECISION_TYPE_CLEF_OMNI);
// the template puts one media marker per file
// the template puts one media marker per image
json images = json::array();
if (!media.empty()) {
if (!files.empty()) {
inp = decision_replace_text(inp, get_media_marker(), " ");
for (size_t i = 0; i < media.size(); i++) {
for (size_t i = 0; i < files.size(); i++) {
images.push_back(get_media_marker());
}
}
@@ -1617,7 +1579,7 @@ void server_decision_context::fill_task_joint(
size_t i_piece = 0;
task.tokens = server_tokens(llama_tokens(), false);
if (!media.empty()) {
if (!files.empty()) {
// the text before the images is tokenized with them, a vision token separates the pieces anyway
std::string head;
while (i_piece < pieces.size() && head.find(get_media_marker()) == std::string::npos) {
@@ -1626,7 +1588,7 @@ void server_decision_context::fill_task_joint(
if (head.find(get_media_marker()) == std::string::npos || head.find(CLEF_MARKER) != std::string::npos) {
throw invalid;
}
task.tokens = process_mtmd_prompt(mctx, head, media, init_opt);
task.tokens = process_mtmd_prompt(mctx, head, files, init_opt);
task.decision.order.resize(task.tokens.size(), LLAMA_DECISION_ORDER_NONE);
}
+2 -7
View File
@@ -56,7 +56,7 @@ struct server_decision_context {
// true if all the questions of a request go in one prompt, see fill_task_joint()
bool is_joint() const {
return type == COMMON_DECISION_TYPE_CLEF || type == COMMON_DECISION_TYPE_CLEF_OMNI;
return type == COMMON_DECISION_TYPE_CLEF;
}
bool is_lfm3_d1() const {
@@ -76,7 +76,6 @@ struct server_decision_context {
case COMMON_DECISION_TYPE_MINICPM_OCR_JEV:
case COMMON_DECISION_TYPE_LFM3_D1:
case COMMON_DECISION_TYPE_LFM3_D1_OMNI:
case COMMON_DECISION_TYPE_CLEF_OMNI:
return true;
default:
return false;
@@ -97,7 +96,7 @@ struct server_decision_context {
json prepare_state(const json & state) const;
// returns the state without its images, they are appended to files in order
// images come from "files" (aliases "images" and "audio") and from the image_url and input_audio parts of a state made of chat messages
// images come from "files" (alias "images") and from the image_url and input_audio parts of a state made of chat messages
// an image can be an audio clip if the model supports it
json parse_state(const json & body, std::vector<raw_buffer> & files) const;
@@ -208,9 +207,5 @@ private:
// note: the order of the tasks is preserved
std::vector<server_task> server_decision_group_tasks(std::vector<server_task> && tasks, size_t n_slots);
// order the media as the joint head reads them: images, then audio, then video
// throw std::invalid_argument on a video if allow_video is false
std::vector<raw_buffer> decision_order_media(const std::vector<raw_buffer> & files, const mtmd_helper_init_opt & init_opt, bool allow_video = true);
// write "<|name|>" with U+00A6 in place of "|", so text from the request is not parsed as special tokens
std::string server_decision_escape_special_tokens(const std::string & text);
+9 -21
View File
@@ -429,20 +429,15 @@ 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, [&]{
return !running || !queue_results.empty();
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();
});
for (size_t i = 0; i < queue_results.size(); i++) {
@@ -452,11 +447,6 @@ 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
@@ -475,12 +465,11 @@ server_task_result_ptr server_response::recv_with_timeout(const std::unordered_s
}
}
if (!running) {
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 (!running) {
RES_DBG("%s : queue result stop\n", __func__);
std::terminate(); // we cannot return here since the caller is HTTP code
}
if (cr_res == std::cv_status::timeout) {
return nullptr;
}
@@ -521,7 +510,6 @@ 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();
}
+1 -2
View File
@@ -182,7 +182,6 @@ 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
@@ -199,7 +198,7 @@ public:
// (used by router mode)
void broadcast(server_task_result_ptr && result);
// wake up all readers, used when no more results will be sent
// terminate the waiting loop
void terminate();
};
-2
View File
@@ -130,7 +130,6 @@ std::vector<std::unique_ptr<field>> make_llama_cmpl_schema(const common_params &
->set_desc("Last n tokens to consider for penalizing repetition (0 = disabled)"));
add((new field_num("repeat_penalty", params.sampling.penalty_repeat))
->add_alias("repetition_penalty")
->set_desc("Control the repetition of token sequences in the generated text (1.0 = disabled)"));
add((new field_num("frequency_penalty", params.sampling.penalty_freq))
@@ -575,7 +574,6 @@ std::vector<std::unique_ptr<field>> make_tts_schema(server_task & task) {
->set_desc("Max number of audio frames to generate"));
add((new field_num("repeat_penalty", task.params.sampling.penalty_repeat))
->add_alias("repetition_penalty")
->set_desc("Repetition penalty applied to the backbone sampler over the whole generation"));
add((new field_bool("stream", task.params.stream))
+41 -10
View File
@@ -8,6 +8,11 @@
#include <utility>
#include <shared_mutex>
enum class stream_read_status {
OK,
OFFSET_LOST,
};
namespace {
constexpr int64_t STREAM_SESSION_TTL_SECONDS = 300;
constexpr size_t STREAM_SESSION_MAX_BYTES = 4 * 1024 * 1024;
@@ -67,6 +72,42 @@ void server_stream_session_manager_stop() {
g_stream_sessions.stop_gc();
}
struct stream_session {
std::string conversation_id;
int64_t started_ts; // unix seconds at construction
stream_session(std::string conversation_id_, size_t max_bytes_);
stream_session(const stream_session &) = delete;
stream_session & operator=(const stream_session &) = delete;
bool append(const char * data, size_t len);
void finalize();
// drain from offset into sink, blocking for more bytes or finalize. OFFSET_LOST if offset
// fell below the dropped prefix
stream_read_status read_from(size_t offset,
const std::function<bool(const char *, size_t)> & sink,
const std::function<bool()> & should_stop);
bool is_done() const;
bool is_cancelled() const;
size_t total_size() const; // bytes that ever entered the session
size_t dropped_prefix() const; // bytes evicted from the front due to cap
int64_t completed_at() const; // 0 while alive, unix seconds after finalize
void cancel();
private:
mutable std::mutex mu;
std::condition_variable cv;
std::vector<char> buffer;
size_t prefix_dropped;
size_t cap_bytes;
bool done;
std::atomic<bool> cancelled; // polled lock-free by the should_stop closure, no mu
int64_t completed_ts;
};
stream_session::stream_session(std::string conversation_id_, size_t max_bytes_)
: conversation_id(std::move(conversation_id_))
, started_ts(now_seconds())
@@ -153,16 +194,6 @@ stream_read_status stream_session::read_from(size_t offset,
}
}
stream_read_status stream_session::read_available(size_t offset, std::string & out) const {
std::lock_guard<std::mutex> lock(mu);
if (offset < prefix_dropped) {
return stream_read_status::OFFSET_LOST;
}
const size_t local_off = std::min(offset - prefix_dropped, buffer.size());
out.append(buffer.begin() + local_off, buffer.end());
return stream_read_status::OK;
}
bool stream_session::is_done() const {
std::lock_guard<std::mutex> lock(mu);
return done;
+1 -48
View File
@@ -3,62 +3,15 @@
#include "server-http.h"
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
// streaming buffer for one generation, survives HTTP disconnect. the producer appends SSE bytes,
// readers drain from any offset via read_from. keyed by conversation_id, one conv = one live session
enum class stream_read_status {
OK,
OFFSET_LOST,
};
struct stream_session {
std::string conversation_id;
int64_t started_ts; // unix seconds at construction
stream_session(std::string conversation_id_, size_t max_bytes_);
stream_session(const stream_session &) = delete;
stream_session & operator=(const stream_session &) = delete;
bool append(const char * data, size_t len);
void finalize();
// drain from offset into sink, blocking for more bytes or finalize. OFFSET_LOST if offset
// fell below the dropped prefix
stream_read_status read_from(size_t offset,
const std::function<bool(const char *, size_t)> & sink,
const std::function<bool()> & should_stop);
// append what is buffered from offset to out without waiting. OFFSET_LOST if offset fell below the dropped prefix
stream_read_status read_available(size_t offset, std::string & out) const;
bool is_done() const;
bool is_cancelled() const;
size_t total_size() const; // bytes that ever entered the session
size_t dropped_prefix() const; // bytes evicted from the front due to cap
int64_t completed_at() const; // 0 while alive, unix seconds after finalize
void cancel();
private:
mutable std::mutex mu;
std::condition_variable cv;
std::vector<char> buffer;
size_t prefix_dropped;
size_t cap_bytes;
bool done;
std::atomic<bool> cancelled; // polled lock-free by the should_stop closure, no mu
int64_t completed_ts;
};
struct stream_session;
using stream_session_ptr = std::shared_ptr<stream_session>;
File diff suppressed because it is too large Load Diff
-12
View File
@@ -25,7 +25,6 @@ struct server_tool {
int id;
std::function<bool()> alive;
void push(const std::string & chunk);
void push_data(const json & data);
};
// should_stop: true once the caller stopped waiting, e.g. the client dropped the connection; a null should_stop means "never stop"
virtual json invoke(json params, stream * st = nullptr, const std::function<bool()> & should_stop = nullptr) const = 0;
@@ -34,7 +33,6 @@ struct server_tool {
};
struct server_tools_runtime; // impl detail, defined in server-tools.cpp
struct tools_tasks; // impl detail, defined in server-tools.cpp
struct server_tools {
std::vector<std::unique_ptr<server_tool>> tools;
@@ -46,23 +44,13 @@ struct server_tools {
// set when --tools-runtime is configured; routes every tool call through an isolate
std::unique_ptr<server_tools_runtime> runtime;
// background tasks started by exec_shell_command, stopped with everything they started when this is destroyed
std::unique_ptr<tools_tasks> tasks;
void setup(const std::vector<std::string> & enabled_tools,
server_mcp & mcp_mgr,
const std::string & tools_runtime);
server_http_context::handler_t handle_get;
server_http_context::handler_t handle_post;
server_http_context::handler_t handle_tasks_events; // GET /tools/tasks/events?conv_ids=a,b
server_http_context::handler_t handle_tasks_create; // POST /tools/tasks {"conv_id": c, "from_exec_id": n}
server_http_context::handler_t handle_tasks_output; // GET /tools/tasks/output?conv_id=c&id=n&from=offset
server_http_context::handler_t handle_tasks_stop; // DELETE /tools/tasks?conv_id=c&id=n
server_tools();
~server_tools();
private:
void setup_tasks_routes();
};
-8
View File
@@ -308,10 +308,6 @@ static bool server_setup_features(
}
ctx_http.get ("/tools", ex_wrapper(tools.handle_get));
ctx_http.post("/tools", ex_wrapper(tools.handle_post));
ctx_http.get ("/tools/tasks/events", ex_wrapper(tools.handle_tasks_events));
ctx_http.get ("/tools/tasks/output", ex_wrapper(tools.handle_tasks_output));
ctx_http.post("/tools/tasks", ex_wrapper(tools.handle_tasks_create));
ctx_http.del ("/tools/tasks", ex_wrapper(tools.handle_tasks_stop));
if (!params.server_tools.empty()) {
warn_names.push_back("server tools (experimental)");
}
@@ -324,10 +320,6 @@ static bool server_setup_features(
} else {
ctx_http.get ("/tools", ex_wrapper(res_403));
ctx_http.post("/tools", ex_wrapper(res_403));
ctx_http.get ("/tools/tasks/events", ex_wrapper(res_403));
ctx_http.get ("/tools/tasks/output", ex_wrapper(res_403));
ctx_http.post("/tools/tasks", ex_wrapper(res_403));
ctx_http.del ("/tools/tasks", ex_wrapper(res_403));
}
if (!warn_names.empty()) {
-19
View File
@@ -171,22 +171,3 @@ 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()
@@ -1,4 +1,3 @@
import json
import os
import re
import shutil
@@ -7,7 +6,6 @@ import sys
import time
import pytest
import requests
from utils import *
server: ServerProcess
@@ -23,10 +21,6 @@ CONTAINER_IMAGE = "busybox"
COMMAND_LEAVING_A_PROCESS = "start /b ping -n 30 127.0.0.1 & echo started" if os.name == "nt" else "sleep 30 & echo started"
COMMAND_OUTLIVING_THE_TIMEOUT = "ping -n 30 127.0.0.1 & echo done" if os.name == "nt" else "sleep 30; echo done"
COMMAND_RUNNING_UNTIL_STOPPED = "ping -n 30 127.0.0.1 > nul" if os.name == "nt" else "sleep 30"
COMMAND_ENDING_AFTER_3_SECONDS = "echo hello & ping -n 4 127.0.0.1 > nul & echo bye" if os.name == "nt" else "echo hello; sleep 3; echo bye"
BACKGROUND_CONV_ID = "conv-background"
@pytest.fixture(autouse=True)
@@ -268,132 +262,6 @@ def test_tools_builtin_exec_shell_command_timeout_ends_the_command():
assert "done" not in res["plain_text_response"]
def call_tool_in_conversation(name: str, params: dict) -> dict:
return call_tool(name, params, headers={"X-Conversation-Id": f"{BACKGROUND_CONV_ID}::some/model"})
def wait_task_exited(events) -> list:
seen = []
for line in events.iter_lines():
if line.startswith(b"data: "):
seen.append(json.loads(line[6:])["event"])
if seen[-1] == "task_exited":
break
events.close()
return seen
def test_tools_builtin_background_task_needs_a_conversation():
global server
server.start()
err = call_tool_expect_error("exec_shell_command", {"command": "echo hello", "background": True})
assert "X-Conversation-Id" in err
def test_tools_builtin_background_task_output_and_events():
global server
server.start()
events = requests.get(server.make_url(f"/tools/tasks/events?conv_ids={BACKGROUND_CONV_ID}"), stream=True, timeout=30)
res = call_tool_in_conversation("exec_shell_command", {"command": COMMAND_ENDING_AFTER_3_SECONDS, "background": True})
assert "hello" in res["plain_text_response"]
assert "moved to the background" in res["plain_text_response"]
task_id = res["task_id"]
seen = wait_task_exited(events)
assert seen[0] == "snapshot"
assert "task_started" in seen
assert f"{task_id}: exited" in call_tool_in_conversation("background_task", {"action": "list"})["plain_text_response"]
other = server.make_request("POST", "/tools", data={"tool": "background_task", "params": {"action": "output", "task_id": task_id}},
headers={"X-Conversation-Id": "conv-other"})
assert "error" in other.body
output = server.make_request("GET", f"/tools/tasks/output?conv_id={BACKGROUND_CONV_ID}&id={task_id}&from=0")
assert "hello" in output.body["output"]
assert "bye" in output.body["output"]
def test_tools_builtin_background_task_ending_early_returns_like_any_command():
global server
server.start()
res = call_tool_in_conversation("exec_shell_command", {"command": "echo quick", "background": True})
assert "quick" in res["plain_text_response"]
assert "exit code: 0" in res["plain_text_response"]
assert "task_id" not in res
def test_tools_builtin_background_task_has_no_timeout():
global server
server.start()
events = requests.get(server.make_url(f"/tools/tasks/events?conv_ids={BACKGROUND_CONV_ID}"), stream=True, timeout=30)
res = call_tool_in_conversation("exec_shell_command", {
"command": COMMAND_ENDING_AFTER_3_SECONDS, "background": True, "background_after_seconds": 0, "timeout": 1,
})
task_id = res["task_id"]
wait_task_exited(events)
output = server.make_request("GET", f"/tools/tasks/output?conv_id={BACKGROUND_CONV_ID}&id={task_id}&from=0")
assert "bye" in output.body["output"]
assert output.body["exit_code"] == 0
assert "timed_out" not in output.body
def test_tools_builtin_background_task_stop():
global server
server.start()
res = call_tool_in_conversation("exec_shell_command", {"command": COMMAND_RUNNING_UNTIL_STOPPED, "background": True})
assert "moved to the background" in res["plain_text_response"]
start = time.monotonic()
stopped = server.make_request("DELETE", f"/tools/tasks?conv_id={BACKGROUND_CONV_ID}&id={res['task_id']}")
assert time.monotonic() - start < 10
assert stopped.body["status"] == "stopped"
def test_tools_builtin_exec_moved_to_the_background_while_running():
global server
server.start()
events = server.make_stream_request("POST", "/tools", data={
"tool": "exec_shell_command",
"params": {"command": COMMAND_RUNNING_UNTIL_STOPPED, "timeout": 20},
"stream": True,
}, headers={"X-Conversation-Id": BACKGROUND_CONV_ID})
exec_id = next(events)["exec_id"]
res = server.make_request("POST", "/tools/tasks", data={"conv_id": BACKGROUND_CONV_ID, "from_exec_id": exec_id})
assert res.status_code == 200, res.body
assert "moved to the background" in "".join(e.get("chunk", "") for e in events)
stopped = server.make_request("DELETE", f"/tools/tasks?conv_id={BACKGROUND_CONV_ID}&id={exec_id}")
assert stopped.body["status"] == "stopped"
def test_tools_builtin_exec_moved_to_the_background_loses_its_timeout():
global server
server.start()
events = requests.get(server.make_url(f"/tools/tasks/events?conv_ids={BACKGROUND_CONV_ID}"), stream=True, timeout=30)
call = server.make_stream_request("POST", "/tools", data={
"tool": "exec_shell_command",
"params": {"command": COMMAND_ENDING_AFTER_3_SECONDS, "timeout": 2},
"stream": True,
}, headers={"X-Conversation-Id": BACKGROUND_CONV_ID})
exec_id = next(call)["exec_id"]
res = server.make_request("POST", "/tools/tasks", data={"conv_id": BACKGROUND_CONV_ID, "from_exec_id": exec_id})
assert res.status_code == 200, res.body
wait_task_exited(events)
output = server.make_request("GET", f"/tools/tasks/output?conv_id={BACKGROUND_CONV_ID}&id={exec_id}&from=0")
assert "bye" in output.body["output"]
assert "timed_out" not in output.body
def test_tools_builtin_cwd_header(tmp_path):
global server
server.start()

Some files were not shown because too many files have changed in this diff Show More