Compare commits

..
19 Commits
Author SHA1 Message Date
George BurtonandWestWaters 94be107ac2 model: add clef-omni (#33354)
* add: model clef-omni

Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com>

* add: has_lm_head to prevent double loading output.weight

* fix: potential key/index error in _load_clef_hparams

* remove: trailing ggml_build_forward_expand(gf, cur), fix: provenance comment

* add: test_decision_media_order to show that the media order matters

* fix: decision_order_media so that media is ordered correctly

* fix: comment in llama_tensor_get_type_impl

* remove: unsused ggml_build_forward_expand(), fix: comment in build_arch_graph

* fix: set min and max vison pixels for ClefOmniMmprojModel

* add: decision type for cloudflare-clef-omni and reject video media

* add: top-level audio in server-decision.cpp

---------

Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com>
2026-12-01 21:31:39 +01:00
Ehsan BateniandMax Krasnyansky 92f76e5c56 hexagon: optimize IQ2_XSS grid gathers (#33407)
Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
2026-12-01 12:28:58 -08:00
Animesh 509468d5aa ggml-cuda : optimize mmvq nwarps for Pascal DP4A (#25479) 2026-12-01 21:25:42 +01:00
Matheus Brittoandmatheusbrito b9073e5483 jinja : support Unicode whitespace and multi-byte chars in strip/trim (#33461)
* jinja : support Unicode whitespace and multi-byte chars in strip/trim

Assisted-by: Antigravity

* jinja : clarify Unicode strip comments and use args.func_name

Assisted-by: Antigravity

---------

Co-authored-by: matheusbrito <matheusbrito@MacBook-Air-de-matheusbrito.local>
2026-12-01 20:40:02 +01:00
Pascal e5cd6e34ba Vulkan: one thread per row for soft_max and sum_rows on short rows (#33197)
* vulkan : one thread per row for soft_max and sum_rows on short rows

A row of at most 8 columns got a whole workgroup with a shared memory
reduction. Each invocation now handles a whole row, with fastdiv for
the row indices, and sum_rows covers mean through its weight. On 3.4M
rows of 4 on an RTX PRO 6000, soft_max goes from 1653 to 42 us and
sum_rows from 1662 to 10 us. Hy4 flash decode goes from 53 to 60 t/s
at 4k context and from 9.6 to 54.8 t/s at 16k.

* vulkan : initialize soft_max fastdiv push constants

* vulkan : use vec4 loads in the short row soft_max and sum_rows

Rows of 4 or 8 floats were read and written one element at a time, so
each load of a subgroup hit addresses 16 or 32 bytes apart. When the row
length is a multiple of 4 and the strides are aligned, move whole vec4
instead, and keep the scalar loop otherwise.

On a RTX PRO 6000 with 3.44M rows of 4 floats, soft_max goes from 42 to
19 us and sum_rows/mean from 10.3 to 9.5 us.

* tests : remove the temporary short row cases

* vulkan : revert the vec4 loads in the short row soft_max and sum_rows

The vec4 path halves the soft_max kernel time on rows of 4 floats, but
Hy4 flash decode is unchanged on a RTX PRO 6000 and sum_rows gets slower
with 8 floats per row, so keep the simpler scalar loop.
2026-12-01 18:38:28 +01:00
Pascal cda9b4113c metal : add apertus to the Metal fusion baseline (#33453) 2026-12-01 19:21:04 +02:00
lhez 562f4b85b2 opencl: add log and non-contig scale (#33237)
* opencl: refactor scale

Assisted-by: Codex

* opencl: add log

Assisted-by: Codex

* docs: update OpenCL operation support
2026-12-01 09:14:33 -08:00
Marin Radic 9452452764 ggml-et : fix multi-line L2 flush and replace L2-SCP polling with FCC 0 (#33313)
FlushVA encodes numlines - 1 in 4 bits (max 16 lines), so the 32-line
Q4_0 panel flush in mul_mat_Q4_0_matrix_engine silently dropped lines
16..31. Add flush_to_l2_multi() in platform.h to chunk flushes by 16.

L2-SCP also persists across kernel launches, so ready_ctr/consumed_ctr
polling in mul_mat_Q4_0_matrix_engine and mul_mat_f16_matrix_engine
raced at entry and could corrupt results or deadlock. Replace the
L2-SCP counters with FCC 0 semaphores (et_sem_post/et_sem_wait) plus
hart 1 exit credit drain (matching flash_attn_ext_f16_me.c), which
avoids FLB 0 aliasing with uberkernel barriers and improves Q4_0
4096x512x14336 throughput from 632.9 to 668.1 GFLOPS (+5.6%).

Assisted-by: Antigravity
2026-12-01 23:24:37 +08:00
Niklas Wenzel 06fa894b15 metal : detect Neural Accelerators without hardcoding chips (#33272)
So that applications built with today's version of llama.cpp will properly use the tensor API on chips released in the future without requiring a llama.cpp update.
2026-12-01 16:48:04 +02:00
30b900181b CUDA/HIP: Use the MMA FA kernel for maskless attention on RDNA (#32930)
* CUDA/HIP: Use the MMA FA kernel for maskless attention on RDNA

Vision encoders commonly use non-causal, maskless attention. On RDNA GPUs, the MMA kernel runs faster than the tile kernel for this workload. However, the current AMD MMA path is only selected for GQA-optimized attention.

Enable the wide MMA kernel (`ncols1 = 64`, `ncols2 = 1`) for maskless attention when `n_queries >= 128` on all AMD GPUs that support WMMA.

Assisted-by: GitHub Copilot

* Remove extra tests

Co-authored-by: Johannes Gäßler <johannesg@5d6.de>

* CUDA: fix ALiBi slope in RDNA3 mma FA kernel

Assisted-by: GitHub Copilot

---------

Co-authored-by: uvos <devnull@uvos.xyz>
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
2026-12-01 15:47:26 +01:00
Pascal 6d0716cff4 gguf: document and test the NUL byte rule for keys and tensor names (#33443)
State in the format description at the top of gguf.h that keys and
tensor names must not contain null bytes while string values can.

Add handcrafted test cases for both: a key with an embedded NUL placed
before the key it would shadow, and tensor names that only differ after
a NUL. Both files are now expected to be rejected.
2026-12-01 15:43:55 +01:00
Mustafa Camurcu 04586184ce vulkan: read IQ1/IQ2/IQ3 grid tables from a storage buffer (#32915)
Upload the grid tables once per device and copy them to shared memory
from a storage buffer instead of from GLSL constant arrays, avoiding
divergent constant loads in init_iq_shmem.

Assisted-by: Claude Opus 5.5
2026-12-01 15:42:58 +01:00
Aleksander Grygier 2e11b8a8dd ui: list the conversation's background tasks under the chat form (#33211)
Built on llama-server's background tasks (#33391). Shell calls now carry the
X-Conversation-Id header, so a command can move to the background: the model
asks for it with `background: true`, and the user with "Move to background"
under a running call.

The chip under the chat form counts the conversation's running tasks, followed
over GET /tools/tasks/events while the tab is visible. Its dialog lists them;
each row shows the task's output, read from GET /tools/tasks/output while it
is open, and Stop ends it with everything it started through DELETE
/tools/tasks. A task leaves the list when it ends.

Llama UI gains a Chip (now used by the system message chip too), an xs button
size and a danger-secondary button variant for Stop; the shell prompt line is
one component shared by the tool call and the task rows.

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-01 15:42:06 +01:00
Nakul Lagwal c9dbfa5779 jinja : iterate over strings in for loops (#33433)
* jinja : iterate over strings in for loops

* jinja : pre-reserve the string expansion

* jinja : mark byte-based string handling with FIXMEs

* jinja : drop redundant iteration comment

Assisted-by: Hermes Agent
2026-12-01 15:37:29 +01:00
Pig with dreams ae2b404f08 convert : fix silent expert weight corruption for GPT-OSS (#32546)
* Fix silent expert weight corruption when converting GPT-OSS to GGUF

Assisted-by: Codex

* Drop test addition from tests/test_conversion_fp8.py
2026-12-01 15:35:56 +01:00
Hongbo Wen 6fd26a7ea0 cuda : use dst strides in unary_op_kernel_strided (#33322)
Index dst via dst->nb[0..3] byte strides in unary_op_kernel_strided and dispatch the strided path whenever src0 or dst is non-contiguous so inplace unary ops on strided views do not overwrite padding.

Assisted-by: Antigravity
2026-12-01 15:23:34 +01:00
Alex-JP-93 b7a59f3f54 vulkan: reduce cm1 int8 MMQ performance gap between AMD shader compilers - part 1: accumulate folding (#32528) 2026-12-01 15:08:27 +01:00
Xuan-Son Nguyen c82b798866 server: add "repetition_penalty" as alias for "repeat_penalty" (#33439) 2026-12-01 14:25:56 +01:00
issixx 386e41466b CUDA: optimize f16 conversion when using kv_rows (#33427) 2026-12-01 21:17:24 +08:00
94 changed files with 2603 additions and 1534 deletions
+2
View File
@@ -1170,6 +1170,7 @@ 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"
};
@@ -1298,6 +1299,7 @@ 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,6 +1002,7 @@ 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
};
+17 -1
View File
@@ -556,10 +556,25 @@ 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)) {
if (!is_val<value_array>(iterable_val) && !is_val<value_object>(iterable_val) && !is_val<value_string>(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");
@@ -970,6 +985,7 @@ 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) {
+84 -33
View File
@@ -1,5 +1,6 @@
#include "jinja/string.h"
#include "jinja/value.h"
#include "unicode.h"
#include <algorithm>
#include <functional>
@@ -205,53 +206,103 @@ 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) {
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 {
while (start < end) {
auto parsed = common_parse_utf8_codepoint(full, start);
if (parsed.status != utf8_parse_result::SUCCESS || !match_cp(parsed.codepoint)) {
break;
}
start += parsed.bytes_consumed;
}
}
if (right) {
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;
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;
} else {
break;
pos += parsed.bytes_consumed;
if (!match_cp(parsed.codepoint)) {
new_end = pos;
}
}
}
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;
}
+22 -26
View File
@@ -739,6 +739,24 @@ 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},
@@ -757,36 +775,13 @@ const func_builtins & value_string_t::get_builtins() const {
return mk_val<value_string>(str);
}},
{"strip", [](const func_args & args) -> value {
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()));
}
return string_strip_impl(args, true, true);
}},
{"rstrip", [](const func_args & args) -> value {
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()));
}
return string_strip_impl(args, false, true);
}},
{"lstrip", [](const func_args & args) -> value {
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()));
}
return string_strip_impl(args, true, false);
}},
{"title", [](const func_args & args) -> value {
args.ensure_kwargs();
@@ -1016,6 +1011,7 @@ 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());
+2
View File
@@ -50,6 +50,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"ChatGLMModel": "chatglm",
"ChatterboxModel": "chatterbox",
"ClefModel": "clef",
"ClefOmniModel": "clef",
"CloverMoeModelLM": "clover",
"CodeShellForCausalLM": "codeshell",
"CogVLMForCausalLM": "cogvlm",
@@ -361,6 +362,7 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
"AudioFlamingo3ForConditionalGeneration": "ultravox",
"ChatterboxModel": "chatterbox",
"ClefModel": "clef",
"ClefOmniModel": "clef",
"CogVLMForCausalLM": "cogvlm",
"Cohere2VisionForConditionalGeneration": "command_r",
"PplxDeciderModel": "pplx_decider",
+53 -13
View File
@@ -4,7 +4,7 @@ import json
import math
from pathlib import Path
from typing import Any, Iterable, Iterator, TYPE_CHECKING
from typing import Any, Callable, 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 Qwen3VLVisionModel
from .qwen3vl import Qwen3OmniMmprojModel, Qwen3OmniMoeTextModel, 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)
hparams["architectures"] = ["ClefModel"]
# 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"]
with open(dir_model / "joint_head_config.json", encoding="utf-8") as f:
hparams["decision"] = json.load(f)
return hparams
@ModelBase.register("ClefModel")
class ClefModel(Qwen3_5TextModel):
model_arch = gguf.MODEL_ARCH.CLEF
no_mtp = True # the checkpoint has no MTP head
class _ClefHeadMixin:
# the joint schema head, on top of the text model of the class that uses this mixin
# prompt follows joint_schema_model.py of the model repo
_SYSTEM_PROMPT = (
@@ -42,6 +42,17 @@ class ClefModel(Qwen3_5TextModel):
)
# 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)
@@ -52,7 +63,7 @@ class ClefModel(Qwen3_5TextModel):
self._scales: dict[str, float] = {}
def set_vocab(self):
super().set_vocab()
super().set_vocab() # ty: ignore[missing-attribute]
self.gguf_writer.add_chat_template([{"name": "systemone", "template": self._systemone_template()}])
@classmethod
@@ -75,9 +86,13 @@ class ClefModel(Qwen3_5TextModel):
"{% 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 }}{% for image in images %}{{ image }}{% endfor %}" + text("\n") + "{% endif %}"
+ "{% if images %}{{ sep }}" + images + "{% endif %}"
+ "{{ sep }}" + render("state")
+ "{{ sep }}" + text("\n\nSCHEMA FIELDS:\n")
+ "{% for q in questions %}"
@@ -96,23 +111,23 @@ class ClefModel(Qwen3_5TextModel):
)
def set_gguf_parameters(self):
super().set_gguf_parameters()
super().set_gguf_parameters() # ty: ignore[missing-attribute]
head = self.hparams["decision"]
self.gguf_writer.add_decision_type(gguf.DecisionType.CLEF)
self.gguf_writer.add_decision_type(self._DECISION_TYPE)
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()
yield from super().get_tensors() # ty: ignore[missing-attribute]
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)
yield from super().modify_tensors(data_torch, name, bid) # ty: ignore[missing-attribute]
return
parts = name.split(".")
@@ -145,6 +160,31 @@ class ClefModel(Qwen3_5TextModel):
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)
+11 -15
View File
@@ -62,23 +62,19 @@ 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]]:
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, :]
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:
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, blocks0, scales0)
self.repack_mxfp4(new_name_up, blocks1, scales1)
self.repack_mxfp4(new_name_gate, blocks[:, ::2, :, :], scales[:, ::2, :])
self.repack_mxfp4(new_name_up, blocks[:, 1::2, :, :], scales[:, 1::2, :])
return []
@classmethod
+1 -1
View File
@@ -69,7 +69,7 @@ Legend:
| L2_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
| LEAKY_RELU | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| LIGHTNING_INDEXER | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| MEAN | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
| MUL | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| MUL_MAT | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 |
+16 -9
View File
@@ -8979,10 +8979,14 @@
"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=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=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=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"
@@ -14821,7 +14825,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","0","no","OpenCL"
"OpenCL","LOG","type=f16,ne=[10,5,4,3]","support","1","yes","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"
@@ -14835,8 +14839,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","0","no","OpenCL"
"OpenCL","LOG","type=f16,ne=[1024,1024,1,1]","support","0","no","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","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"
@@ -14855,7 +14859,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","0","no","OpenCL"
"OpenCL","LOG","type=f32,ne=[10,5,4,3]","support","1","yes","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"
@@ -14869,8 +14873,11 @@
"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","0","no","OpenCL"
"OpenCL","LOG","type=f32,ne=[1024,1024,1,1]","support","0","no","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","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,6 +24,7 @@
// 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,
+45 -8
View File
@@ -40,14 +40,23 @@ static __global__ void dequantize_block(const void * __restrict__ vx, dst_t * __
}
}
template <bool need_check>
static __global__ void dequantize_block_q8_0_f16(const void * __restrict__ vx, half * __restrict__ y, const int64_t k) {
// 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) {
#if __CUDA_ARCH__ >= GGML_CUDA_CC_PASCAL
constexpr int nint = CUDA_Q8_0_NE_ALIGN/sizeof(int) + WARP_SIZE;
const int64_t i0 = CUDA_Q8_0_NE_ALIGN*blockIdx.x;
const int * x0 = ((int *) vx) + blockIdx.x * nint;
half2 * y2 = (half2 *) (y + i0);
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);
__shared__ int vals[nint];
@@ -76,7 +85,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);
GGML_UNUSED_VARS(vx, y, k, rows, n_rows);
NO_DEVICE_CODE;
#endif // __CUDA_ARCH__ >= GGML_CUDA_CC_PASCAL
}
@@ -268,10 +277,31 @@ 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><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, k);
dequantize_block_q8_0_f16<need_check, false><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, k, nullptr, 0);
} else {
const bool need_check = true;
dequantize_block_q8_0_f16<need_check><<<num_blocks, WARP_SIZE, 0, stream>>>(vx, y, k);
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);
}
}
@@ -673,6 +703,13 @@ 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,6 +31,12 @@ 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>) {
+19 -4
View File
@@ -1373,8 +1373,16 @@ void launch_fattn(
GGML_ASSERT(f16_extra.K != 0);
half * K_f16 = (half *) f16_extra.K;
if (ggml_is_contiguously_allocated(K)) {
to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(K->type);
to_fp16(K_data, K_f16, ggml_nelements(K), main_stream);
// 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);
}
nb11 = nb11*bs*sizeof(half)/ts;
nb12 = nb12*bs*sizeof(half)/ts;
@@ -1407,8 +1415,15 @@ void launch_fattn(
GGML_ASSERT(f16_extra.V != 0);
half * V_f16 = (half *) f16_extra.V;
if (ggml_is_contiguously_allocated(V)) {
to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(V->type);
to_fp16(V_data, V_f16, ggml_nelements(V), main_stream);
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);
}
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] += __half2float(tile_mask[j*(nbatch_fa + 8) + i]);
KQ_C[i00/(np*T_C_KQ::J)].x[l] += slope*__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 || ncols2 == 1 || DKQ > 256) {
if (ncols1*ncols2 < 16 || DKQ > 256) {
NO_DEVICE_CODE;
return;
}
+6
View File
@@ -860,6 +860,12 @@ 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)) {
+13 -3
View File
@@ -91,6 +91,7 @@ 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,
@@ -118,6 +119,8 @@ 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
@@ -148,6 +151,9 @@ 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;
}
@@ -478,7 +484,11 @@ 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) {
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;
}
switch (ncols_dst) {
case 1:
case 2:
@@ -641,7 +651,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_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_PASCAL_DP4A || 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) {
@@ -650,7 +660,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_RDNA1) && mmvq_two_rows_ncols1(type) ? 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;
case 2:
case 3:
case 4:
+25 -9
View File
@@ -135,7 +135,11 @@ 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) {
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) {
ggml_cuda_pdl_lc();
const int i = blockDim.x*blockIdx.x + threadIdx.x;
@@ -149,17 +153,25 @@ static __global__ void unary_op_kernel_strided(const T * x, T * dst, const int k
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 T * src_ptr = (const T *)((const char *)x + src_byte_offset);
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);
ggml_cuda_pdl_sync();
dst[i] = ggml_cuda_cast<T>(op(ggml_cuda_cast<float>(*src_ptr)));
*dst_ptr = 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, 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,
const size_t nb0, const size_t nb1, const size_t nb2, const size_t nb3,
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);
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);
}
template <float (*op)(float)>
@@ -172,8 +184,9 @@ 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)) {
if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) {
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) {
@@ -185,15 +198,18 @@ 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], stream);
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);
} 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], stream);
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);
} 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], stream);
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);
}
}
}
@@ -25,32 +25,11 @@
#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 + sync counters).
// L2 SCP layout per minion (double-buffered dequant panel).
// 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_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;
}
}
}
#define SCP_PANEL_SIZE (BLOCK_K * TILE_M * (uint64_t) sizeof(float)) // 2048
#define SCP_PER_MINION (2 * SCP_PANEL_SIZE) // 4096
// 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].
@@ -192,22 +171,17 @@ 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 + sync.
// L2 SCP pointers for this minion's double-buffered panels.
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;
@@ -229,22 +203,28 @@ 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: wait for hart 0 to finish with this buffer.
// Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers).
if (chunk_id >= 2) {
scp_wait(consumed_ctr, chunk_id - 1);
et_sem_wait(ET_BARRIER_MINION);
}
dequant_q4_0_panel(scp_panel[buf], src0_batch, mb, kb, nb1_0);
FENCE;
flush_to_l2(scp_panel[buf], BLOCK_K, 64);
flush_to_l2_multi(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;
}
@@ -261,11 +241,6 @@ 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;
@@ -307,8 +282,7 @@ 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.
chunk_id++;
scp_wait(ready_ctr, chunk_id);
et_sem_wait(ET_BARRIER_MINION);
// Two FMA passes over the 32-wide block (16 K-cols each).
for (int half = 0; half < 2; ++half) {
@@ -337,7 +311,8 @@ int entry_point(struct ggml_et_binary_params * params, void * env) {
}
// Signal that this buffer is free for hart 1 to reuse.
scp_signal(consumed_ctr, chunk_id);
et_sem_post(ET_BARRIER_MINION);
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: monotonic counters in L2 SCP with evict-based coherency.
// Sync: FCC 0 semaphores (et_sem_post / et_sem_wait).
// Double-buffered bpanel allows pack/FMA overlap.
//
#define NUM_COMPUTE_SHIRES 32
@@ -28,34 +28,11 @@
typedef uint16_t et_fp16_t;
// L2 SCP layout per minion (double-buffered bpanel + sync counters)
// L2 SCP layout per minion (double-buffered bpanel)
// [0..1023] bpanel buffer 0 (16 lines x 64 bytes)
// [1024..2047] bpanel buffer 1
// [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;
}
}
}
#define SCP_BPANEL_SIZE (16 * 32 * sizeof(et_fp16_t)) // 1024 bytes
#define SCP_PER_MINION (2 * SCP_BPANEL_SIZE) // 2048 bytes
/**
* Build the interleaved B panel that TensorFMA16A32 expects (vectorized).
@@ -170,23 +147,17 @@ 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 + sync
// L2 SCP pointers for this minion's double-buffered panels
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;
@@ -208,9 +179,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: wait for hart 0 to finish with this buffer
// Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers).
if (chunk_id >= 2) {
scp_wait(consumed_ctr, chunk_id - 1);
et_sem_wait(ET_BARRIER_MINION);
}
pack_b_interleaved(scp_bp[buf], src0_batch, mb, kb, nb1_0);
@@ -219,11 +190,17 @@ 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;
}
@@ -240,12 +217,6 @@ 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;
@@ -282,8 +253,7 @@ 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
chunk_id++;
scp_wait(ready_ctr, chunk_id);
et_sem_wait(ET_BARRIER_MINION);
// 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);
@@ -298,7 +268,8 @@ 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
scp_signal(consumed_ctr, chunk_id);
et_sem_post(ET_BARRIER_MINION);
chunk_id++;
}
// K-split ring reduce
@@ -476,6 +476,23 @@ 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
+9 -2
View File
@@ -22,11 +22,18 @@
#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_LUT_BYTES (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_GRID_BYTES)
#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_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_LUT_BYTES] = {
static const uint8_t __attribute__((aligned(128))) htp_iq2xxs_lut[HTP_IQ2XXS_TABLE_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,
+6 -3
View File
@@ -183,7 +183,8 @@ 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_NIBBLE_BYTES;
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);
// 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);
@@ -194,8 +195,10 @@ 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)));
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);
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);
return Q6_V_hi_W(p);
}
+21 -1
View File
@@ -38,10 +38,30 @@ 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) {
for (uint32_t i = 0; i < HTP_IQ2XXS_LUT_BYTES / VLEN; i++) {
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++) {
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;
}
+31 -18
View File
@@ -28,6 +28,9 @@
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;
@@ -1109,6 +1112,33 @@ 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));
@@ -1145,24 +1175,7 @@ ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) {
dev->props.has_bfloat = false;
}
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;
}
dev->props.has_tensor = ggml_metal_has_tensor(dev->mtl_device);
// double-check that the tensor API compiles
if (dev->props.has_tensor) {
+81 -43
View File
@@ -870,7 +870,8 @@ 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;
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_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;
@@ -1172,6 +1173,7 @@ 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;
@@ -4693,8 +4695,12 @@ 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 = 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(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
@@ -5192,6 +5198,7 @@ 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));
@@ -12829,7 +12836,8 @@ 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->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]);
return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
op->src[0]->type == op->type && ggml_is_contiguous_rows(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;
@@ -12846,6 +12854,8 @@ 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) &&
@@ -21893,6 +21903,7 @@ 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
@@ -39863,54 +39874,75 @@ 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);
GGML_ASSERT(src0->extra);
GGML_ASSERT(dst);
GGML_ASSERT(dst->extra);
GGML_ASSERT(src0 && src0->extra);
GGML_ASSERT(dst && dst->extra);
GGML_UNUSED(src1);
GGML_ASSERT(ggml_is_contiguous(src0));
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_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;
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;
cl_kernel kernel;
int n = ggml_nelements(dst);
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;
}
if (n % 4 == 0) {
kernel = backend_ctx->kernel_scale_f32_4;
n /= 4;
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);
} else {
kernel = backend_ctx->kernel_scale_f32;
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);
}
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) {
@@ -41859,6 +41891,12 @@ 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;
+96 -18
View File
@@ -1,27 +1,105 @@
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
kernel void kernel_scale_f32(
global float * src0,
ulong offset0,
global float * dst,
ulong offsetd,
float scale,
float bias
global const float * src0,
ulong offset0,
global float * dst,
ulong offsetd,
float scale,
float 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;
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;
}
kernel void kernel_scale_f32_4(
global float4 * src0,
ulong offset0,
global float4 * dst,
ulong offsetd,
float scale,
float bias
global const float4 * src0,
ulong offset0,
global float4 * dst,
ulong offsetd,
float scale,
float 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;
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);
}
}
@@ -74,6 +74,7 @@ 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,8 +614,15 @@ 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,6 +234,13 @@ 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
@@ -971,6 +978,7 @@ 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;
@@ -988,6 +996,7 @@ 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];
@@ -1070,6 +1079,8 @@ 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;
+71 -3
View File
@@ -1,5 +1,9 @@
#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();
@@ -576,6 +580,45 @@ 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) {
@@ -877,7 +920,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, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, NUM_DESCRIPTOR_BINDINGS * 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));
}
@@ -888,6 +931,15 @@ 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++;
@@ -4056,6 +4108,8 @@ 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);
@@ -4127,6 +4181,7 @@ 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);
@@ -5677,7 +5732,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 < MAX_PARAMETER_COUNT; i++) {
for (uint32_t i = 0; i < NUM_DESCRIPTOR_BINDINGS; i++) {
dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
dsl_binding_flags.push_back({});
}
@@ -5719,6 +5774,8 @@ 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),
@@ -10566,9 +10623,15 @@ 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;
@@ -10630,6 +10693,9 @@ 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;
@@ -12891,7 +12957,8 @@ void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const g
m0, m1,
n_head_log2,
nrows_x,
src2 != nullptr
src2 != nullptr,
0, 0, 0, 0,
};
if (ncols <= 16384) {
@@ -18417,6 +18484,7 @@ 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,6 +84,7 @@ 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
@@ -103,7 +104,8 @@ shared vec2 buf_a_dm[BM * BK_STEP]; // .x = d, .y = m
shared float buf_a_d[BM * BK_STEP * KSCALES];
#endif
shared uint32_t buf_b_qs[BN * QPITCH];
// uvec4 so that the B stores and fragment loads move 16 bytes per access
shared uvec4 buf_b_qs[BN * QPITCH / 4];
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)
@@ -124,7 +126,8 @@ shared int8_t cm1_kvalues[16];
const uint CM_ELEMS = (TM * TN) / WARP;
#define ACC_BIAS_BITS 0x4B400000
#define ACC_BIAS_F 12582912.0f
const bool USE_MAGIC_BIAS = WARP != 32;
// 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)
// Accumulator row for element e: RDNA4 blocked, RDNA3/3.5 interleaved.
uint cm_elem_row(uint e) {
@@ -132,13 +135,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 (0 for symmetric types).
// min_term = asymmetric-quant min*b_sum correction; pass -0.0 for symmetric types so prev + min_term folds away.
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 prev + ACC_TYPE(fma(float(acc_e) * scale_a, scale_b, min_term));
return ACC_TYPE(fma(float(acc_e) * scale_a, scale_b, float(prev) + min_term));
}
#ifdef MUL_MAT_ID
@@ -319,7 +322,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), QPITCH, gl_CooperativeMatrixLayoutColumnMajor);
coopMatLoad(cache_b, buf_b_qs, ((b_col0 + c * TN) * QPITCH + ks * (BK / 4) + h * (TK / 4)) / 4, QPITCH / 4, gl_CooperativeMatrixLayoutColumnMajor);
const float scale_b_v = buf_b_d[ks * BN + b_col0 + c * TN + elem_col0];
@@ -332,7 +335,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);
}
}
}
@@ -349,7 +352,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), QPITCH, gl_CooperativeMatrixLayoutColumnMajor);
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);
}
}
@@ -402,7 +405,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), QPITCH, gl_CooperativeMatrixLayoutColumnMajor);
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);
}
}
@@ -434,7 +437,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,11 +528,7 @@ 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);
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;
buf_b_qs[(buf_ib * QPITCH + ks * (BK / 4)) / 4 + loadr] = uvec4(v);
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)
@@ -0,0 +1,94 @@
#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);
}
}
}
@@ -0,0 +1,35 @@
#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,6 +1059,8 @@ 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"}}));
@@ -1093,6 +1095,7 @@ 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"}});
+50
View File
@@ -653,6 +653,7 @@ class MODEL_ARCH(IntEnum):
QWEN35MOE = auto()
CLEF = auto()
VLLM_DECISION2 = auto()
CLEF_OMNI = auto()
CLOVER_MOE = auto()
QWEN4EXP = auto()
PHI2 = auto()
@@ -1684,6 +1685,7 @@ 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",
@@ -3775,6 +3777,53 @@ 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,
@@ -7654,6 +7703,7 @@ 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:
+2
View File
@@ -45,6 +45,7 @@ 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" },
@@ -1655,6 +1656,7 @@ bool llama_arch_supports_save(llm_arch arch) {
case LLM_ARCH_T5:
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;
+1
View File
@@ -48,6 +48,7 @@ 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,
+4
View File
@@ -373,6 +373,8 @@ 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:
@@ -3044,6 +3046,7 @@ 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:
{
@@ -3977,6 +3980,7 @@ 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;
+7 -1
View File
@@ -528,7 +528,13 @@ 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) { throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); }
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 (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)); }
}
+96
View File
@@ -0,0 +1,96 @@
#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;
}
+92 -72
View File
@@ -5,9 +5,7 @@
#include <algorithm>
#include <cmath>
void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
llama_model_qwen35::load_arch_hparams(ml);
void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hparams) {
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);
@@ -23,10 +21,18 @@ void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
hparams.n_embd_out_impl = 1;
}
void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
llama_model_qwen35::load_arch_tensors(ml);
void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
llama_model_qwen35::load_arch_hparams(ml);
head.load_hparams(ml, hparams);
}
LLAMA_LOAD_LOCALS;
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);
};
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());
@@ -82,10 +88,10 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
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, n_vocab}, TENSOR_NOT_REQUIRED);
output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, model.vocab.n_tokens()}, model.TENSOR_NOT_REQUIRED);
if (output_lexical == nullptr) {
output_lexical = tok_embd;
output_lexical = model.tok_embd;
}
proj_memory = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight"), {n_embd, n_embd_h}, 0);
@@ -104,6 +110,11 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
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);
}
@@ -185,7 +196,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_model_clef::input_decision : public llm_graph_input_i {
class llama_clef_head::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)) {}
@@ -277,11 +288,7 @@ llama_model_clef::graph::graph(const llm_graph_params & params) :
ggml_tensor * inp_pos = build_inp_pos();
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));
auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this);
for (int il = 0; il < n_layer; ++il) {
ggml_tensor * inpSA = inpL;
@@ -321,16 +328,9 @@ 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 = 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);
cur = model.head.build(*this, cur);
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_model_clef::graph::build_attn_inp_causal() {
auto inp = std::make_unique<llm_graph_input_attn_clef>(hparams, cparams);
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);
const auto type_mask = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32;
const auto type_mask = ctx.cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32;
inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx0, type_mask, GGML_PAD(n_tokens, 256), n_tokens, 1, 1);
inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx.ctx0, type_mask, GGML_PAD(ctx.n_tokens, 256), ctx.n_tokens, 1, 1);
ggml_set_input(inp->self_attn_mask.raw);
cb(inp->self_attn_mask.raw, "self_kq_mask", -1);
ctx.cb(inp->self_attn_mask.raw, "self_kq_mask", -1);
return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp));
return (llm_graph_input_attn_no_cache *) ctx.res->add_input(std::move(inp));
}
ggml_tensor * llama_model_clef::graph::build_layer_attn(
@@ -496,21 +496,23 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear(
return ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
}
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);
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);
}
// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null
ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) {
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;
const int64_t n_embd_h = q->ne[0];
const int64_t n_head_h = model.n_head_decision;
const int64_t n_head_h = 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, 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);
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);
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]
@@ -523,18 +525,29 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten
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, build_lora_mm(a.wo, cur), a.bo);
return ggml_add(ctx0, ctx.build_lora_mm(a.wo, cur), a.bo);
}
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);
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);
cur = ggml_gelu_erf(ctx0, cur);
return ggml_add(ctx0, build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b);
return ggml_add(ctx0, ctx.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_model_clef::graph::build_head(ggml_tensor * hidden, input_decision * inp) {
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));
const int64_t n_questions = inp->n_questions;
const int64_t n_options = inp->n_options;
@@ -550,9 +563,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
ggml_set_input(t);
}
hidden = build_head_norm(hidden, model.hidden_norm);
hidden = build_head_norm(ctx, hidden, hidden_norm);
ggml_tensor * memory = build_lora_mm(model.proj_memory, hidden); // [n_embd_h, n_tokens]
ggml_tensor * memory = ctx.build_lora_mm(proj_memory, hidden); // [n_embd_h, n_tokens]
const int64_t n_embd_h = memory->ne[0];
@@ -565,29 +578,29 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
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, model.output_lexical, inp->tokens);
ggml_tensor * lexical = ggml_get_rows(ctx0, 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 = 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));
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));
// the options read the prompt
for (uint32_t il = 0; il < model.n_layer_routing; ++il) {
const auto & layer = model.head_layers[il];
for (uint32_t il = 0; il < n_layer_routing; ++il) {
const auto & layer = head_layers[il];
ggml_tensor * cur = build_head_attn(
build_head_norm(options, layer.cross_norm),
build_head_norm(memory, layer.cross_norm_kv),
ggml_tensor * cur = build_head_attn(ctx,
build_head_norm(ctx, options, layer.cross_norm),
build_head_norm(ctx, memory, layer.cross_norm_kv),
layer.cross_attn);
options = ggml_add(ctx0, options, cur);
options = ggml_add(ctx0, options, build_head_ffn(options, layer));
options = ggml_add(ctx0, options, build_head_ffn(ctx, options, layer));
}
cb(options, "decision_options", -1);
ctx.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 = build_lora_mm(model.proj_question, question); // [n_embd_h, n_questions]
ggml_tensor * fields = ctx.build_lora_mm(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]
@@ -596,25 +609,25 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
ggml_tensor * summary = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, options)), weights);
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));
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));
}
// the questions read each other and the prompt
for (uint32_t il = model.n_layer_routing; il < model.head_layers.size(); ++il) {
const auto & layer = model.head_layers[il];
for (uint32_t il = n_layer_routing; il < head_layers.size(); ++il) {
const auto & layer = head_layers[il];
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));
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));
cur = build_head_norm(fields, layer.cross_norm);
fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn));
cur = build_head_norm(ctx, fields, layer.cross_norm);
fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, memory, layer.cross_attn));
fields = ggml_add(ctx0, fields, build_head_ffn(fields, layer));
fields = ggml_add(ctx0, fields, build_head_ffn(ctx, fields, layer));
}
fields = build_head_norm(fields, model.field_norm);
cb(fields, "decision_fields", -1);
fields = build_head_norm(ctx, fields, field_norm);
ctx.cb(fields, "decision_fields", -1);
const float eps = 1e-12f;
@@ -624,7 +637,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
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(options, model.option_norm);
options = build_head_norm(ctx, options, 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)));
@@ -633,15 +646,22 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
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, build_lora_mm(model.scorer, features), model.scorer_b);
ggml_tensor * residual = ggml_add(ctx0, ctx.build_lora_mm(scorer, features), scorer_b);
residual = ggml_gelu_erf(ctx0, residual);
residual = ggml_add(ctx0, build_lora_mm(model.scorer_out, residual), model.scorer_out_b); // [1, n_options]
residual = ggml_add(ctx0, ctx.build_lora_mm(scorer_out, residual), scorer_out_b); // [1, n_options]
auto scale = [&](int i) {
return ggml_view_1d(ctx0, model.scales, 1, i * ggml_element_size(model.scales));
return ggml_view_1d(ctx0, scales, 1, i * ggml_element_size(scales));
};
ggml_tensor * joint = ggml_add(ctx0, ggml_mul(ctx0, cosine, scale(1)), residual);
return ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2)));
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;
}
+45 -17
View File
@@ -701,6 +701,8 @@ 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;
};
@@ -3004,12 +3006,8 @@ struct llama_model_qwen35 : public llama_model_base {
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
// 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;
// joint decision head of clef, on top of the final hidden states of a backbone evaluated without memory
struct llama_clef_head {
struct attn {
ggml_tensor * wq = nullptr;
ggml_tensor * bq = nullptr;
@@ -3058,6 +3056,7 @@ struct llama_model_clef : public llama_model_qwen35 {
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;
@@ -3066,11 +3065,33 @@ struct llama_model_clef : public llama_model_qwen35 {
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,
@@ -3081,15 +3102,6 @@ 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;
};
@@ -3097,6 +3109,22 @@ 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) {}
+8 -4
View File
@@ -20,10 +20,14 @@ void llama_model_qwen3vlmoe::load_arch_tensors(llama_model_loader &) {
// 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}, 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);
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);
}
}
for (int i = 0; i < n_layer; ++i) {
+1
View File
@@ -4,6 +4,7 @@ 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
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
7 apertus ,0 ,any ,RMS_NORM+MUL , 9
8 arcee ,0 ,any ,RMS_NORM+MUL , 5
9 arctic ,1 ,any ,MUL+ADD , 4
10 arctic ,1 ,any ,RMS_NORM+MUL , 7
+16 -6
View File
@@ -2160,9 +2160,10 @@ 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_STR3(type, ne_a, v);
return VARS_TO_STR4(type, ne_a, v, inplace);
}
double max_nmse_err(ggml_backend_t backend) override {
@@ -2177,13 +2178,14 @@ 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)
: op(op), type(type), ne_a(ne_a), v(v) {}
int v = 0,
bool inplace = false)
: op(op), type(type), ne_a(ne_a), v(v), inplace(inplace) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
const bool grad_supported = op == GGML_UNARY_OP_ABS || op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_NEG ||
const bool grad_supported = !inplace && (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) {
@@ -2208,7 +2210,7 @@ struct test_unary : public test_case {
ggml_set_name(a, "a");
}
ggml_tensor * out = ggml_unary(ctx, a, op);
ggml_tensor * out = inplace ? ggml_unary_inplace(ctx, a, op) : ggml_unary(ctx, a, op);
ggml_set_name(out, "out");
return out;
@@ -12070,7 +12072,11 @@ 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));
@@ -15074,6 +15080,8 @@ 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
@@ -16059,6 +16067,8 @@ 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}) {
+14 -2
View File
@@ -30,6 +30,7 @@ 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,
@@ -44,6 +45,7 @@ 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,
@@ -71,6 +73,7 @@ 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";
@@ -85,6 +88,7 @@ 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";
@@ -302,9 +306,12 @@ 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);
const std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY
std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY
? ""
: "my_key_" + std::to_string((hft == HANDCRAFTED_KV_DUPLICATE_KEY ? i/2 : i));
: "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);
}
if (hft == HANDCRAFTED_KV_BAD_KEY_SIZE) {
const uint64_t n = -1;
@@ -401,6 +408,9 @@ 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);
}
@@ -773,6 +783,7 @@ 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,
@@ -787,6 +798,7 @@ 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,
+79
View File
@@ -435,6 +435,62 @@ 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}}}},
@@ -962,6 +1018,29 @@ 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(),
+2 -1
View File
@@ -1184,6 +1184,7 @@ 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:
@@ -1297,7 +1298,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_VLLM_DECISION2) {
if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_CLEF_OMNI || arch == LLM_ARCH_VLLM_DECISION2) {
return false; // TODO decision head tensors
}
if (arch == LLM_ARCH_DEEPSEEK2OCR) {
+120
View File
@@ -773,6 +773,40 @@ 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
//
@@ -798,6 +832,90 @@ 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
//
@@ -992,7 +1110,9 @@ int main(int argc, char ** argv) {
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);
+12 -8
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. Default: `1.1`
`repeat_penalty`: Control the repetition of token sequences in the generated text (alias: `repetition_penalty`). 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 (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 (alias: `repetition_penalty`, 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,6 +1932,8 @@ 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`.
@@ -1941,11 +1943,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, 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 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 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.
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.
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"]`.
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"]`.
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.
@@ -1953,14 +1955,16 @@ 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, 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, cloudflare-clef-omni, 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 alias `images`.
- The `files` field, or its aliases `images` and `audio`.
- 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` and `images` first. The image parts are removed from the state.
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.
*Response:*
+1
View File
@@ -241,6 +241,7 @@ 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 -1
View File
@@ -5713,7 +5713,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", "speed", "loudness", "cfg_scale" }) {
for (const char * k : { "top_p", "temperature", "repeat_penalty", "repetition_penalty", "speed", "loudness", "cfg_scale" }) {
if (body.contains(k) && body[k].is_string()) {
body[k] = std::stof(body[k].get<std::string>());
}
+46 -8
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) {
} else if (model_type == COMMON_DECISION_TYPE_CLEF || model_type == COMMON_DECISION_TYPE_CLEF_OMNI) {
n_options_max = 255;
noul_true_first = true;
choice_sorted = true;
@@ -410,6 +410,40 @@ 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");
@@ -417,8 +451,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" is an alias of "files"
for (const char * key : {"files", "images"}) {
// "images" and "audio" are aliases of "files"
for (const char * key : {"files", "images", "audio"}) {
if (!body.contains(key) || body.at(key).is_null()) {
continue;
}
@@ -1553,11 +1587,15 @@ void server_decision_context::fill_task_joint(
};
inp = decision_replace_text(decision_sort_keys(inp), CLEF_MARKER, "<<clef ");
// the template puts one media marker per image
// 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
json images = json::array();
if (!files.empty()) {
if (!media.empty()) {
inp = decision_replace_text(inp, get_media_marker(), " ");
for (size_t i = 0; i < files.size(); i++) {
for (size_t i = 0; i < media.size(); i++) {
images.push_back(get_media_marker());
}
}
@@ -1579,7 +1617,7 @@ void server_decision_context::fill_task_joint(
size_t i_piece = 0;
task.tokens = server_tokens(llama_tokens(), false);
if (!files.empty()) {
if (!media.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) {
@@ -1588,7 +1626,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, files, init_opt);
task.tokens = process_mtmd_prompt(mctx, head, media, init_opt);
task.decision.order.resize(task.tokens.size(), LLAMA_DECISION_ORDER_NONE);
}
+7 -2
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;
return type == COMMON_DECISION_TYPE_CLEF || type == COMMON_DECISION_TYPE_CLEF_OMNI;
}
bool is_lfm3_d1() const {
@@ -76,6 +76,7 @@ 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;
@@ -96,7 +97,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" (alias "images") and from the image_url and input_audio parts of a state made of chat messages
// images come from "files" (aliases "images" and "audio") 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;
@@ -207,5 +208,9 @@ 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);
+2
View File
@@ -130,6 +130,7 @@ 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))
@@ -574,6 +575,7 @@ 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))
@@ -8,6 +8,7 @@
ChatAttachmentsList,
ChatFormActions,
ChatFormActionsRecording,
ChatFormBackgroundTasks,
ChatFormCurrentWorkingDirectory,
ChatFormInput,
ChatFormInputFileInputInvisible,
@@ -90,6 +91,8 @@
isLoading?: boolean;
placeholder?: string;
showAddButton?: boolean;
/** List the conversation's background tasks under the form; one form on the page does. */
showBackgroundTasks?: boolean;
showModelSelector?: boolean;
/** Writing the system message: the form takes the system message's dashed, muted look. */
systemMode?: boolean;
@@ -124,6 +127,7 @@
onValueChange,
placeholder = 'Type a message...',
showAddButton = true,
showBackgroundTasks = false,
showModelSelector = true,
singleRow = false,
systemMode = false,
@@ -1012,6 +1016,10 @@
{#if systemMessageChip}
<ChatFormSystemMessageChip content={systemMessageChip} {disabled} />
{/if}
{#if showBackgroundTasks}
<ChatFormBackgroundTasks />
{/if}
</div>
</form>
@@ -0,0 +1,113 @@
<script lang="ts">
// One background task in the dialog: its description and a Stop action, above the same
// terminal block as a shell tool call, collapsed, with what the task printed inside.
import { Button } from '@ggml-org/llama-ui/ui/button';
import { Square } from '@lucide/svelte';
import { CollapsibleTerminalBlock, ShellPromptLine } from '#lib/components/app/index.ts';
import {
BACKGROUND_TASK_NO_OUTPUT_LABEL,
BACKGROUND_TASK_SKIPPED_LABEL,
BACKGROUND_TASK_STOP_ARIA_LABEL,
BACKGROUND_TASK_STOP_LABEL,
MS_PER_SECOND,
TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX
} from '#lib/constants/index.ts';
import { backgroundTasksStore } from '#lib/stores/index.ts';
import type { BackgroundTask } from '#lib/types/index.ts';
import { formatRelativeTime } from '#lib/utils/index.ts';
interface Props {
task: BackgroundTask;
}
let { task }: Props = $props();
const log = $derived(backgroundTasksStore.log(task.id));
let open = $state(false);
let stopping = $state(false);
let logEl: HTMLPreElement | undefined = $state();
// the output follows its end as it grows, until the user scrolls up to read
let pinned = true;
// the output is read only while the block is open: the store reads what is new each time the
// server says the task printed
$effect(() => {
if (!open) return;
return backgroundTasksStore.watchOutput(task.id);
});
$effect(() => {
void log.text;
if (!pinned) return;
requestAnimationFrame(() => {
if (logEl) logEl.scrollTop = logEl.scrollHeight;
});
});
function handleScroll() {
if (!logEl) return;
pinned =
logEl.scrollHeight - logEl.scrollTop - logEl.clientHeight <=
TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX;
}
async function stop(event: MouseEvent) {
event.stopPropagation();
stopping = true;
try {
await backgroundTasksStore.stop(task.id);
} finally {
stopping = false;
}
}
</script>
<div class="grid gap-2" data-background-task={task.id}>
<div class="flex items-center gap-2">
<span class="min-w-0 flex-1 truncate text-body-sm font-medium">
{task.description || task.command}
</span>
<Button
aria-label={BACKGROUND_TASK_STOP_ARIA_LABEL}
disabled={stopping}
onclick={stop}
size="xs"
variant="danger-secondary"
>
<Square />
{BACKGROUND_TASK_STOP_LABEL}
</Button>
</div>
<CollapsibleTerminalBlock bind:open>
{#snippet titleSnippet()}
<ShellPromptLine command={task.command} cwd={task.cwd} singleLine />
{/snippet}
<div class="grid gap-2">
<div class="font-mono text-caption text-muted-foreground">
task {task.id} · started
{formatRelativeTime(task.started_at * MS_PER_SECOND)}
</div>
{#if log.skipped > 0}
<div class="font-mono text-caption text-muted-foreground">
{BACKGROUND_TASK_SKIPPED_LABEL(log.skipped)}
</div>
{/if}
<pre
bind:this={logEl}
class="max-h-80 overflow-auto font-mono text-caption leading-relaxed whitespace-pre-wrap"
onscroll={handleScroll}>{log.text || BACKGROUND_TASK_NO_OUTPUT_LABEL}</pre>
</div>
</CollapsibleTerminalBlock>
</div>
@@ -0,0 +1,77 @@
<script lang="ts">
// The chip under the chat form that counts the commands llama-server keeps running for this
// conversation (dev servers, watchers, builds), and the dialog it opens to read and stop them.
import ChatFormBackgroundTaskRow from './ChatFormBackgroundTaskRow.svelte';
import { Button } from '@ggml-org/llama-ui/ui/button';
import { Chip } from '@ggml-org/llama-ui/ui/chip';
import * as Dialog from '@ggml-org/llama-ui/ui/dialog';
import { SquareTerminal, X } from '@lucide/svelte';
import {
BACKGROUND_TASKS_DIALOG_DESCRIPTION,
BACKGROUND_TASKS_DIALOG_TITLE,
BACKGROUND_TASKS_EMPTY_LABEL,
BACKGROUND_TASKS_RUNNING_LABEL,
BACKGROUND_TASKS_STOP_ALL_LABEL
} from '#lib/constants/index.ts';
import { backgroundTasksStore as store, conversationsStore } from '#lib/stores/index.ts';
// a hidden tab lets go of its event stream: a browser only opens a few connections to one
// server, across all of its tabs
let hidden = $state(globalThis.document?.hidden ?? false);
// derived, so the stream is opened again only when one of the two really changes
const conversationId = $derived(conversationsStore.activeConversation?.id ?? '');
const follow = $derived(store.available && !hidden);
$effect(() => store.watch(conversationId, follow));
const count = $derived(store.tasks.length);
</script>
<svelte:document onvisibilitychange={() => (hidden = document.hidden)} />
{#if store.available && count > 0}
<Chip class="mt-1.5" data-background-tasks-chip onclick={() => (store.dialogOpen = true)}>
<SquareTerminal />
<span class="truncate">{BACKGROUND_TASKS_RUNNING_LABEL(count)}</span>
</Chip>
{/if}
<Dialog.Root bind:open={store.dialogOpen}>
<Dialog.Content
class="flex max-h-[calc(100vh-4rem)] flex-col gap-0 p-0 md:w-[calc(100vw-4rem)]! md:max-w-3xl!"
>
<Dialog.Header
class="flex-row items-center gap-2 border-b border-border/40 p-4"
showCloseButton={false}
>
<Dialog.Title class="text-body-sm font-semibold">{BACKGROUND_TASKS_DIALOG_TITLE}</Dialog.Title
>
{#if count > 1}
<Button onclick={() => void store.stopAll()} size="xs" variant="secondary">
{BACKGROUND_TASKS_STOP_ALL_LABEL}
</Button>
{/if}
<Dialog.Close
aria-label="Close"
class="ml-auto inline-flex cursor-pointer items-center justify-center rounded-md p-1.5 text-muted-foreground/70 transition-colors hover:bg-muted-foreground/10 hover:text-foreground"
type="button"
>
<X class="size-icon-md" />
</Dialog.Close>
</Dialog.Header>
<Dialog.Description class="sr-only">{BACKGROUND_TASKS_DIALOG_DESCRIPTION}</Dialog.Description>
<div class="grid gap-5 overflow-y-auto p-4">
{#each store.tasks as task (task.id)}
<ChatFormBackgroundTaskRow {task} />
{:else}
<p class="text-body-sm text-muted-foreground">{BACKGROUND_TASKS_EMPTY_LABEL}</p>
{/each}
</div>
</Dialog.Content>
</Dialog.Root>
@@ -1,4 +1,5 @@
<script lang="ts">
import { Chip } from '@ggml-org/llama-ui/ui/chip';
import { MessageSquareText } from '@lucide/svelte';
import { DialogSystemMessageEdit } from '#lib/components/app/index.ts';
import { SYSTEM_MESSAGE_PLACEHOLDER } from '#lib/constants/index.ts';
@@ -19,17 +20,11 @@
{#if hasContent}
<div class="grid">
<button
class="mt-1.5 flex w-auto min-w-0 items-center gap-1 rounded-md px-2 py-1 text-caption text-muted-foreground backdrop-blur-2xl hover:text-foreground"
{disabled}
onclick={() => (isOpen = true)}
title={content}
type="button"
>
<MessageSquareText class="size-icon-sm" />
<Chip class="mt-1.5" {disabled} onclick={() => (isOpen = true)} title={content}>
<MessageSquareText />
<span class="truncate">Custom system message</span>
</button>
</Chip>
</div>
<DialogSystemMessageEdit
@@ -9,16 +9,26 @@
import { parseExecShellCommandMeta } from './parsers/exec-shell-command';
import ToolCallBlock from './ToolCallBlock.svelte';
import { AlertTriangle, Check, CircleStop, Loader2, XCircle } from '@lucide/svelte';
import { Button } from '@ggml-org/llama-ui/ui/button';
import {
AlertTriangle,
Check,
CircleStop,
Loader2,
SquareArrowDown,
XCircle
} from '@lucide/svelte';
import { ShellPromptLine } from '#lib/components/app/index.ts';
import {
BACKGROUND_TASK_DETACH_LABEL,
BACKGROUND_TASK_DETACH_TITLE,
SETTINGS_KEYS,
TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX
} from '#lib/constants/index.ts';
import { AgenticSectionType, AttachmentType } from '#lib/enums/index.ts';
import { settingsStore, toolsStore } from '#lib/stores/index.ts';
import { backgroundTasksStore, settingsStore } from '#lib/stores/index.ts';
import type { AgenticSection, DatabaseMessageExtra, ToolResultLine } from '#lib/types/index.ts';
import {
abbreviateHome,
type ExecShellExitStatus,
highlightCode,
isExitCodeSummaryLine,
@@ -58,6 +68,27 @@
// is not live.
const isLive = $derived(isExecuting);
// a running command can move to the background: its call returns, the command goes on as a
// task of the conversation, listed under the chat form
const canDetach = $derived(
isLive && backgroundTasksStore.execIdOf(section.toolCallId) !== undefined
);
let detaching = $state(false);
async function detach(event: MouseEvent) {
event.stopPropagation();
if (!section.toolCallId) return;
detaching = true;
try {
await backgroundTasksStore.detach(section.toolCallId);
} finally {
detaching = false;
}
}
const isPreResult = $derived(
section.type === AgenticSectionType.TOOL_CALL_PENDING ||
section.type === AgenticSectionType.TOOL_CALL_STREAMING
@@ -107,8 +138,6 @@
const cwd = $derived(
section.toolCwd ?? (isStreaming && isPreResult ? conversationCwd : undefined)
);
const home = $derived(toolsStore.serverHome);
const wdDisplay = $derived(abbreviateHome(cwd ?? '', home));
const exitBadgeClass = $derived(
execShellExitStatus?.timedOut
@@ -213,24 +242,6 @@
});
</script>
{#snippet promptLine()}
{#if cwd}
<span class="exec-wd" title={cwd}>{wdDisplay}</span>
{/if}
<span class="exec-prompt">$</span>
{#if highlightedCommandHtml}
<span class="font-mono">{@html highlightedCommandHtml}</span>
{:else}
<span class="font-mono">{execShellMeta?.command}</span>
{/if}
{#if commandStreaming}
<span class="exec-cursor"></span>
{/if}
{/snippet}
<ToolCallBlock
emptyResultIsInterrupted
extraLiveStreaming={isLive}
@@ -266,7 +277,12 @@
{#snippet children(_meta, ctx)}
<div class="terminal-frame">
<div class="exec-prompt-line font-mono text-caption">
{@render promptLine()}
<ShellPromptLine
command={execShellMeta?.command ?? ''}
cursor={commandStreaming}
{cwd}
highlightedHtml={highlightedCommandHtml}
/>
</div>
{#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)}
@@ -334,40 +350,24 @@
{/snippet}
</ToolCallBlock>
<!-- outside the block, so it shows whether or not the block is open -->
{#if canDetach}
<div class="-mt-1 mb-2 flex">
<Button
data-detach-command
disabled={detaching}
onclick={detach}
size="xs"
title={BACKGROUND_TASK_DETACH_TITLE}
variant="secondary"
>
<SquareArrowDown />
{BACKGROUND_TASK_DETACH_LABEL}
</Button>
</div>
{/if}
<style>
:root {
--exec-wd-margin: 0.4rem;
}
.exec-wd {
font-family: var(--font-mono);
color: var(--fg-muted);
margin-right: var(--exec-wd-margin);
}
.exec-prompt {
font-family: var(--font-mono);
color: var(--fg-muted);
opacity: 0.55;
margin-right: var(--exec-wd-margin);
}
.exec-cursor {
display: inline-block;
width: 0.5em;
height: 1.05em;
margin-left: 0.15rem;
vertical-align: text-bottom;
background: var(--fg-default);
animation: exec-cursor-blink 1.1s steps(1) infinite;
}
@keyframes exec-cursor-blink {
50% {
opacity: 0;
}
}
.exec-title-command {
color: var(--fg-muted);
font-size: 0.92em;
@@ -387,10 +387,6 @@
word-break: break-word;
}
.exec-prompt-line :global(.font-mono) {
white-space: pre-wrap;
}
.terminal-output.is-clamped {
max-height: 28rem;
overflow-y: auto;
@@ -223,6 +223,7 @@
onSystemPromptClick={handleSystemPromptClick}
onUploadedFileRemove={handleUploadedFileRemove}
placeholder={isSystemMode ? 'System message...' : undefined}
showBackgroundTasks
singleRow={settingsStore.config[SETTINGS_KEYS.SINGLE_ROW_CHAT_FORM] !== false}
systemMode={isSystemMode}
/>
@@ -267,6 +267,7 @@ export { default as ChatFormInput } from './ChatForm/ChatFormInput/ChatFormInput
* synthetic "Set working directory to ..." user message into chat history
* and is enforced on tool calls via the `x-tool-cwd` request header.
*/
export { default as ChatFormBackgroundTasks } from './ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte';
export { default as ChatFormCurrentWorkingDirectory } from './ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte';
/**
@@ -0,0 +1,79 @@
<script lang="ts">
// The prompt line of a shell command, as a terminal shows it: the working directory with the
// home folder abbreviated, a dim `$`, then the command, highlighted when given its HTML.
import { toolsStore } from '#lib/stores/index.ts';
import { abbreviateHome } from '#lib/utils/index.ts';
interface Props {
command: string;
cwd?: string;
/** The command highlighted as bash, rendered instead of the plain text */
highlightedHtml?: string;
/** A blinking block after the command, while it is still being written */
cursor?: boolean;
/** Keep it on one line, cutting the command short, instead of wrapping it */
singleLine?: boolean;
}
let { command, cursor = false, cwd, highlightedHtml, singleLine = false }: Props = $props();
const cwdLabel = $derived(cwd ? abbreviateHome(cwd, toolsStore.serverHome) : '');
</script>
<span class={['shell-prompt-line font-mono', singleLine && 'flex min-w-0 items-baseline']}>
{#if cwd}
<span class="shell-cwd shrink-0" title={cwd}>{cwdLabel}</span>
{/if}
<span class="shell-dollar shrink-0">$</span>
<span class={['shell-command', singleLine ? 'min-w-0 truncate' : 'wrap']} title={command}>
{#if highlightedHtml}
{@html highlightedHtml}
{:else}
{command}
{/if}
</span>
{#if cursor}
<span class="shell-cursor"></span>
{/if}
</span>
<style>
.shell-prompt-line {
--shell-prompt-gap: 0.4rem;
--shell-dollar-opacity: 0.55;
}
.shell-cwd,
.shell-dollar {
color: var(--fg-muted);
margin-right: var(--shell-prompt-gap);
}
.shell-dollar {
opacity: var(--shell-dollar-opacity);
}
.shell-command.wrap {
white-space: pre-wrap;
word-break: break-word;
}
.shell-cursor {
display: inline-block;
width: 0.5em;
height: 1.05em;
margin-left: 0.15rem;
vertical-align: text-bottom;
background: var(--fg-default);
animation: shell-cursor-blink 1.1s steps(1) infinite;
}
@keyframes shell-cursor-blink {
50% {
opacity: 0;
}
}
</style>
@@ -126,6 +126,15 @@ export { default as CollapsibleContentBlock } from './CollapsibleContentBlock.sv
*/
export { default as CollapsibleTerminalBlock } from './CollapsibleTerminalBlock.svelte';
/**
* **ShellPromptLine** - A shell command as a terminal prompt shows it
*
* The working directory (home abbreviated), a dim `$` and the command, optionally
* highlighted and with a typing cursor. Shared by the shell tool call and the
* background tasks list so both read the same.
*/
export { default as ShellPromptLine } from './ShellPromptLine.svelte';
/**
* **MermaidPreview** - Pan and zoom viewer for a diagram's svg
*
@@ -24,6 +24,14 @@ export const API_TOOLS = {
LIST: '/tools'
};
// the background tasks of a conversation: `POST` moves a running command to the background,
// `DELETE` stops one, and both answer with the task they changed
export const API_TOOLS_TASKS = {
EVENTS: '/tools/tasks/events',
OUTPUT: '/tools/tasks/output',
TASKS: '/tools/tasks'
};
// resumable stream routes, the conv::model identity travels as the conv_id query param
// because model names can contain slashes that a path segment cannot carry
// resume retry cadence while the owning model is still loading (server answers 503)
@@ -0,0 +1,37 @@
// how long the task event stream waits before it reads again after it went away, doubling
// each time up to the maximum
export const BACKGROUND_TASKS_RETRY_MS = 1000;
export const BACKGROUND_TASKS_RETRY_MAX_MS = 15_000;
// how much of a task's output the chat keeps, the same as the server does: the front is
// dropped past it
export const BACKGROUND_TASK_LOG_MAX_LENGTH = 256 * 1024;
/** The background tasks dialog's title, and what it says while the conversation runs none */
export const BACKGROUND_TASKS_DIALOG_TITLE = 'Background tasks';
export const BACKGROUND_TASKS_EMPTY_LABEL = 'Nothing is running in the background.';
export const BACKGROUND_TASKS_DIALOG_DESCRIPTION =
'Commands llama-server keeps running for this conversation, with their output';
/** What an open task row shows before the task printed anything */
export const BACKGROUND_TASK_NO_OUTPUT_LABEL = 'No output yet';
/** Stopping a task, from its row or all of them at once */
export const BACKGROUND_TASK_STOP_LABEL = 'Stop';
export const BACKGROUND_TASK_STOP_ARIA_LABEL = 'Stop task';
export const BACKGROUND_TASK_STOP_FAILED = 'Could not stop the task';
export const BACKGROUND_TASKS_STOP_ALL_LABEL = 'Stop all';
/** Above an output only the end of was kept */
export const BACKGROUND_TASK_SKIPPED_LABEL = (bytes: number): string =>
`[${bytes} earlier bytes dropped]`;
/** The button under a running shell call that lets it go on as a background task */
export const BACKGROUND_TASK_DETACH_LABEL = 'Move to background';
export const BACKGROUND_TASK_DETACH_TITLE =
'Keep it running as a background task and let the agent go on';
export const BACKGROUND_TASK_DETACH_FAILED = 'Could not move the command to the background';
/** The chip's label: how many tasks the conversation runs */
export const BACKGROUND_TASKS_RUNNING_LABEL = (count: number): string =>
`${count} background ${count === 1 ? 'task' : 'tasks'}`;
+1
View File
@@ -4,6 +4,7 @@
export * from './agentic.constants';
export * from './api-endpoints.constants';
export * from './app.constants';
export * from './background-tasks.constants';
export * from './backend.constants';
export * from './chat-tabs.constants';
export * from './database.constants';
@@ -8,6 +8,7 @@
// ChatMessageToolCallBlockSearchResults for prior art).
import Braces from '@lucide/svelte/icons/braces';
import CircleDashed from '@lucide/svelte/icons/circle-dashed';
import Clock from '@lucide/svelte/icons/clock';
import Eye from '@lucide/svelte/icons/eye';
import FilePen from '@lucide/svelte/icons/file-pen';
@@ -38,6 +39,11 @@ export const TOOL_UI: Readonly<Record<BuiltInTool, ToolUiEntry>> = {
label: 'Search chats',
source: ToolSource.BROWSER
},
[BuiltInTool.SERVER_BACKGROUND_TASK]: {
icon: CircleDashed,
label: 'Background task',
source: ToolSource.SERVER
},
[BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER },
[BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: {
icon: Terminal,
+2
View File
@@ -121,6 +121,8 @@ export {
export { KeyboardKey } from './keyboard.enums';
export {
BackgroundTaskStatus,
BackgroundTasksServerEvent,
BuiltInTool,
GlobSearchType,
SearchChatsMessageSelection,
+16
View File
@@ -46,6 +46,7 @@ export enum BuiltInTool {
BROWSER_READ_MEDIA = 'read_media',
BROWSER_RUN_JAVASCRIPT = 'run_javascript',
BROWSER_SEARCH_CHATS = 'search_chats',
SERVER_BACKGROUND_TASK = 'background_task',
SERVER_EDIT_FILE = 'edit_file',
SERVER_EXEC_SHELL_COMMAND = 'exec_shell_command',
SERVER_FILE_GLOB_SEARCH = 'file_glob_search',
@@ -67,3 +68,18 @@ export enum SearchChatsOrder {
ASC = 'asc',
DESC = 'desc'
}
/** What a background task is doing, as llama-server names it */
export enum BackgroundTaskStatus {
EXITED = 'exited',
RUNNING = 'running',
STOPPED = 'stopped'
}
/** The events llama-server sends on `GET /tools/tasks/events` */
export enum BackgroundTasksServerEvent {
SNAPSHOT = 'snapshot',
TASK_EXITED = 'task_exited',
TASK_OUTPUT = 'task_output',
TASK_STARTED = 'task_started'
}
@@ -0,0 +1,87 @@
/**
* BackgroundTasksService - The commands llama-server keeps running for a conversation
*
* `exec_shell_command` runs every command as a task. A task outlives its call once it moves to
* the background - the model asks for that when it starts the command, the user asks for it while
* the command runs - and it then belongs to the conversation the call carried in its
* `X-Conversation-Id` header, which `ToolsService` sends. Every route is scoped to the
* conversation the request names, so every call here names one. The server side, and what each
* route answers, is documented in `tools/server/README-dev.md`.
*
* No state: the tasks of the conversation the chat is on live in `backgroundTasksStore`.
*/
import { API_TOOLS_TASKS } from '#lib/constants/index.ts';
import type {
BackgroundTask,
BackgroundTaskOutput,
BackgroundTasksEvent
} from '#lib/types/index.ts';
import { apiFetch } from '#lib/utils/api-fetch.ts';
import { getAuthHeaders } from '#lib/utils/api-headers.ts';
import { serverUrl } from '#lib/utils/server-config.ts';
import { parseSseJsonStream } from '#lib/utils/sse.ts';
/** The query of a route that works on one task of one conversation */
function taskParams(conversationId: string, id: number): URLSearchParams {
return new URLSearchParams({ conv_id: conversationId, id: String(id) });
}
export class BackgroundTasksService {
/** Move a running command to the background: its call returns at once, the command goes on */
static detach(conversationId: string, execId: number): Promise<BackgroundTask> {
return apiFetch<BackgroundTask>(API_TOOLS_TASKS.TASKS, {
body: JSON.stringify({ conv_id: conversationId, from_exec_id: execId }),
method: 'POST'
});
}
/**
* The tasks of a conversation: a `snapshot` of them, then an event every time one starts,
* prints or ends. The stream stays open while the page keeps reading it, so a caller reads
* it again when this generator returns or throws.
*/
static async *events(
conversationId: string,
signal?: AbortSignal
): AsyncGenerator<BackgroundTasksEvent> {
const params = new URLSearchParams({ conv_ids: conversationId });
const response = await fetch(`${serverUrl(API_TOOLS_TASKS.EVENTS)}?${params}`, {
headers: { Accept: 'text/event-stream', ...getAuthHeaders() },
signal
});
if (!response.ok || !response.body) {
throw new Error(`background tasks answered ${response.status}`);
}
for await (const { data } of parseSseJsonStream<BackgroundTasksEvent>(response, signal)) {
yield data;
}
}
/** What a task printed since `from`; `skipped` says how much the server had dropped by then */
static output(
conversationId: string,
id: number,
from: number,
signal?: AbortSignal
): Promise<BackgroundTaskOutput> {
const params = taskParams(conversationId, id);
params.set('from', String(from));
return apiFetch<BackgroundTaskOutput>(`${API_TOOLS_TASKS.OUTPUT}?${params}`, {
authOnly: true,
signal
});
}
/** Stop a task, with everything it started */
static stop(conversationId: string, id: number): Promise<BackgroundTask> {
return apiFetch<BackgroundTask>(`${API_TOOLS_TASKS.TASKS}?${taskParams(conversationId, id)}`, {
authOnly: true,
method: 'DELETE'
});
}
}
+28 -8
View File
@@ -20,16 +20,20 @@ export class ToolsService {
* @param cwd - Working directory for the tool call, sent as the
* x-tool-cwd request header. The server resolves relative paths
* against it; the model cannot override it.
* @param conversationId - The conversation the call belongs to, sent as the
* X-Conversation-Id header: a command it starts can then move to the
* background as a task of that conversation.
*/
static async executeTool(
toolName: string,
params: Record<string, unknown>,
signal?: AbortSignal,
cwd?: string
cwd?: string,
conversationId?: string
): Promise<ToolExecutionResult> {
const result = await apiFetch<Record<string, unknown>>(API_TOOLS.EXECUTE, {
body: JSON.stringify({ params, tool: toolName }),
headers: cwd ? { [HEADERS.X_TOOL_CWD_HEADER]: cwd } : undefined,
headers: toolHeaders(cwd, conversationId),
method: 'POST',
signal
});
@@ -131,12 +135,10 @@ export class ToolsService {
toolName: string,
params: Record<string, unknown>,
signal?: AbortSignal,
cwd?: string
cwd?: string,
conversationId?: string
): AsyncGenerator<ToolStreamEvent> {
const headers = getJsonHeaders();
if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd;
const headers = { ...getJsonHeaders(), ...toolHeaders(cwd, conversationId) };
const response = await fetch(serverUrl(API_TOOLS.EXECUTE), {
body: JSON.stringify({ params, stream: true, tool: toolName }),
headers,
@@ -159,7 +161,11 @@ export class ToolsService {
const event = next.value.data;
if (event.chunk !== undefined) {
if (event.exec_id !== undefined) {
yield { chunk: null, done: false, execId: event.exec_id };
}
if (event.chunk) {
yield { chunk: event.chunk, done: false };
}
@@ -182,6 +188,8 @@ export interface ToolStreamEvent {
chunk: string | null;
done: boolean;
error?: string;
/** The server's id of the command an `exec_shell_command` call runs, sent first */
execId?: number;
}
/** Wire shape of one SSE event from `POST /tools?stream=true`. */
@@ -189,6 +197,18 @@ interface ToolServerEvent {
chunk?: string;
done?: boolean;
error?: string;
exec_id?: number;
}
/** The headers that tell the server where a tool call runs and which conversation it is for */
function toolHeaders(cwd?: string, conversationId?: string): Record<string, string> {
const headers: Record<string, string> = {};
if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd;
if (conversationId) headers[HEADERS.X_CONVERSATION_ID_HEADER] = conversationId;
return headers;
}
async function formatNonOkResponse(response: Response): Promise<string> {
@@ -46,6 +46,7 @@ import { SearchChatsService } from '#lib/services/search-chats.service.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
// direct imports between stores, not via the barrel, to avoid circular deps
import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts';
import { backgroundTasksStore } from '#lib/stores/background-tasks.svelte.ts';
import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts';
import { mcpStore } from '#lib/stores/mcp/index.svelte.ts';
import { modelsStore } from '#lib/stores/models/index.svelte.ts';
@@ -458,21 +459,39 @@ class AgenticStore {
let accumulated = '';
let isError = false;
for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) {
if (ev.chunk !== null) {
accumulated += ev.chunk;
context.update(accumulated);
}
if (ev.done) {
if (ev.error) {
accumulated = accumulated ? `${accumulated}\nError: ${ev.error}` : `Error: ${ev.error}`;
context.update(accumulated);
isError = true;
// the command can move to the background from its row while it runs, as a task of
// this conversation
try {
for await (const ev of ToolsService.streamTool(
toolName,
args,
signal,
cwd,
conversationId
)) {
if (ev.execId !== undefined) {
backgroundTasksStore.attach(conversationId, toolCall.id, ev.execId);
}
break;
if (ev.chunk !== null) {
accumulated += ev.chunk;
context.update(accumulated);
}
if (ev.done) {
if (ev.error) {
accumulated = accumulated
? `${accumulated}\nError: ${ev.error}`
: `Error: ${ev.error}`;
context.update(accumulated);
isError = true;
}
break;
}
}
} finally {
backgroundTasksStore.forget(toolCall.id);
}
return { content: accumulated, isError };
@@ -482,7 +501,7 @@ class AgenticStore {
const args = this.parseToolArguments(toolCall.function.arguments);
const cwd = conversationsStore.activeConversation?.cwd;
return ToolsService.executeTool(toolName, args, signal, cwd);
return ToolsService.executeTool(toolName, args, signal, cwd, conversationId);
}
if (toolSource === ToolSource.BROWSER) {
@@ -0,0 +1,262 @@
/**
* backgroundTasksStore - The commands the agent left running in this conversation
*
* llama-server runs every `exec_shell_command` as a task, and a task moved to the background
* belongs to the conversation that started it. This store follows the running tasks of the
* conversation the chat is on over the server's event stream, reads what they print, moves a
* command that is still running to the background, and stops one. The chat form lists them; a
* command still attached to its call is detached from its own row in the trace.
*
* The server owns the list and the processes: this only reads the stream, and a conversation
* keeps its tasks when the user goes back to it.
*/
import {
BACKGROUND_TASK_DETACH_FAILED,
BACKGROUND_TASK_STOP_FAILED,
BACKGROUND_TASKS_RETRY_MAX_MS,
BACKGROUND_TASKS_RETRY_MS
} from '#lib/constants/index.ts';
import { BackgroundTasksServerEvent, BackgroundTaskStatus, BuiltInTool } from '#lib/enums/index.ts';
import { BackgroundTasksService } from '#lib/services/background-tasks.service.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import { toolsStore } from '#lib/stores/tools.svelte.ts';
import type { BackgroundTask, BackgroundTaskLog, BackgroundTasksEvent } from '#lib/types/index.ts';
import { appendTaskOutput, emptyTaskLog, sleep } from '#lib/utils/index.ts';
import { untrack } from 'svelte';
import { toast } from 'svelte-sonner';
class BackgroundTasksStore {
dialogOpen = $state(false);
// a command still attached to the call that started it: its tool call, and the server's id of it
private attached = $state<Record<string, { conversationId: string; execId: number }>>({});
// the running tasks of the followed conversation, by id
private byId = $state<Record<number, BackgroundTask>>({});
// the conversation whose tasks are kept, empty until the chat is on one
private followed = '';
// what has been read of each task's output
private logs = $state<Record<number, BackgroundTaskLog>>({});
// rows open on screen: only their tasks are read when the server says there is new output
private open = new Set<number>();
// a read of a task in flight, so two events do not read it twice
private reading = new Set<number>();
// tasks that printed again while a read was in flight: read once more when it lands
private stale = new Set<number>();
/** The server runs commands, and keeps the ones that outlive their call */
get available(): boolean {
return agenticMode.enabled && toolsStore.hasServerTool(BuiltInTool.SERVER_BACKGROUND_TASK);
}
/** The conversation's running tasks, the newest first */
get tasks(): BackgroundTask[] {
return Object.values(this.byId).sort((a, b) => b.started_at - a.started_at || b.id - a.id);
}
/** A call whose command is running and can still be moved to the background */
attach(conversationId: string, toolCallId: string, execId: number): void {
this.attached[toolCallId] = { conversationId, execId };
}
/**
* Moves the command of a running call to the background: its call returns at once and the
* command keeps running as a task of the conversation.
*/
async detach(toolCallId: string): Promise<void> {
const call = this.attached[toolCallId];
if (!call) return;
try {
const task = await BackgroundTasksService.detach(call.conversationId, call.execId);
this.forget(toolCallId);
this.keep(call.conversationId, task);
} catch (error) {
// a command that ended on its own a moment before has left `attached`: nothing to say
if (this.attached[toolCallId]) {
toast.error(BACKGROUND_TASK_DETACH_FAILED, {
description: error instanceof Error ? error.message : undefined
});
}
}
}
/** The command a running call is still attached to, by the id of that call */
execIdOf(toolCallId?: string): number | undefined {
return toolCallId ? this.attached[toolCallId]?.execId : undefined;
}
/** Its call is over: the command either ended with it or is a task the list shows */
forget(toolCallId: string): void {
delete this.attached[toolCallId];
}
/** What the chat has read of a task's output */
log(taskId: number): BackgroundTaskLog {
return this.logs[taskId] ?? emptyTaskLog();
}
/** Stops a task, with everything it started */
async stop(taskId: number): Promise<void> {
const conversationId = this.followed;
if (!this.byId[taskId]) return;
try {
this.keep(conversationId, await BackgroundTasksService.stop(conversationId, taskId));
} catch (error) {
// a task that ended on its own a moment before has left the list: nothing to say
if (conversationId === this.followed && this.byId[taskId]) {
toast.error(BACKGROUND_TASK_STOP_FAILED, {
description: error instanceof Error ? error.message : undefined
});
}
}
}
async stopAll(): Promise<void> {
await Promise.all(this.tasks.map((task) => this.stop(task.id)));
}
/**
* Keeps the tasks of a conversation, and reads their event stream while `follow` is set;
* call it from an `$effect` and hand the effect the return value. The list starts empty
* when the chat moves to another conversation; a stream that stops and starts again on the
* same one (the tab was hidden, the server went away) keeps what was read.
*/
watch(conversationId: string, follow: boolean): void | (() => void) {
if (conversationId !== this.followed) this.reset(conversationId);
if (!conversationId || !follow) return;
const controller = new AbortController();
// the request reads settings for its headers: none of that is this effect's business
untrack(() => void this.follow(conversationId, controller.signal));
return () => controller.abort();
}
/**
* Reads a task's output while its row is open, and once at once to fill the row in;
* give the return value to an `$effect`.
*/
watchOutput(taskId: number): () => void {
this.open.add(taskId);
void this.read(taskId);
return () => this.open.delete(taskId);
}
/** One event of the task stream */
private apply(conversationId: string, event: BackgroundTasksEvent): void {
switch (event.event) {
case BackgroundTasksServerEvent.SNAPSHOT:
this.byId = {};
for (const task of event.tasks) this.keep(conversationId, task);
// the stream may have missed what the open rows printed while it was away
for (const taskId of this.open) void this.read(taskId);
break;
case BackgroundTasksServerEvent.TASK_STARTED:
case BackgroundTasksServerEvent.TASK_EXITED:
this.keep(conversationId, event.task);
break;
case BackgroundTasksServerEvent.TASK_OUTPUT:
if (this.open.has(event.id)) void this.read(event.id);
break;
}
}
// Reads the task stream of a conversation, again when it goes away, until it is aborted.
private async follow(conversationId: string, signal: AbortSignal): Promise<void> {
let delay = BACKGROUND_TASKS_RETRY_MS;
while (!signal.aborted) {
try {
for await (const event of BackgroundTasksService.events(conversationId, signal)) {
if (signal.aborted) return;
delay = BACKGROUND_TASKS_RETRY_MS;
this.apply(conversationId, event);
}
} catch {
// the server went away: read again below
}
if (signal.aborted) return;
await sleep(delay);
delay = Math.min(delay * 2, BACKGROUND_TASKS_RETRY_MAX_MS);
}
}
// A task as the server last answered it: listed while it runs, gone once it is done. An
// answer that lands after the chat moved to another conversation is not this list's.
private keep(conversationId: string, task: BackgroundTask): void {
if (conversationId !== this.followed) return;
if (task.status === BackgroundTaskStatus.RUNNING) {
this.byId[task.id] = task;
} else {
delete this.byId[task.id];
delete this.logs[task.id];
}
}
// What a running task printed since the last read
private async read(taskId: number): Promise<void> {
const conversationId = this.followed;
if (!this.byId[taskId]) return;
if (this.reading.has(taskId)) {
this.stale.add(taskId);
return;
}
this.reading.add(taskId);
try {
const read = await BackgroundTasksService.output(
conversationId,
taskId,
this.logs[taskId]?.offset ?? 0
);
if (conversationId === this.followed) {
this.logs[taskId] = appendTaskOutput(this.logs[taskId], read);
}
} catch {
// the server went away, or the task left its list: keep what is known of it
} finally {
this.reading.delete(taskId);
}
if (this.stale.delete(taskId)) await this.read(taskId);
}
/** The chat moved to another conversation: start its list empty */
private reset(conversationId: string): void {
this.followed = conversationId;
this.byId = {};
this.logs = {};
this.open.clear();
this.stale.clear();
}
}
export const backgroundTasksStore = new BackgroundTasksStore();
+3
View File
@@ -34,6 +34,9 @@ export { agenticStore } from './agentic/index.svelte';
// CONVERSATION MEDIA (one slideshow of the thread's images, audio and video)
export { mediaGalleryStore } from './media-gallery.svelte';
// BACKGROUND TASKS (commands llama-server keeps running for a conversation, e.g. dev servers)
export { backgroundTasksStore } from './background-tasks.svelte';
// CONVERSATIONS
export { sidebarDragStore } from './sidebar-drag.svelte';
export { conversationsStore } from './conversations/index.svelte';
+4 -4
View File
@@ -360,6 +360,10 @@ class ToolsStore {
});
}
hasServerTool(name: BuiltInTool): boolean {
return this._serverTools.some((def) => def.function.name === name);
}
/**
* Load persisted disabled tools and fetch the builtin tool list.
* Called by initStores() after migrations have run.
@@ -524,10 +528,6 @@ class ToolsStore {
}
}
private hasServerTool(name: BuiltInTool): boolean {
return this._serverTools.some((def) => def.function.name === name);
}
private inferTypeFromDefault(value: unknown): string | undefined {
if (typeof value === 'string') return 'string';
+4
View File
@@ -242,6 +242,10 @@ export type { DesktopIconStripItem, MenuAction } from './navigation';
// Tools types
export type {
BackgroundTask,
BackgroundTaskLog,
BackgroundTaskOutput,
BackgroundTasksEvent,
EditFileEdit,
EditFileMeta,
EditFileTitleMeta,
+52 -1
View File
@@ -1,5 +1,9 @@
import type { OpenAIToolDefinition } from './mcp';
import type { ToolSource } from '#lib/enums/index.ts';
import type {
BackgroundTasksServerEvent,
BackgroundTaskStatus,
ToolSource
} from '#lib/enums/index.ts';
import type { Component } from 'svelte';
/**
@@ -81,3 +85,50 @@ export interface EditFileTitleMeta {
editsApplied?: number;
errorMessage?: string;
}
/**
* A command llama-server keeps running for one conversation after the tool call
* that started it returned, as its routes answer it (`tools/server/README-dev.md`).
* The server owns the list; Llama Chat only reads it.
*/
export interface BackgroundTask {
/** the server's id of the command: the call that started it and the task it became share it */
id: number;
command: string;
/** the model's description of the call, may be empty */
description: string;
/** the working directory the command runs in */
cwd: string;
/** unix seconds */
started_at: number;
status: BackgroundTaskStatus;
}
/** One read of `GET /tools/tasks/output`: the task, and what it printed since the offset asked */
export interface BackgroundTaskOutput extends BackgroundTask {
output: string;
/** where the read after this one starts */
next: number;
/** bytes the server dropped between the offset asked and where `output` starts */
skipped?: number;
}
/** What the chat has read of a task's output, so a re-read only asks for the new bytes */
export interface BackgroundTaskLog {
text: string;
/** the offset the next read starts at */
offset: number;
/** what was dropped from the front, so the text does not start at the beginning */
skipped: number;
}
/** One event of `GET /tools/tasks/events` */
export type BackgroundTasksEvent =
/** the conversation's tasks right now, sent first */
| { event: BackgroundTasksServerEvent.SNAPSHOT; tasks: BackgroundTask[] }
| {
event: BackgroundTasksServerEvent.TASK_EXITED | BackgroundTasksServerEvent.TASK_STARTED;
task: BackgroundTask;
}
/** a task printed: the offset its output reaches now */
| { event: BackgroundTasksServerEvent.TASK_OUTPUT; id: number; offset: number };
@@ -0,0 +1,26 @@
import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts';
import type { BackgroundTaskLog, BackgroundTaskOutput } from '#lib/types/index.ts';
/** An output nothing has been read of yet */
export function emptyTaskLog(): BackgroundTaskLog {
return { offset: 0, skipped: 0, text: '' };
}
/**
* A read added to what the chat has of a task's output. Only the end of a long output is
* kept: what is cut from the front counts as skipped, like what the server dropped.
*/
export function appendTaskOutput(
current: BackgroundTaskLog | undefined,
read: BackgroundTaskOutput
): BackgroundTaskLog {
const log = current ?? emptyTaskLog();
const text = log.text + read.output;
const cut = Math.max(0, text.length - BACKGROUND_TASK_LOG_MAX_LENGTH);
return {
offset: Math.max(log.offset, read.next),
skipped: log.skipped + (read.skipped ?? 0) + cut,
text: text.slice(cut)
};
}
+2
View File
@@ -223,6 +223,8 @@ export {
// Data URL utilities
export { createBase64DataUrl } from './data-url';
export { sleep } from './sleep';
export { appendTaskOutput, emptyTaskLog } from './background-tasks';
// Header utilities
export { parseHeadersToArray, serializeHeaders } from './headers';
+4
View File
@@ -0,0 +1,4 @@
/** Resolves after `ms` milliseconds */
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -61,7 +61,7 @@ function promptText(container: Element): string {
}
function hasCursor(container: Element): boolean {
return container.querySelector('.exec-cursor') !== null;
return container.querySelector('.shell-cursor') !== null;
}
describe('exec_shell_command streaming title', () => {
@@ -0,0 +1,49 @@
<script lang="ts" module>
import { defineMeta } from '@storybook/addon-svelte-csf';
import ChatFormBackgroundTaskRow from '#lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte';
import { MS_PER_SECOND } from '#lib/constants/index.ts';
import { BackgroundTaskStatus } from '#lib/enums/index.ts';
import type { BackgroundTask } from '#lib/types/index.ts';
import StateGallery from '$llama-ui-stories/helpers/StateGallery.svelte';
import StateGalleryItem from '$llama-ui-stories/helpers/StateGalleryItem.svelte';
// one task of the background tasks dialog: its description, Stop, and its shell
// command over the output it printed
const { Story } = defineMeta({
component: ChatFormBackgroundTaskRow,
parameters: {
layout: 'padded'
},
title: 'Llama Chat/Chat/ChatForm/ChatFormBackgroundTaskRow'
});
const STARTED_AT = Math.floor(Date.now() / MS_PER_SECOND);
const task = (overrides: Partial<BackgroundTask>): BackgroundTask => ({
command: 'npx -y http-server /tmp/hello-world -p 8780',
cwd: '/tmp',
description: 'Serve the hello world page',
id: 1,
started_at: STARTED_AT,
status: BackgroundTaskStatus.RUNNING,
...overrides
});
</script>
<Story asChild name="States">
<StateGallery columns={1}>
<StateGalleryItem label="With a description">
<ChatFormBackgroundTaskRow task={task({ id: 1 })} />
</StateGalleryItem>
<StateGalleryItem label="Command only">
<ChatFormBackgroundTaskRow
task={task({
command: 'npm run build -- --watch',
description: '',
id: 2
})}
/>
</StateGalleryItem>
</StateGallery>
</Story>
@@ -0,0 +1,48 @@
import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts';
import { BackgroundTaskStatus } from '#lib/enums/index.ts';
import type { BackgroundTaskOutput } from '#lib/types/index.ts';
import { appendTaskOutput } from '#lib/utils/background-tasks.ts';
import { describe, expect, it } from 'vitest';
const read = (overrides: Partial<BackgroundTaskOutput>): BackgroundTaskOutput => ({
command: 'npx -y http-server /tmp/hello-world -p 8780',
cwd: '/tmp',
description: 'Serve the hello world page',
id: 7,
next: 0,
output: '',
started_at: 1_800_000_000,
status: BackgroundTaskStatus.RUNNING,
...overrides
});
describe('appendTaskOutput', () => {
it('adds what a task printed since the last read', () => {
const log = appendTaskOutput(undefined, read({ next: 6, output: 'hello ' }));
expect(log).toEqual({ offset: 6, skipped: 0, text: 'hello ' });
expect(appendTaskOutput(log, read({ next: 11, output: 'world' }))).toEqual({
offset: 11,
skipped: 0,
text: 'hello world'
});
});
it('counts what the server dropped before the read', () => {
expect(appendTaskOutput(undefined, read({ next: 500, output: 'end', skipped: 497 }))).toEqual({
offset: 500,
skipped: 497,
text: 'end'
});
});
it('keeps only the end of a long output', () => {
const extra = 10;
const output = 'a'.repeat(extra) + 'b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH);
const log = appendTaskOutput(undefined, read({ next: output.length, output }));
expect(log.text).toBe('b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH));
expect(log.skipped).toBe(extra);
expect(log.offset).toBe(output.length);
});
});
@@ -17,13 +17,17 @@
'icon-lg': 'size-(--height-control-lg)',
'icon-sm': 'size-5 rounded-sm',
lg: 'h-control-lg rounded-lg px-6 has-[>svg]:px-4',
sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5'
sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5',
// a compact action inside a row or a block: caption text, no fixed height
xs: 'gap-1.5 rounded-md px-2 py-1 text-caption [&_svg:not([class*=size-])]:size-icon-xs'
},
variant: {
default:
'matte-key-solid [--key-edge:var(--button-primary-edge)] bg-(--action-primary) text-(--fg-on-action) hover:bg-(--action-primary-hover)',
destructive:
'matte-key-solid [--key-edge:var(--button-danger-edge)] [--key-sheen-solid:var(--button-danger-sheen)] bg-(--action-danger) hover:bg-(--action-danger-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-(--fg-on-danger)!',
'danger-secondary':
'bg-(--action-danger-secondary) text-(--fg-danger) hover:bg-(--action-danger-secondary-hover) focus-visible:bg-(--action-danger-secondary-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40',
ghost:
'hover:text-(--fg-default) hover:bg-(--action-ghost-hover) hover:shadow-(--button-shadow) backdrop-blur-sm',
outline:
@@ -0,0 +1,32 @@
<script lang="ts" module>
import { tv } from '../utils';
// a quiet button for what a form carries along (a working directory, a system message,
// background tasks): muted text and a small icon, the text's colour on hover
export const chipVariants = tv({
base: 'flex w-auto min-w-0 items-center gap-1 rounded-md px-2 py-1 text-caption text-muted-foreground backdrop-blur-2xl outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg:not([class*=size-])]:size-icon-sm [&_svg]:shrink-0'
});
</script>
<script lang="ts">
import { cn, type WithElementRef } from '../utils';
import type { HTMLButtonAttributes } from 'svelte/elements';
let {
children,
class: className,
ref = $bindable(null),
type = 'button',
...restProps
}: WithElementRef<HTMLButtonAttributes> = $props();
</script>
<button
bind:this={ref}
class={cn(chipVariants(), className)}
data-slot="chip"
{type}
{...restProps}
>
{@render children?.()}
</button>
@@ -0,0 +1,2 @@
export { default as Chip } from './chip.svelte';
export { chipVariants } from './chip.svelte';
@@ -75,6 +75,9 @@
/* one red for every danger state: the danger action is the status fill itself, the alerts' red */
--action-danger: var(--fill-danger);
--action-danger-hover: color-mix(in oklch, var(--action-danger) 90%, transparent);
/* the quiet danger action: red text on a faint wash of the same red, stronger on hover */
--action-danger-secondary: color-mix(in oklch, var(--fill-danger) 8%, transparent);
--action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 16%, transparent);
--action-quiet: color-mix(in oklch, var(--neutral-100) 30%, transparent);
--action-quiet-hover: var(--neutral-100);
--action-ghost-hover: color-mix(in oklch, var(--neutral-500) 10%, transparent);
@@ -174,6 +177,8 @@
/* the same red as every danger state, as matte glass: the status fill, frosted and translucent over the page */
--action-danger: color-mix(in oklch, var(--fill-danger) 58%, transparent);
--action-danger-hover: color-mix(in oklch, var(--fill-danger) 68%, transparent);
--action-danger-secondary: color-mix(in oklch, var(--fill-danger) 12%, transparent);
--action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 22%, transparent);
--action-quiet: color-mix(in oklch, var(--neutral-400) 15%, transparent);
--action-quiet-hover: color-mix(in oklch, var(--neutral-400) 25%, transparent);
--action-ghost-hover: color-mix(in oklch, var(--neutral-400) 10%, transparent);
@@ -20,9 +20,10 @@
'tertiary',
'outline',
'ghost',
'destructive'
'destructive',
'danger-secondary'
];
const sizes: NonNullable<ButtonSize>[] = ['sm', 'default', 'lg'];
const sizes: NonNullable<ButtonSize>[] = ['xs', 'sm', 'default', 'lg'];
</script>
<Story asChild name="Default">
@@ -48,6 +49,8 @@
<Button><Plus /> New chat</Button>
<Button variant="destructive"><Trash2 /> Delete</Button>
<Button variant="danger-secondary"><Trash2 /> Remove</Button>
</div>
</StateGalleryItem>
</StateGallery>
@@ -0,0 +1,33 @@
<script lang="ts" module>
import StateGallery from '../../helpers/StateGallery.svelte';
import StateGalleryItem from '../../helpers/StateGalleryItem.svelte';
import { Chip } from '@ggml-org/llama-ui/ui/chip';
import { MessageSquareText, SquareTerminal } from '@lucide/svelte';
import { defineMeta } from '@storybook/addon-svelte-csf';
const { Story } = defineMeta({
component: Chip,
parameters: {
layout: 'centered'
},
title: 'Llama UI/Components/Actions/Chip'
});
</script>
<Story asChild name="Default">
<StateGallery columns={3}>
<StateGalleryItem label="Icon and label">
<Chip><SquareTerminal /><span class="truncate">1 background task</span></Chip>
</StateGalleryItem>
<StateGalleryItem label="Long label">
<Chip class="max-w-48">
<MessageSquareText /><span class="truncate">A custom system message that runs long</span>
</Chip>
</StateGalleryItem>
<StateGalleryItem label="Disabled">
<Chip disabled><MessageSquareText /><span class="truncate">Custom system message</span></Chip>
</StateGalleryItem>
</StateGallery>
</Story>