Compare commits

...
16 Commits
Author SHA1 Message Date
Mark TodorovichandMax Krasnyansky 59b716523f hexagon: move conv2d_dw kernels to a separate file (#32982)
* hexagon: move conv2d-dw kernels to conv2d-dw-ops.c

* hexagon: split conv2d-dw headers as well

* hexagon: add support for f16/f32 mixed types in conv2d

---------

Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
2026-12-03 13:43:35 -08:00
Rootodus 8c9895f1b5 vulkan: add subgroup shader for pool1d (#33221)
* vulkan: add subgroup shader for pool1d

Assisted-by: Google AI Search
2026-12-03 21:41:24 +01:00
Radoslav GerganovandBrian Woods b9fcf77a49 rpc : fix stale alloc_size cache entry reused for larger src tensor (#33611)
The RPC client's alloc-size cache key for
ggml_backend_rpc_buffer_type_get_alloc_size() omits the src tensors.
For ops in ggml_op_alloc_size_may_expand() the server-side allocation
size can depend on a src, e.g. TOP_K on Metal with nelements(src0) or
FLASH_ATTN_EXT on CUDA/Metal with the KV length. A size cached for a
small src could be reused for a larger one, overrunning the
server-side compute buffer.

Key the cache on the full layout of the tensor and its srcs, reusing
the supports_op key (renamed to op_layout_key), and move the cache and
its mutex from function-level statics into
ggml_backend_rpc_buffer_type_context.

ref: #30794

Testing done (on Apple M4 Max):
    TEST_RPC_DEVICE=MTL0 bash tests/test-rpc-multi-server.sh \
        build/bin/ggml-rpc-server build/bin/test-rpc-multi-server


Assisted-by: Claude Opus 5.5

Co-authored-by: Brian Woods <me@brian.biz>
2026-12-03 21:08:03 +02:00
Aleksander Grygier 2d4f84836c ui: one slideshow for every image of the conversation, in its order (#33622)
* ui: open the slideshow at the trace image that was clicked

The thread is walked from its leaf to its root and then sorted by
timestamp. Messages saved in the same millisecond, as the results of
parallel tool calls can be, kept the walk's leaf-first order through the
stable sort, so the slideshow listed a trace's images backwards and opened
each at its mirror. The path is put root first before the sort.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: one slideshow for every image of the conversation, in its order

The attachment lists and the slideshow showed their items newest first,
while the image clicked was found in the thread's own order: each click
opened its mirror. Nothing is reversed now: attachment lists keep the
order the files were added in and the slideshow the thread's order, so
the image clicked is the one that opens.

The images a tool call shows once opened (read media, a tool's output, a
shell command's) and an attachment's image in Markdown open the same
slideshow at themselves.

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-03 19:37:51 +01:00
74e7f44650 model: qwen4 (#33626)
Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
Co-authored-by: Pascal <admin@serveurperso.com>
2026-12-03 19:18:55 +01:00
Ahmed Mohammed 45b8962622 gguf-py : allow F64 and integer tensors in gguf_convert_endian (#33575)
* gguf-py : allow F64 and integer tensors in gguf_convert_endian

Assisted-by: Claude

* gguf-py : move I8 to byteswap_tensors as noop, drop test
2026-12-03 18:39:41 +01:00
Aleksander Grygier 75d911fff3 ui: rejoin a dropped reply once the page is back, retrying a few times (#33615)
A phone that locks freezes the page and drops its connection, and for the first seconds
after it wakes it has no network. The stream reader tried to rejoin once, often then, and
closed the reply as interrupted when that failed. It now waits until the page is in front
and online, retries up to six times with growing pauses, and stops early when the server
says the session is gone.

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-03 17:45:02 +01:00
9a811bab3c hexagon: conv2d_dw 5x5 performance improvement (#32979)
* hexagon: conv2d-dw 5x5 kernel dbl buf DMA

Co-authored-by: Todor Boinovski <todorb@qti.qualcomm.com>

* hexagon: update conv2d to support f16/f32 mixed types, proper f16 lowering, use generic dma_pipeline

---------

Co-authored-by: Todor Boinovski <todorb@qti.qualcomm.com>
Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
2026-12-03 08:40:21 -08:00
Pascal f727eab9af ui: drop the type-aware lint of plain .ts files (#33619)
The projectService block for src/**/*.ts gives eslint a full
TypeScript program for every module of the app, but no rule needs it
there: svelte/no-navigation-without-resolve only fires on .svelte
links, whose files are already linted with type information that sees
the types of the modules they import, such as RouterService.chat().

Dropping it takes the peak memory of eslint from 5.9 GB back to
4.3 GB, under the default Node heap, with the same lint result.
2026-12-03 16:47:54 +01:00
PRANESH S d4adfb478e gguf-py : parse bool values in gguf-set-metadata (#33548)
* gguf-py : parse bool values in gguf-set-metadata

* gguf-py : remove set-metadata test

* gguf-py : accept empty string as false in gguf-set-metadata
2026-12-03 14:36:36 +01:00
Aleksander Grygier debcc4d992 ui: answer a list of CORS origins with the origin that asked (#33602)
* server: answer a list of CORS origins with the one that asked

With more than one origin in --cors-origins, Access-Control-Allow-Origin carried the whole
comma-separated list, which browsers reject. The request's own origin is now sent back
when it is in the list, with Vary: Origin, and none otherwise.

Assisted-by: Claude (Opus 5.5 Medium)

* server: keep "*" in --cors-origins working without credentials

The wildcard fell through to the origin list, so with --no-cors-credentials it matched
no origin and Access-Control-Allow-Origin was dropped. "*" is now handled before the list.
test_cors_options covers a two-origin list and "*" without credentials.

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-03 14:36:16 +01:00
stornic56 4c0ad42e68 models: laguna/afmoe: move inp_out_ids crop before attn_o_proj in last layer (#33557)
* models: laguna/afmoe: move inp_out_ids crop before attn_o_proj in last layer

Advance the ggml_get_rows(..., inp_out_ids) crop of the last layer
(il == n_layer - 1) to run before the attention output projection wo
(attn_o_proj) in laguna.cpp and afmoe.cpp, and before attn_post_norm in
afmoe.cpp.

Since build_lora_mm (wo) and build_norm operate strictly row-wise
without mixing positions or touching the KV cache, advancing the crop is
mathematically equivalent and saves (n_tokens - n_outputs) projections
in the last layer during prefill on all backends.

test-llama-archs: CPU + Vulkan0, laguna/afmoe, all OK.
NMSE laguna 2.38e-07, afmoe 8.83e-08 vs CPU.

AI usage disclosure: assisted

* tests: update MTL.csv fusion counts for afmoe
2026-12-03 14:25:09 +01:00
Jeff Bolz d39c260e6c vulkan: SSM_SCAN optimizations and coopmat2 support (#32916)
* vulkan: SSM_SCAN optimizations and coopmat2 support

Add a prefill shader that does multiple rows at a time, prefetches/stages
through shared memory. The subgroup reduction only runs once per block of tokens.
Doing multiple rows at a time amortizes some of the load overhead and stalls.
Uses larger (vec4) loads. Spreads the "A"/softplus work across threads rather than
repeating on every thread.

Add a coopmat2 shader that implements the chunked matrix form, similar to CUDA
and Metal backends. Each workgroup does 32 rows of a head. Claude verified that
the KLD relative to the fp32 baseline was no worse than CUDA's SSD path relative
to its fp32 baseline.

Add more test coverage for different layouts/views/alignment.

* allow d_state 96 in the fast shaders

* vulkan: SSM_SCAN: address review feedback

- The prefill shader uses chunks of 8 tokens at d_state 128. 16 used
  enough shared memory to lower the occupancy on AMD.
- constexpr constants instead of defines. The ones only the coopmat2
  shader uses, and its shared memory size, are inside its #if, so that
  builds without coopmat2 have no unused constants.
- The prefill shaders no longer need 16-byte aligned binding offsets,
  which AMD and Intel only align to 4 bytes.
- The prefill shader is disabled on Intel, where it spills and is slower
  than the per-token shader.
- Fewer comments.

Assisted-by: Claude Opus 5.5

* vulkan: SSM_SCAN: use log1p in softplus

softplus(dt) computed log(1 + exp(dt)), which loses precision when
exp(dt) is small. The scan shaders now use the log1p helper from
utils.glsl, as the CPU and CUDA backends use log1pf.

Assisted-by: Claude Opus 5.5
2026-12-03 15:21:52 +02:00
ae81d7f090 vulkan: hoist K-quant dequant in mul_mat_vecq (#31022)
* vulkan: hoist K-quant dequant in mul_mat_vecq

Preload each row's weight tile before the column loop so the K-quant block
is unpacked once per row instead of once per column. Small perf win at np=8.

* vulkan: keep legacy MMVQ types on the inline path

The a_tile array is indexed by the NUM_ROWS spec constant. On the Nvidia
Vulkan driver it is not scalarized, so q4_0/q8_0 spill to local memory and
regress (RTX 3090: -12.6%/-21% in test-backend-ops). The legacy unpack is
already cheap; keep those types on the base per-column load+dot. K-quants
and i-quants keep the hoist.

Also store a scalar dm for Q4_0/Q5_0/Q8_0/MXFP4 instead of broadcasting it
to a vec2.

Tested on RX 9070 XT: legacy SPIR-V matches base and perf is within noise;
iq4_xs/iq1_m/q4_K/q6_K/q2_K are unchanged. test-backend-ops passes for
q4_0, q8_0, q4_K, q6_K, iq4_xs, iq1_m and q2_K.

* vulkan: specialize mul_mat_vecq tail for two-row workgroups

---------

Co-authored-by: DrMkdaddy <DrMkdaddy@users.noreply.github.com>
Co-authored-by: Noor Mkdad <37319157+DrMkdaddy@users.noreply.github.com>
2026-12-03 15:20:42 +02:00
yoshi a89559540d ggml : fix view init skipped after buft max_size split (#25584)
* ggml : fix view init skipped after buft max_size split

When ggml_backend_buft_alloc_buffer_n splits allocation on buft
max_size, a view-only tail has size 0 and is left out of the plan.
Persistent views (e.g. KV k_stream / v_stream) were then left without
ggml_backend_view_init.

Do not split on a size-0 tensor. The views stay in the parent range,
and the existing view_init runs.

* ggml : add regression test for view init after max_size split

Cover the buft max_size split path where a view-only tail is left out
of the alloc plan and would skip ggml_backend_view_init.
2026-12-03 15:19:06 +02:00
Aleksander Grygier 05b9db8310 ui: name the MCP server of each tool in /tools, and let MCP servers' icons load (#33598)
* server : name the MCP server of each tool in /tools

A tool of an MCP server llama-server runs from --mcp-servers-config is
listed as <server>_<tool>, so a client could only guess the server from
the name, and guess wrong when the server's name has an underscore.
GET /tools now gives it in `mcp_server` for such tools. Built-in tools
are listed as before.

Assisted-by: Claude (Opus 5.5 Medium)

* server: serve the UI with COEP credentialless

The cross-origin isolation the UI is served with (COEP require-corp) blocked images from
hosts that send no CORP header, such as MCP server icons. With credentialless the page
stays isolated and remote images load without credentials.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: regenerate DESIGN.md with the danger secondary tokens

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-03 13:38:56 +01:00
62 changed files with 3319 additions and 1334 deletions
+21 -2
View File
@@ -20,12 +20,30 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
auto is_qwen3_coder = !supports_reasoning;
// Compact reasoning: "<think>" + reasoning + "</think>" + content with no separators (Qwen4), unlike the
// "<think>\n...\n</think>\n\n" of Qwen3.5. The template shows it when thinking is turned off.
bool compact_think = false;
if (supports_reasoning) {
autoparser::generation_params probe;
probe.messages = json::array({ { { "role", "user" }, { "content", "x" } } });
probe.add_generation_prompt = true;
probe.enable_thinking = false;
try {
compact_think = string_ends_with(common_chat_template_generation_prompt(tmpl, probe), "<think></think>");
} catch (const std::exception &) {
// a template that cannot render without thinking keeps the default layout
}
}
if (supports_reasoning) {
data.thinking_start_tag = "<think>";
// Support both </think> and <tool_call> as reasoning end sequences.
// The newline variant comes first so it is included in the forced message
// <function= is omitted, as it is a workaround for Qwen3-Coder which is not a thinking model
data.thinking_end_tags = { "\n</think>", "</think>", "<tool_call>" };
if (compact_think) {
data.thinking_end_tags = { "</think>", "<tool_call>" };
}
data.preserved_tokens.insert(data.preserved_tokens.end(), { "<think>", "</think>" });
}
@@ -33,6 +51,7 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
{ COMMON_CHAT_ROLE_ASSISTANT, "<|im_start|>assistant" },
{ COMMON_CHAT_ROLE_TOOL, "<|im_start|>user\n<tool_response>" }, // Qwen3-Coder, Qwen3.5, Nemotron Nano 3
{ COMMON_CHAT_ROLE_TOOL, "<|im_start|>tool_response" }, // StepFun-3.5-Flash
{ COMMON_CHAT_ROLE_TOOL, "<|im_start|>tool\n" }, // Qwen4
{ COMMON_CHAT_ROLE_USER, "<|im_start|>user" },
{ COMMON_CHAT_ROLE_SYSTEM, "<|im_start|>system" },
};
@@ -47,9 +66,9 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
data.generation_prompt = GEN_PREFIX;
if (supports_reasoning) {
data.generation_prompt += "<think>\n" + msg.reasoning_content;
data.generation_prompt += (compact_think ? "<think>" : "<think>\n") + msg.reasoning_content;
if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
data.generation_prompt += "\n</think>\n\n";
data.generation_prompt += compact_think ? "</think>" : "\n</think>\n\n";
}
}
if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
+6
View File
@@ -309,6 +309,10 @@ TEXT_MODEL_MAP: dict[str, str] = {
"Qwen3_5TextModel": "qwen",
"Qwen4ExpForCausalLM": "qwen4exp",
"Qwen4ExpForConditionalGeneration": "qwen4exp",
"Qwen4MoeForCausalLM": "qwen4exp",
"Qwen4MoeForConditionalGeneration": "qwen4exp",
"Qwen4ForCausalLM": "qwen4exp",
"Qwen4ForConditionalGeneration": "qwen4exp",
"RND1": "qwen",
"RWForCausalLM": "falcon",
"RWKV6Qwen2ForCausalLM": "rwkv",
@@ -455,6 +459,8 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
"Qwen3_5ForConditionalGeneration": "qwen3vl",
"Qwen3_5MoeForConditionalGeneration": "qwen3vl",
"Qwen4ExpForConditionalGeneration": "qwen4exp",
"Qwen4MoeForConditionalGeneration": "qwen4exp",
"Qwen4ForConditionalGeneration": "qwen4exp",
"RADIOModel": "nemotron",
"Sarashina2VisionForCausalLM": "sarashina2",
"SmolVLMForConditionalGeneration": "smolvlm",
+30 -4
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import json
from typing import Iterable, cast
import torch
@@ -13,7 +14,9 @@ from .qwen import _LinearAttentionVReorderBase, _Qwen35MRopeMixin
from .qwen3vl import Qwen3VLVisionModel
@ModelBase.register("Qwen4ExpForConditionalGeneration", "Qwen4ExpForCausalLM")
@ModelBase.register("Qwen4ExpForConditionalGeneration", "Qwen4ExpForCausalLM",
"Qwen4MoeForConditionalGeneration", "Qwen4MoeForCausalLM",
"Qwen4ForConditionalGeneration", "Qwen4ForCausalLM")
@ModelBase.example("Qwen/Qwen3.8-Flash-Next")
class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
"""Qwen3.8-Flash-Next.
@@ -54,6 +57,29 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
self._ple_scale = float(scale[0])
super().dequant_model()
def set_vocab(self):
# no tokenizer.json at the root: load the one in tokenizer-compat/
compat = self.dir_model / "tokenizer-compat"
if (self.dir_model / "tokenizer.json").is_file() or not (compat / "tokenizer.json").is_file():
super().set_vocab()
return
dir_model = self.dir_model
self.dir_model = compat
try:
super().set_vocab()
finally:
self.dir_model = dir_model
def get_vocab_base_pre(self, tokenizer) -> str:
res = super().get_vocab_base_pre(tokenizer)
# Qwen4 hashes like Qwen3.5 but is tiktoken-encoded (ignore_merges)
tokenizer_json = self.dir_model / "tokenizer.json"
if res == "qwen35" and tokenizer_json.is_file():
with open(tokenizer_json, encoding="utf-8") as f:
if json.load(f).get("model", {}).get("ignore_merges"):
res = "qwen4"
return res
def _has_fp8_source_scale(self, name: str) -> bool:
if ".ngram_embedding.shard_" in name:
prefix = name.split(".ngram_embedding.shard_")[0]
@@ -102,14 +128,14 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
layer_types = hp["layer_types"]
# the MTP block is a full-attention QSA layer too
self.gguf_writer.add_attention_compress_ratios(
[ratio if layer_types[i] == "full_attention" else 0 for i in range(n_layer)]
[0 if layer_types[i] == "linear_attention" else ratio for i in range(n_layer)]
+ [ratio] * (self.block_count - n_layer)
)
# ple_layer_ids is 1-based in the HF config; empty means no n-gram table,
# so emit no PLE keys rather than optional ones
# the MTP head never reads PLE, so an MTP-only file carries none of it
ple_layers = [i - 1 for i in hp["ple_layer_ids"]]
ple_layers = [i - 1 for i in hp.get("ple_layer_ids") or []]
if not ple_layers or self.mtp_only:
return
self.gguf_writer.add_ple_layers(ple_layers)
@@ -259,7 +285,7 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
)
@ModelBase.register("Qwen4ExpForConditionalGeneration")
@ModelBase.register("Qwen4ExpForConditionalGeneration", "Qwen4MoeForConditionalGeneration", "Qwen4ForConditionalGeneration")
@ModelBase.example("Qwen/Qwen3.8-Flash-Next")
class Qwen4ExpVisionModel(Qwen3VLVisionModel):
"""The vision tower is an unmodified Qwen3-VL ViT."""
+1 -1
View File
@@ -73,7 +73,7 @@ static ggml_backend_buft_alloc_buffer_n_plan_t ggml_backend_buft_alloc_buffer_n_
}
// flush the current buffer if adding this tensor would exceed max_size
if (cur_buf_size > 0 && (cur_buf_size + this_size) > max_size) {
if (this_size > 0 && cur_buf_size > 0 && (cur_buf_size + this_size) > max_size) {
plan.push_back({ cur_buf_size, first, i });
cur_buf_size = this_size;
first = i;
+43 -17
View File
@@ -5352,8 +5352,46 @@ static bool htp_kparams_solve_conv2d_dw(
const struct ggml_tensor * src1 = op->src[1];
const struct ggml_tensor * dst = op;
// 5x5 s=1 p=2 d=1 depthwise: DMA/HVX kernel (supports f16/f32 weights, inputs, and outputs).
if ((src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_F32) &&
(src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_F32) &&
(dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F32) &&
src0->ne[0] == 5 && src0->ne[1] == 5 && src0->ne[2] == 1 && src0->ne[3] == src1->ne[2] &&
ggml_are_same_shape(dst, src1) &&
ggml_get_op_params_i32(op, 0) == 1 && ggml_get_op_params_i32(op, 1) == 1 &&
ggml_get_op_params_i32(op, 2) == 2 && ggml_get_op_params_i32(op, 3) == 2 &&
ggml_get_op_params_i32(op, 4) == 1 && ggml_get_op_params_i32(op, 5) == 1 &&
ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
const uint32_t n_threads = htp_session_n_hvx(sess);
const size_t vtcm_sz = htp_session_vtcm_size(sess);
const size_t src_es = ggml_type_size(src1->type);
const size_t dst_es = ggml_type_size(dst->type);
const uint64_t planes = (uint64_t) dst->ne[2] * dst->ne[3];
if (planes <= UINT32_MAX && src1->ne[0] <= UINT32_MAX - 4 && src1->ne[1] <= UINT32_MAX - 4 &&
(uint64_t) (src1->ne[0] + 4) * src_es <= vtcm_sz &&
(uint64_t) (src1->ne[1] + 4) * (uint64_t) (src1->ne[0] + 4) * src_es <= vtcm_sz) {
uint32_t nth = (uint32_t) (std::min)(planes, (uint64_t) (std::min)(n_threads, 255u));
for (; nth > 0; --nth) {
struct htp_conv2d_dw5_vtcm_layout layout;
htp_conv2d_dw5_vtcm_layout_build(&layout, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1],
src_es, dst_es, nth);
if (layout.total_bytes <= UINT32_MAX && layout.total_bytes <= vtcm_sz) {
kparams->kernel_type = HTP_CONV2D_DW_KERNEL_WHCN_5X5_DMA;
kparams->flags = (src0->type == GGML_TYPE_F16 ? HTP_CONV2D_DW_FLAG_F16 : 0);
kparams->n_hvx = (uint8_t) nth;
kparams->total_tasks = (uint32_t) planes;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
kparams->w = (uint32_t) src1->ne[0];
kparams->h = (uint32_t) src1->ne[1];
return true;
}
}
}
}
if ((src0->type != GGML_TYPE_F16 && src0->type != GGML_TYPE_F32) ||
src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
(src1->type != GGML_TYPE_F16 && src1->type != GGML_TYPE_F32) ||
(dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_F32)) {
return false;
}
@@ -5400,12 +5438,8 @@ static bool htp_kparams_solve_conv2d_dw(
const uint32_t ow_u = (uint32_t) ow;
const uint32_t oh_u = (uint32_t) oh;
const uint32_t row_src_bytes = cwhn
? (w * c * (uint32_t) sizeof(float))
: (w * (uint32_t) sizeof(float));
const uint32_t row_dst_bytes = cwhn
? (ow_u * c * (uint32_t) sizeof(float))
: (ow_u * (uint32_t) sizeof(float));
const uint32_t row_src_bytes = (cwhn ? w * c : w) * (uint32_t) ggml_type_size(src1->type);
const uint32_t row_dst_bytes = (cwhn ? ow_u * c : ow_u) * (uint32_t) ggml_type_size(dst->type);
uint8_t kernel_type = HTP_CONV2D_DW_KERNEL_UNSUPPORTED;
if (cwhn) {
@@ -5427,7 +5461,6 @@ static bool htp_kparams_solve_conv2d_dw(
}
const bool fast_k3x3 = kernel_type >= HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3;
const uint32_t pad_rows = fast_k3x3 ? 4 : 0;
const uint32_t pad_top_stride = fast_k3x3 ? w : 0;
const size_t vtcm_budget = htp_session_vtcm_size(sess);
@@ -5441,11 +5474,7 @@ static bool htp_kparams_solve_conv2d_dw(
struct htp_conv2d_dw_vtcm_layout layout;
while (true) {
const uint32_t max_ih_chunk = (std::min)(h, (oh_chunk - 1) * (uint32_t) s1 + (kh - 1) * (uint32_t) d1 + 1);
const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * row_src_bytes + 128;
const uint32_t max_dst_bytes = oh_chunk * row_dst_bytes + 128;
htp_conv2d_dw_vtcm_layout_build(&layout, max_src_bytes, max_dst_bytes, w_size, n_hvx);
htp_conv2d_dw_vtcm_layout_build(&layout, w, h, c, kh, ow_u, oh_chunk, s1, d1, cwhn, fast_k3x3, w_size, n_hvx);
if (layout.total_bytes <= vtcm_budget && layout.total_bytes > 0) {
break;
@@ -5467,10 +5496,7 @@ static bool htp_kparams_solve_conv2d_dw(
n_hvx = 1;
}
const uint32_t max_ih_chunk = (std::min)(h, (oh_chunk - 1) * (uint32_t) s1 + (kh - 1) * (uint32_t) d1 + 1);
const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * row_src_bytes + 128;
const uint32_t max_dst_bytes = oh_chunk * row_dst_bytes + 128;
htp_conv2d_dw_vtcm_layout_build(&layout, max_src_bytes, max_dst_bytes, w_size, n_hvx);
htp_conv2d_dw_vtcm_layout_build(&layout, w, h, c, kh, ow_u, oh_chunk, s1, d1, cwhn, fast_k3x3, w_size, n_hvx);
kparams->kernel_type = kernel_type;
kparams->flags = (cwhn ? HTP_CONV2D_DW_FLAG_CWHN : 0) | (src0->type == GGML_TYPE_F16 ? HTP_CONV2D_DW_FLAG_F16 : 0);
+1
View File
@@ -9,6 +9,7 @@
#include "htp/binary-ops.h"
#include "htp/concat-ops.h"
#include "htp/conv2d-ops.h"
#include "htp/conv2d-dw-ops.h"
#include "htp/cpy-ops.h"
#include "htp/cumsum-ops.h"
#include "htp/diag-ops.h"
+1
View File
@@ -4,6 +4,7 @@
#include "htp/argsort-ops.h"
#include "htp/binary-ops.h"
#include "htp/conv2d-ops.h"
#include "htp/conv2d-dw-ops.h"
#include "htp/cumsum-ops.h"
#include "htp/diag-ops.h"
#include "htp/dsv4-hc-ops.h"
+1
View File
@@ -52,6 +52,7 @@ add_library(${HTP_LIB} SHARED
argsort-ops.c
im2col-ops.c
conv2d-ops.c
conv2d-dw-ops.c
roll-ops.c
pool-ops.c
upscale-ops.c
File diff suppressed because it is too large Load Diff
+144
View File
@@ -0,0 +1,144 @@
#ifndef HTP_CONV2D_DW_OPS_H
#define HTP_CONV2D_DW_OPS_H
#include <stddef.h>
#include <stdint.h>
#include "hex-common.h"
#include "hex-fastdiv.h"
#include "htp-ops.h"
#include "htp-vtcm.h"
enum htp_conv2d_dw_kernel_type {
HTP_CONV2D_DW_KERNEL_UNSUPPORTED = 0,
HTP_CONV2D_DW_KERNEL_CWHN, // CWHN channel-contiguous layout
HTP_CONV2D_DW_KERNEL_WHCN_S1, // WHCN general stride-1
HTP_CONV2D_DW_KERNEL_WHCN_S2, // WHCN general stride-2
HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3, // WHCN aligned w%32==0, 3x3 s=1 p=1 d=1
HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W32, // WHCN w=32->ow=16, 3x3 s=2 p=1 d=1 (2 rows per vector)
HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W64, // WHCN w=64->ow=32, 3x3 s=2 p=1 d=1 (1 vector rolling kh)
HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3, // WHCN aligned w%32==0 (w>=96), 3x3 s=2 p=1 d=1
HTP_CONV2D_DW_KERNEL_WHCN_5X5_DMA, // WHCN 5x5 s=1 p=2 d=1, DMA row halo
HTP_CONV2D_DW_KERNEL_COUNT,
};
enum htp_conv2d_dw_flags {
HTP_CONV2D_DW_FLAG_CWHN = (1u << 0),
HTP_CONV2D_DW_FLAG_F16 = (1u << 1),
};
// WHCN_5X5_DMA VTCM layout shared by host and NPU: per-thread weight area (2 f16 slots + 25 f32 splats, rounded
// up) and the source slot tail for the valign over-read past the last row.
#define HTP_CONV2D_DW5_W_BYTES (32 * 128)
#define HTP_CONV2D_DW5_SRC_TAIL (3 * 128)
struct htp_conv2d_dw_kernel_params {
uint8_t kernel_type;
uint8_t flags; // bitmask of enum htp_conv2d_dw_flags
uint8_t n_hvx;
uint32_t total_tasks;
uint32_t vtcm_size;
uint32_t w;
uint32_t h;
uint32_t c;
uint32_t kw;
uint32_t kh;
uint32_t ow;
uint32_t oh;
int32_t s0;
int32_t s1;
int32_t p0;
int32_t p1;
int32_t d0;
int32_t d1;
uint32_t oh_chunk;
uint32_t n_chunks;
uint32_t row_src_bytes;
uint32_t row_dst_bytes;
uint32_t pad_top_stride;
struct fastdiv_values div_c;
struct fastdiv_values div_n_chunks;
};
#if defined(__cplusplus)
static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob");
#else
_Static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob");
#endif
struct htp_conv2d_dw_vtcm_layout {
size_t total_bytes;
size_t off_w;
size_t off_src;
size_t off_dst;
size_t src_spad_half_size;
size_t dst_spad_half_size;
size_t src_bytes_per_hvx;
size_t dst_bytes_per_hvx;
};
static inline void htp_conv2d_dw_vtcm_layout_build(
struct htp_conv2d_dw_vtcm_layout * L,
uint32_t w,
uint32_t h,
uint32_t c,
uint32_t kh,
uint32_t ow,
uint32_t oh_chunk,
int32_t s1,
int32_t d1,
bool cwhn,
bool has_pad_rows,
uint32_t w_size,
uint32_t n_hvx
) {
const uint32_t pad_rows = has_pad_rows ? 4 : 0;
const uint32_t row_src_f32 = (cwhn ? w * c : w) * (uint32_t) sizeof(float);
const uint32_t row_dst_f32 = (cwhn ? ow * c : ow) * (uint32_t) sizeof(float);
const uint32_t max_ih_chunk = MIN(h, (oh_chunk - 1) * (uint32_t) s1 + (kh - 1) * (uint32_t) d1 + 1);
const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * row_src_f32 + 128;
const uint32_t max_dst_bytes = oh_chunk * row_dst_f32 + 128;
L->src_spad_half_size = hex_round_up(max_src_bytes + 256, 128);
L->dst_spad_half_size = hex_round_up(max_dst_bytes + 128, 128);
L->src_bytes_per_hvx = 2 * L->src_spad_half_size;
L->dst_bytes_per_hvx = 2 * L->dst_spad_half_size;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_w, hex_round_up(w_size, 128));
VTCM_LAYOUT_ALLOC(off, off_src, L->src_bytes_per_hvx * n_hvx);
VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx);
L->total_bytes = off;
}
struct htp_conv2d_dw5_vtcm_layout {
size_t total_bytes;
size_t off_src;
size_t off_weight;
size_t off_dst;
size_t src_row_stride;
size_t src_slot_bytes;
size_t dst_slot_bytes;
};
static inline void htp_conv2d_dw5_vtcm_layout_build(
struct htp_conv2d_dw5_vtcm_layout * L,
uint32_t w,
uint32_t h,
size_t src_es,
size_t dst_es,
uint32_t n_hvx
) {
L->src_row_stride = hex_align_up((size_t) (w + 4) * src_es, 128);
L->src_slot_bytes = hex_align_up((size_t) (h + 4) * L->src_row_stride + HTP_CONV2D_DW5_SRC_TAIL, 128);
L->dst_slot_bytes = hex_align_up((size_t) w * h * dst_es, 128);
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_src, (size_t) 2 * n_hvx * L->src_slot_bytes);
VTCM_LAYOUT_ALLOC(off, off_weight, (size_t) n_hvx * HTP_CONV2D_DW5_W_BYTES);
VTCM_LAYOUT_ALLOC(off, off_dst, (size_t) 2 * n_hvx * L->dst_slot_bytes);
L->total_bytes = off;
}
#endif // HTP_CONV2D_DW_OPS_H
-904
View File
@@ -5,7 +5,6 @@
#define GGML_COMMON_DECL_C
#include "ggml-common.h"
#include "conv2d-ops.h"
#include "dma-copy.h"
#include "dma-queue.h"
#include "hex-common.h"
#include "hex-fastdiv.h"
@@ -2369,906 +2368,3 @@ int op_conv_2d(struct htp_ops_context * octx) {
return HTP_STATUS_NO_SUPPORT;
}
struct conv2d_dw_task_slice {
dma_addr_t src_addr;
dma_addr_t dst_addr;
uint32_t src_bytes;
uint32_t dst_bytes;
uint32_t ih_count;
uint32_t top_pad;
uint32_t bot_pad;
uint32_t oh_start;
uint32_t oh_len;
int32_t ih_first;
uint32_t c;
};
static inline void conv2d_dw_get_slice(
struct conv2d_dw_task_slice * slice,
uint32_t task,
const struct htp_tensor * src1,
const struct htp_tensor * dst,
const struct htp_conv2d_dw_kernel_params * kp) {
uint32_t chunk_idx;
uint32_t n;
uint32_t c = 0;
if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) {
n = fastdiv(task, &kp->div_n_chunks);
chunk_idx = task - n * kp->n_chunks;
} else {
const uint32_t plane = fastdiv(task, &kp->div_n_chunks);
chunk_idx = task - plane * kp->n_chunks;
n = fastdiv(plane, &kp->div_c);
c = plane - n * kp->c;
}
const uint32_t oh_start = chunk_idx * kp->oh_chunk;
const uint32_t oh_len = MIN(kp->oh_chunk, kp->oh - oh_start);
const int32_t ih_min = (int32_t)(oh_start * kp->s1) - kp->p1;
const int32_t ih_max = (int32_t)((oh_start + oh_len - 1) * kp->s1 + (kp->kh - 1) * kp->d1) - kp->p1;
const uint32_t ih_span = (uint32_t)(ih_max - ih_min + 1);
const int32_t ih_first = MAX(0, ih_min);
const int32_t ih_last = MIN((int32_t)kp->h - 1, ih_max);
const uint32_t ih_count = (ih_first <= ih_last) ? (uint32_t)(ih_last - ih_first + 1) : 0;
const uint32_t top_pad = (ih_count > 0) ? (uint32_t)(ih_first - ih_min) : ih_span;
const uint32_t bot_pad = ih_span - top_pad - ih_count;
slice->src_bytes = ih_count * kp->row_src_bytes;
slice->dst_bytes = oh_len * kp->row_dst_bytes;
slice->ih_count = ih_count;
slice->top_pad = top_pad;
slice->bot_pad = bot_pad;
slice->oh_start = oh_start;
slice->oh_len = oh_len;
slice->ih_first = ih_first;
slice->c = c;
if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) {
slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) ih_first * src1->nb[1];
slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) oh_start * dst->nb[1];
} else {
slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) c * src1->nb[2] + (size_t) ih_first * src1->nb[1];
slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) c * dst->nb[2] + (size_t) oh_start * dst->nb[1];
}
}
static inline HVX_Vector conv2d_dw_splat_w_f32(const void * ptr) {
return hvx_vec_splat_f32(*(const float *) ptr);
}
static inline HVX_Vector conv2d_dw_splat_w_f16(const void * ptr) {
const HVX_Vector vh = Q6_Vh_vsplat_R(*(const uint16_t *) ptr);
const HVX_Vector v1 = Q6_Vh_vsplat_R(0x3c00);
return Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(vh, v1)));
}
static inline HVX_Vector conv2d_dw_load_w_f32(const void * ptr) {
return hvx_vmemu(ptr);
}
static inline HVX_Vector conv2d_dw_load_w_f16(const void * ptr) {
return Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(ptr)));
}
static inline HVX_Vector conv2d_dw_qf32_mpy_add3(
HVX_Vector acc,
HVX_Vector x0, HVX_Vector w0,
HVX_Vector x1, HVX_Vector w1,
HVX_Vector x2, HVX_Vector w2) {
const HVX_Vector p01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, w0), Q6_Vqf32_vmpy_VsfVsf(x1, w1));
const HVX_Vector p2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x2, w2));
return Q6_Vqf32_vadd_Vqf32Vqf32(p01, p2);
}
static inline void conv2d_dw_pad_vtcm_k3x3(
float * in_vtcm,
const struct conv2d_dw_task_slice * slice,
uint32_t w_in,
uint32_t extra_bot_rows) {
if (slice->top_pad > 0) {
hvx_splat_f32_a(in_vtcm, 0.0f, slice->top_pad * w_in);
}
const uint32_t tail_zero_rows = slice->bot_pad + extra_bot_rows;
if (tail_zero_rows > 0) {
hvx_splat_f32_a(in_vtcm + (size_t) (slice->top_pad + slice->ih_count) * w_in, 0.0f, tail_zero_rows * w_in);
}
}
#define DEFINE_CONV2D_DW_WHCN_S1_K3X3(SUFFIX, SPLAT_W_FN) \
__attribute__((noinline)) \
static void conv2d_dw_whcn_s1_k3x3_##SUFFIX( \
const float * restrict in_vtcm, \
float * restrict out_vtcm, \
const void * w_vtcm, \
const struct conv2d_dw_task_slice * slice, \
const struct htp_ops_context * octx, \
const struct htp_conv2d_dw_kernel_params * kp) { \
\
const struct htp_tensor * src0 = octx->src[0]; \
const size_t w_nb0 = src0->nb[0]; \
const size_t w_nb1 = src0->nb[1]; \
const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \
const uint32_t oh_len = slice->oh_len; \
const uint32_t w_in = kp->w; \
\
conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, w_in, 0); \
\
const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \
const HVX_Vector zero = Q6_V_vzero(); \
\
uint32_t ohi = 0; \
for (; ohi + 4 <= oh_len; ohi += 4) { \
const float * restrict r0 = in_vtcm + (size_t) ohi * w_in; \
const float * restrict r1 = r0 + w_in; \
const float * restrict r2 = r1 + w_in; \
const float * restrict r3 = r2 + w_in; \
const float * restrict r4 = r3 + w_in; \
const float * restrict r5 = r4 + w_in; \
\
float * restrict out0 = out_vtcm + (size_t) (ohi + 0) * w_in; \
float * restrict out1 = out0 + w_in; \
float * restrict out2 = out1 + w_in; \
float * restrict out3 = out2 + w_in; \
\
HVX_Vector p0 = zero, c0 = hvx_vmem(r0); \
HVX_Vector p1 = zero, c1 = hvx_vmem(r1); \
HVX_Vector p2 = zero, c2 = hvx_vmem(r2); \
HVX_Vector p3 = zero, c3 = hvx_vmem(r3); \
HVX_Vector p4 = zero, c4 = hvx_vmem(r4); \
HVX_Vector p5 = zero, c5 = hvx_vmem(r5); \
\
for (uint32_t ox = 0; ox < w_in; ox += 32) { \
const bool has_next = (ox + 32 < w_in); \
\
const HVX_Vector n0 = has_next ? hvx_vmem(r0 + ox + 32) : zero; \
const HVX_Vector l0 = Q6_V_valign_VVR(c0, p0, 124); \
const HVX_Vector rg0 = Q6_V_valign_VVR(n0, c0, 4); \
HVX_Vector acc0 = conv2d_dw_qf32_mpy_add3(zero, l0, w00, c0, w01, rg0, w02); \
p0 = c0; c0 = n0; \
\
const HVX_Vector n1 = has_next ? hvx_vmem(r1 + ox + 32) : zero; \
const HVX_Vector l1 = Q6_V_valign_VVR(c1, p1, 124); \
const HVX_Vector rg1 = Q6_V_valign_VVR(n1, c1, 4); \
acc0 = conv2d_dw_qf32_mpy_add3(acc0, l1, w10, c1, w11, rg1, w12); \
HVX_Vector acc1 = conv2d_dw_qf32_mpy_add3(zero, l1, w00, c1, w01, rg1, w02); \
p1 = c1; c1 = n1; \
\
const HVX_Vector n2 = has_next ? hvx_vmem(r2 + ox + 32) : zero; \
const HVX_Vector l2 = Q6_V_valign_VVR(c2, p2, 124); \
const HVX_Vector rg2 = Q6_V_valign_VVR(n2, c2, 4); \
acc0 = conv2d_dw_qf32_mpy_add3(acc0, l2, w20, c2, w21, rg2, w22); \
hvx_vmem(out0 + ox) = Q6_Vsf_equals_Vqf32(acc0); \
acc1 = conv2d_dw_qf32_mpy_add3(acc1, l2, w10, c2, w11, rg2, w12); \
HVX_Vector acc2 = conv2d_dw_qf32_mpy_add3(zero, l2, w00, c2, w01, rg2, w02); \
p2 = c2; c2 = n2; \
\
const HVX_Vector n3 = has_next ? hvx_vmem(r3 + ox + 32) : zero; \
const HVX_Vector l3 = Q6_V_valign_VVR(c3, p3, 124); \
const HVX_Vector rg3 = Q6_V_valign_VVR(n3, c3, 4); \
acc1 = conv2d_dw_qf32_mpy_add3(acc1, l3, w20, c3, w21, rg3, w22); \
hvx_vmem(out1 + ox) = Q6_Vsf_equals_Vqf32(acc1); \
acc2 = conv2d_dw_qf32_mpy_add3(acc2, l3, w10, c3, w11, rg3, w12); \
HVX_Vector acc3 = conv2d_dw_qf32_mpy_add3(zero, l3, w00, c3, w01, rg3, w02); \
p3 = c3; c3 = n3; \
\
const HVX_Vector n4 = has_next ? hvx_vmem(r4 + ox + 32) : zero; \
const HVX_Vector l4 = Q6_V_valign_VVR(c4, p4, 124); \
const HVX_Vector rg4 = Q6_V_valign_VVR(n4, c4, 4); \
acc2 = conv2d_dw_qf32_mpy_add3(acc2, l4, w20, c4, w21, rg4, w22); \
hvx_vmem(out2 + ox) = Q6_Vsf_equals_Vqf32(acc2); \
acc3 = conv2d_dw_qf32_mpy_add3(acc3, l4, w10, c4, w11, rg4, w12); \
p4 = c4; c4 = n4; \
\
const HVX_Vector n5 = has_next ? hvx_vmem(r5 + ox + 32) : zero; \
const HVX_Vector l5 = Q6_V_valign_VVR(c5, p5, 124); \
const HVX_Vector rg5 = Q6_V_valign_VVR(n5, c5, 4); \
acc3 = conv2d_dw_qf32_mpy_add3(acc3, l5, w20, c5, w21, rg5, w22); \
hvx_vmem(out3 + ox) = Q6_Vsf_equals_Vqf32(acc3); \
p5 = c5; c5 = n5; \
} \
} \
\
for (; ohi < oh_len; ++ohi) { \
const float * restrict r0 = in_vtcm + (size_t) ohi * w_in; \
const float * restrict r1 = r0 + w_in; \
const float * restrict r2 = r1 + w_in; \
float * restrict out_row = out_vtcm + (size_t) ohi * w_in; \
\
HVX_Vector p0 = zero, c0 = hvx_vmem(r0); \
HVX_Vector p1 = zero, c1 = hvx_vmem(r1); \
HVX_Vector p2 = zero, c2 = hvx_vmem(r2); \
\
for (uint32_t ox = 0; ox < w_in; ox += 32) { \
const bool has_next = (ox + 32 < w_in); \
\
const HVX_Vector n0 = has_next ? hvx_vmem(r0 + ox + 32) : zero; \
const HVX_Vector l0 = Q6_V_valign_VVR(c0, p0, 124); \
const HVX_Vector rg0 = Q6_V_valign_VVR(n0, c0, 4); \
HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, l0, w00, c0, w01, rg0, w02); \
p0 = c0; c0 = n0; \
\
const HVX_Vector n1 = has_next ? hvx_vmem(r1 + ox + 32) : zero; \
const HVX_Vector l1 = Q6_V_valign_VVR(c1, p1, 124); \
const HVX_Vector rg1 = Q6_V_valign_VVR(n1, c1, 4); \
acc = conv2d_dw_qf32_mpy_add3(acc, l1, w10, c1, w11, rg1, w12); \
p1 = c1; c1 = n1; \
\
const HVX_Vector n2 = has_next ? hvx_vmem(r2 + ox + 32) : zero; \
const HVX_Vector l2 = Q6_V_valign_VVR(c2, p2, 124); \
const HVX_Vector rg2 = Q6_V_valign_VVR(n2, c2, 4); \
acc = conv2d_dw_qf32_mpy_add3(acc, l2, w20, c2, w21, rg2, w22); \
p2 = c2; c2 = n2; \
\
hvx_vmem(out_row + ox) = Q6_Vsf_equals_Vqf32(acc); \
} \
} \
}
DEFINE_CONV2D_DW_WHCN_S1_K3X3(f32, conv2d_dw_splat_w_f32)
DEFINE_CONV2D_DW_WHCN_S1_K3X3(f16, conv2d_dw_splat_w_f16)
#define DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(SUFFIX, SPLAT_W_FN) \
__attribute__((noinline)) \
static void conv2d_dw_whcn_s2_k3x3_w32_##SUFFIX( \
const float * restrict in_vtcm, \
float * restrict out_vtcm, \
const void * w_vtcm, \
const struct conv2d_dw_task_slice * slice, \
const struct htp_ops_context * octx, \
const struct htp_conv2d_dw_kernel_params * kp) { \
\
(void) kp; \
const struct htp_tensor * src0 = octx->src[0]; \
const size_t w_nb0 = src0->nb[0]; \
const size_t w_nb1 = src0->nb[1]; \
const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \
const uint32_t oh_len = slice->oh_len; \
\
conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, 32, (oh_len & 1) ? 2 : 0); \
\
const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \
const HVX_Vector zero = Q6_V_vzero(); \
\
const HVX_VectorPred q_not_lane16 = Q6_Q_or_QQn(Q6_Q_vsetq_R(64), Q6_Q_vsetq2_R(68)); \
const float * restrict in_row = in_vtcm; \
HVX_Vector v_prev_b2 = hvx_vmem(in_row); \
in_row += 32; \
\
for (uint32_t ohi = 0; ohi < oh_len; ohi += 2) { \
const HVX_Vector v_a0 = v_prev_b2; \
const HVX_Vector v_a1 = hvx_vmem(in_row); \
const HVX_Vector v_a2 = hvx_vmem(in_row + 32); \
const HVX_Vector v_b0 = v_a2; \
const HVX_Vector v_b1 = hvx_vmem(in_row + 64); \
const HVX_Vector v_b2 = hvx_vmem(in_row + 96); \
in_row += 128; \
v_prev_b2 = v_b2; \
\
const HVX_VectorPair vp0 = Q6_W_vdeal_VVR(v_b0, v_a0, -4); \
const HVX_Vector ev0 = Q6_V_lo_W(vp0); \
const HVX_Vector od0 = Q6_V_hi_W(vp0); \
const HVX_Vector lf0 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od0, zero, 124)); \
HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \
\
const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(v_b1, v_a1, -4); \
const HVX_Vector ev1 = Q6_V_lo_W(vp1); \
const HVX_Vector od1 = Q6_V_hi_W(vp1); \
const HVX_Vector lf1 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od1, zero, 124)); \
acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \
\
const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(v_b2, v_a2, -4); \
const HVX_Vector ev2 = Q6_V_lo_W(vp2); \
const HVX_Vector od2 = Q6_V_hi_W(vp2); \
const HVX_Vector lf2 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od2, zero, 124)); \
acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \
\
hvx_vmem(out_vtcm + (size_t) ohi * 16) = Q6_Vsf_equals_Vqf32(acc); \
} \
}
DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(f32, conv2d_dw_splat_w_f32)
DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(f16, conv2d_dw_splat_w_f16)
#define DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(SUFFIX, SPLAT_W_FN) \
__attribute__((noinline)) \
static void conv2d_dw_whcn_s2_k3x3_w64_##SUFFIX( \
const float * restrict in_vtcm, \
float * restrict out_vtcm, \
const void * w_vtcm, \
const struct conv2d_dw_task_slice * slice, \
const struct htp_ops_context * octx, \
const struct htp_conv2d_dw_kernel_params * kp) { \
\
(void) kp; \
const struct htp_tensor * src0 = octx->src[0]; \
const size_t w_nb0 = src0->nb[0]; \
const size_t w_nb1 = src0->nb[1]; \
const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \
const uint32_t oh_len = slice->oh_len; \
\
conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, 64, 0); \
\
const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \
const HVX_Vector zero = Q6_V_vzero(); \
\
const float * restrict in_row = in_vtcm; \
const HVX_VectorPair vp0_init = Q6_W_vdeal_VVR(hvx_vmem(in_row + 32), hvx_vmem(in_row), -4); \
in_row += 64; \
HVX_Vector ev0 = Q6_V_lo_W(vp0_init); \
HVX_Vector od0 = Q6_V_hi_W(vp0_init); \
HVX_Vector lf0 = Q6_V_valign_VVR(od0, zero, 124); \
\
for (uint32_t ohi = 0; ohi < oh_len; ++ohi) { \
const float * restrict r1_ptr = in_row; \
const float * restrict r2_ptr = in_row + 64; \
in_row += 128; \
\
HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \
\
const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(hvx_vmem(r1_ptr + 32), hvx_vmem(r1_ptr), -4); \
const HVX_Vector ev1 = Q6_V_lo_W(vp1); \
const HVX_Vector od1 = Q6_V_hi_W(vp1); \
const HVX_Vector lf1 = Q6_V_valign_VVR(od1, zero, 124); \
acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \
\
const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(hvx_vmem(r2_ptr + 32), hvx_vmem(r2_ptr), -4); \
const HVX_Vector ev2 = Q6_V_lo_W(vp2); \
const HVX_Vector od2 = Q6_V_hi_W(vp2); \
const HVX_Vector lf2 = Q6_V_valign_VVR(od2, zero, 124); \
acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \
\
hvx_vmem(out_vtcm + (size_t) ohi * 32) = Q6_Vsf_equals_Vqf32(acc); \
\
ev0 = ev2; \
od0 = od2; \
lf0 = lf2; \
} \
}
DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(f32, conv2d_dw_splat_w_f32)
DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(f16, conv2d_dw_splat_w_f16)
#define DEFINE_CONV2D_DW_WHCN_S2_K3X3(SUFFIX, SPLAT_W_FN) \
__attribute__((noinline)) \
static void conv2d_dw_whcn_s2_k3x3_##SUFFIX( \
const float * restrict in_vtcm, \
float * restrict out_vtcm, \
const void * w_vtcm, \
const struct conv2d_dw_task_slice * slice, \
const struct htp_ops_context * octx, \
const struct htp_conv2d_dw_kernel_params * kp) { \
\
const struct htp_tensor * src0 = octx->src[0]; \
const size_t w_nb0 = src0->nb[0]; \
const size_t w_nb1 = src0->nb[1]; \
const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \
const uint32_t oh_len = slice->oh_len; \
const uint32_t w_in = kp->w; \
const uint32_t ow = kp->ow; \
\
conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, w_in, 0); \
\
const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \
const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \
const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \
const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \
const HVX_Vector zero = Q6_V_vzero(); \
\
for (uint32_t ohi = 0; ohi < oh_len; ++ohi) { \
const float * restrict r0 = in_vtcm + (size_t) (2 * ohi) * w_in; \
const float * restrict r1 = r0 + w_in; \
const float * restrict r2 = r1 + w_in; \
float * restrict out_row = out_vtcm + (size_t) ohi * ow; \
\
HVX_Vector prev_od0 = zero; \
HVX_Vector prev_od1 = zero; \
HVX_Vector prev_od2 = zero; \
\
for (uint32_t ox = 0; ox < ow; ox += 32) { \
const uint32_t ix = 2 * ox; \
const bool has1 = (ix + 32 < w_in); \
\
const HVX_VectorPair vp0 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r0 + ix + 32) : zero, hvx_vmem(r0 + ix), -4); \
const HVX_Vector ev0 = Q6_V_lo_W(vp0); \
const HVX_Vector od0 = Q6_V_hi_W(vp0); \
const HVX_Vector lf0 = Q6_V_valign_VVR(od0, prev_od0, 124); \
prev_od0 = od0; \
HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \
\
const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r1 + ix + 32) : zero, hvx_vmem(r1 + ix), -4); \
const HVX_Vector ev1 = Q6_V_lo_W(vp1); \
const HVX_Vector od1 = Q6_V_hi_W(vp1); \
const HVX_Vector lf1 = Q6_V_valign_VVR(od1, prev_od1, 124); \
prev_od1 = od1; \
acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \
\
const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r2 + ix + 32) : zero, hvx_vmem(r2 + ix), -4); \
const HVX_Vector ev2 = Q6_V_lo_W(vp2); \
const HVX_Vector od2 = Q6_V_hi_W(vp2); \
const HVX_Vector lf2 = Q6_V_valign_VVR(od2, prev_od2, 124); \
prev_od2 = od2; \
acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \
\
if (ox + 32 <= ow) { \
hvx_vmem(out_row + ox) = Q6_Vsf_equals_Vqf32(acc); \
} else { \
const uint32_t rem = ow - ox; \
const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \
hvx_vec_store_u(out_row + ox, rem * sizeof(float), Q6_V_vmux_QVV(q, Q6_Vsf_equals_Vqf32(acc), zero)); \
} \
} \
} \
}
DEFINE_CONV2D_DW_WHCN_S2_K3X3(f32, conv2d_dw_splat_w_f32)
DEFINE_CONV2D_DW_WHCN_S2_K3X3(f16, conv2d_dw_splat_w_f16)
#define DEFINE_CONV2D_DW_WHCN_S1(SUFFIX, SPLAT_W_FN) \
__attribute__((noinline)) \
static void conv2d_dw_whcn_s1_##SUFFIX( \
const float * in_vtcm, \
float * out_vtcm, \
const void * w_vtcm, \
const struct conv2d_dw_task_slice * slice, \
const struct htp_ops_context * octx, \
const struct htp_conv2d_dw_kernel_params * kp) { \
\
const struct htp_tensor * src0 = octx->src[0]; \
const char * w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \
const int32_t p0 = kp->p0; \
const int32_t p1 = kp->p1; \
const int32_t s1 = kp->s1; \
const int32_t d1 = kp->d1; \
const int32_t w = (int32_t) kp->w; \
const HVX_Vector zero = Q6_V_vzero(); \
\
for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \
const uint32_t oh = slice->oh_start + ohi; \
float * out_row = out_vtcm + (size_t) ohi * kp->ow; \
\
for (uint32_t ox = 0; ox < kp->ow; ox += 32) { \
const uint32_t rem = kp->ow - ox; \
const uint32_t nbytes = (rem < 32) ? (rem * sizeof(float)) : 128; \
HVX_Vector acc0 = zero; \
HVX_Vector acc1 = zero; \
HVX_Vector acc2 = zero; \
HVX_Vector acc3 = zero; \
\
for (uint32_t kh = 0; kh < kp->kh; ++kh) { \
const int32_t ih = (int32_t) (oh * s1 + kh * d1) - p1; \
if (ih < 0 || ih >= (int32_t) kp->h) { \
continue; \
} \
const float * in_row = in_vtcm + (size_t) (ih - slice->ih_first) * kp->w; \
const char * w_row = w_chan + (size_t) kh * src0->nb[1]; \
\
for (uint32_t kw = 0; kw < kp->kw; ++kw) { \
const HVX_Vector w_v = SPLAT_W_FN(w_row + (size_t) kw * src0->nb[0]); \
const int32_t base_iw = (int32_t) ox - p0 + (int32_t) kw; \
HVX_Vector in_v; \
\
if (base_iw >= 0) { \
in_v = hvx_vmemu(in_row + base_iw); \
} else { \
const int32_t pad = -base_iw; \
const HVX_Vector v = hvx_vmemu(in_row); \
in_v = Q6_V_valign_VVR(v, zero, 128 - (uint32_t) pad * sizeof(float)); \
} \
if (base_iw + 31 >= w) { \
const int32_t valid = w - base_iw; \
const HVX_VectorPred q = Q6_Q_vsetq_R(MAX(0, valid) * sizeof(float)); \
in_v = Q6_V_vmux_QVV(q, in_v, zero); \
} \
\
const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(in_v, w_v); \
switch (kw & 3) { \
case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \
case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \
case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \
case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \
} \
} \
} \
\
const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \
const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \
HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \
if (rem < 32) { \
const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \
acc_out = Q6_V_vmux_QVV(q, acc_out, zero); \
} \
\
hvx_vec_store_u(out_row + ox, nbytes, acc_out); \
} \
} \
}
DEFINE_CONV2D_DW_WHCN_S1(f32, conv2d_dw_splat_w_f32)
DEFINE_CONV2D_DW_WHCN_S1(f16, conv2d_dw_splat_w_f16)
#define DEFINE_CONV2D_DW_WHCN_S2(SUFFIX, SPLAT_W_FN) \
__attribute__((noinline)) \
static void conv2d_dw_whcn_s2_##SUFFIX( \
const float * in_vtcm, \
float * out_vtcm, \
const void * w_vtcm, \
const struct conv2d_dw_task_slice * slice, \
const struct htp_ops_context * octx, \
const struct htp_conv2d_dw_kernel_params * kp) { \
\
const struct htp_tensor * src0 = octx->src[0]; \
const char * w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \
const int32_t p0 = kp->p0; \
const int32_t p1 = kp->p1; \
const int32_t s1 = kp->s1; \
const int32_t d1 = kp->d1; \
const int32_t w = (int32_t) kp->w; \
const HVX_Vector zero = Q6_V_vzero(); \
\
for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \
const uint32_t oh = slice->oh_start + ohi; \
float * out_row = out_vtcm + (size_t) ohi * kp->ow; \
\
for (uint32_t ox = 0; ox < kp->ow; ox += 32) { \
const uint32_t rem = kp->ow - ox; \
const uint32_t nbytes = (rem < 32) ? (rem * sizeof(float)) : 128; \
HVX_Vector acc0 = zero; \
HVX_Vector acc1 = zero; \
HVX_Vector acc2 = zero; \
HVX_Vector acc3 = zero; \
\
for (uint32_t kh = 0; kh < kp->kh; ++kh) { \
const int32_t ih = (int32_t) (oh * s1 + kh * d1) - p1; \
if (ih < 0 || ih >= (int32_t) kp->h) { \
continue; \
} \
const float * in_row = in_vtcm + (size_t) (ih - slice->ih_first) * kp->w; \
const char * w_row = w_chan + (size_t) kh * src0->nb[1]; \
\
for (uint32_t kw = 0; kw < kp->kw; ++kw) { \
const HVX_Vector w_v = SPLAT_W_FN(w_row + (size_t) kw * src0->nb[0]); \
const int32_t base_iw = (int32_t) (2 * ox) - p0 + (int32_t) kw; \
HVX_Vector in_v; \
\
if (base_iw >= 0) { \
const HVX_Vector v0 = hvx_vmemu(in_row + base_iw); \
const HVX_Vector v1 = hvx_vmemu(in_row + base_iw + 32); \
in_v = Q6_V_lo_W(Q6_W_vdeal_VVR(v1, v0, -4)); \
} else { \
const int32_t pad = -base_iw; \
const HVX_Vector v0 = hvx_vmemu(in_row); \
const HVX_Vector v1 = hvx_vmemu(in_row + 32); \
const HVX_VectorPair vp = Q6_W_vdeal_VVR(v1, v0, -4); \
if (pad & 1) { \
const uint32_t shift_lanes = (uint32_t) (pad + 1) / 2; \
const HVX_Vector v_odd = Q6_V_hi_W(vp); \
in_v = Q6_V_valign_VVR(v_odd, zero, 128 - shift_lanes * sizeof(float)); \
} else { \
const uint32_t shift_lanes = (uint32_t) pad / 2; \
const HVX_Vector v_even = Q6_V_lo_W(vp); \
in_v = Q6_V_valign_VVR(v_even, zero, 128 - shift_lanes * sizeof(float)); \
} \
} \
if (base_iw + 62 >= w) { \
const int32_t valid = (w - base_iw + 1) / 2; \
const HVX_VectorPred q = Q6_Q_vsetq_R(MAX(0, valid) * sizeof(float)); \
in_v = Q6_V_vmux_QVV(q, in_v, zero); \
} \
\
const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(in_v, w_v); \
switch (kw & 3) { \
case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \
case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \
case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \
case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \
} \
} \
} \
\
const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \
const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \
HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \
if (rem < 32) { \
const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \
acc_out = Q6_V_vmux_QVV(q, acc_out, zero); \
} \
\
hvx_vec_store_u(out_row + ox, nbytes, acc_out); \
} \
} \
}
DEFINE_CONV2D_DW_WHCN_S2(f32, conv2d_dw_splat_w_f32)
DEFINE_CONV2D_DW_WHCN_S2(f16, conv2d_dw_splat_w_f16)
#define DEFINE_CONV2D_DW_CWHN(SUFFIX, LOAD_W_FN) \
__attribute__((noinline)) \
static void conv2d_dw_cwhn_##SUFFIX( \
const float * in_vtcm, \
float * out_vtcm, \
const void * w_vtcm, \
const struct conv2d_dw_task_slice * slice, \
const struct htp_ops_context * octx, \
const struct htp_conv2d_dw_kernel_params * kp) { \
\
const struct htp_tensor * src0 = octx->src[0]; \
const uint32_t in_row_stride = kp->w * kp->c; \
const uint32_t out_row_stride = kp->ow * kp->c; \
const HVX_Vector zero = Q6_V_vzero(); \
\
for (uint32_t cb = 0; cb < kp->c; cb += 32) { \
const uint32_t rem = MIN(32, kp->c - cb); \
const char * w_base = (const char *) w_vtcm + (size_t) cb * src0->nb[3]; \
\
for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \
const uint32_t oh = slice->oh_start + ohi; \
float * out_row = out_vtcm + (size_t) ohi * out_row_stride + cb; \
\
for (uint32_t ow = 0; ow < kp->ow; ++ow) { \
HVX_Vector acc0 = zero; \
HVX_Vector acc1 = zero; \
HVX_Vector acc2 = zero; \
HVX_Vector acc3 = zero; \
\
for (uint32_t kh = 0; kh < kp->kh; ++kh) { \
const int32_t ih = (int32_t)(oh * kp->s1 + kh * kp->d1) - kp->p1; \
if (ih < 0 || ih >= (int32_t)kp->h) { \
continue; \
} \
const float * in_row = in_vtcm + (size_t)(ih - slice->ih_first) * in_row_stride + cb; \
const char * w_row = w_base + (size_t) kh * src0->nb[1]; \
\
for (uint32_t kw = 0; kw < kp->kw; ++kw) { \
const int32_t iw = (int32_t)(ow * kp->s0 + kw * kp->d0) - kp->p0; \
if (iw < 0 || iw >= (int32_t)kp->w) { \
continue; \
} \
\
const float * in_ptr = in_row + (size_t) iw * kp->c; \
const char * w_ptr = w_row + (size_t) kw * src0->nb[0]; \
const HVX_Vector v_in = hvx_vmemu(in_ptr); \
const HVX_Vector v_w = LOAD_W_FN(w_ptr); \
const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(v_in, v_w); \
switch (kw & 3) { \
case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \
case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \
case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \
case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \
} \
} \
} \
\
const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \
const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \
const HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \
\
float * dst_ptr = out_row + (size_t) ow * kp->c; \
if (rem == 32) { \
hvx_vmemu(dst_ptr) = acc_out; \
} else { \
hvx_vec_store_u(dst_ptr, rem * sizeof(float), acc_out); \
} \
} \
} \
} \
}
DEFINE_CONV2D_DW_CWHN(f32, conv2d_dw_load_w_f32)
DEFINE_CONV2D_DW_CWHN(f16, conv2d_dw_load_w_f16)
typedef void (*conv2d_dw_compute_fn_t)(
const float * in_vtcm,
float * out_vtcm,
const void * w_vtcm,
const struct conv2d_dw_task_slice * slice,
const struct htp_ops_context * octx,
const struct htp_conv2d_dw_kernel_params * kp);
static const conv2d_dw_compute_fn_t conv2d_dw_kernels[HTP_CONV2D_DW_KERNEL_COUNT][2] = {
[HTP_CONV2D_DW_KERNEL_UNSUPPORTED] = { NULL, NULL },
[HTP_CONV2D_DW_KERNEL_CWHN] = { conv2d_dw_cwhn_f32, conv2d_dw_cwhn_f16 },
[HTP_CONV2D_DW_KERNEL_WHCN_S1] = { conv2d_dw_whcn_s1_f32, conv2d_dw_whcn_s1_f16 },
[HTP_CONV2D_DW_KERNEL_WHCN_S2] = { conv2d_dw_whcn_s2_f32, conv2d_dw_whcn_s2_f16 },
[HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3] = { conv2d_dw_whcn_s1_k3x3_f32, conv2d_dw_whcn_s1_k3x3_f16 },
[HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W32] = { conv2d_dw_whcn_s2_k3x3_w32_f32, conv2d_dw_whcn_s2_k3x3_w32_f16 },
[HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W64] = { conv2d_dw_whcn_s2_k3x3_w64_f32, conv2d_dw_whcn_s2_k3x3_w64_f16 },
[HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3] = { conv2d_dw_whcn_s2_k3x3_f32, conv2d_dw_whcn_s2_k3x3_f16 },
};
struct conv2d_dw_dma_context {
struct htp_ops_context * octx;
const struct htp_conv2d_dw_kernel_params * kp;
struct htp_conv2d_dw_vtcm_layout layout;
const void * w_vtcm;
conv2d_dw_compute_fn_t compute_fn;
uint32_t task_start;
uint32_t task_count;
uint32_t tasks_per_hvx;
};
static void conv2d_dw_dma_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
const struct conv2d_dw_dma_context * ctx = (const struct conv2d_dw_dma_context *) data;
const struct htp_ops_context * octx = ctx->octx;
const struct htp_conv2d_dw_kernel_params * kp = ctx->kp;
const struct htp_conv2d_dw_vtcm_layout * L = &ctx->layout;
const struct htp_tensor * src1 = octx->src[1];
const struct htp_tensor * dst = octx->dst;
conv2d_dw_compute_fn_t compute_fn = ctx->compute_fn;
const uint32_t first = ctx->task_start + ith * ctx->tasks_per_hvx;
const uint32_t last = MIN(first + ctx->tasks_per_hvx, ctx->task_start + ctx->task_count);
if (first >= last) {
return;
}
(void) nth;
struct htp_thread_trace * tr = th->trace;
dma_queue * dma_q = th->dma_q;
const uint32_t src_spad_half = (uint32_t) L->src_spad_half_size;
const uint32_t dst_spad_half = (uint32_t) L->dst_spad_half_size;
const uint32_t pad_top_stride = kp->pad_top_stride;
uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base;
uint8_t * src_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_src) + ith * L->src_bytes_per_hvx;
uint8_t * dst_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_dst) + ith * L->dst_bytes_per_hvx;
float * srcb2[2] = { (float *) src_spad, (float *) (src_spad + src_spad_half) };
float * dstb2[2] = { (float *) dst_spad, (float *) (dst_spad + dst_spad_half) };
struct conv2d_dw_task_slice sl2[2];
const uint32_t total = last - first;
for (uint32_t i = 0; i < total && i < 2; ++i) {
conv2d_dw_get_slice(&sl2[i], first + i, src1, dst, kp);
dma_queue_push(dma_q,
dma_make_data(dst->data, dstb2[i]),
sl2[i].dst_bytes, dst_spad_half,
sl2[i].dst_bytes, 0);
float * src_dst = srcb2[i] + (size_t) sl2[i].top_pad * pad_top_stride;
dma_queue_push(dma_q,
dma_make_data(src_dst, sl2[i].src_addr),
src_spad_half, sl2[i].src_bytes,
sl2[i].src_bytes, sl2[i].src_bytes > 0 ? 1 : 0);
}
for (uint32_t i = 0; i < total; ++i) {
const uint32_t task = first + i;
const uint32_t buf = i & 1u;
float * srcb = srcb2[buf];
float * dstb = dstb2[buf];
dma_queue_pop(dma_q);
dma_queue_pop(dma_q);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) task);
compute_fn(srcb, dstb, ctx->w_vtcm, &sl2[buf], octx, kp);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) task);
dma_queue_push(dma_q,
dma_make_data(sl2[buf].dst_addr, dstb),
sl2[buf].dst_bytes, dst_spad_half,
sl2[buf].dst_bytes, sl2[buf].dst_bytes > 0 ? 1 : 0);
if (i + 2 < total) {
conv2d_dw_get_slice(&sl2[buf], task + 2, src1, dst, kp);
float * src_dst = srcb + (size_t) sl2[buf].top_pad * pad_top_stride;
dma_queue_push(dma_q,
dma_make_data(src_dst, sl2[buf].src_addr),
src_spad_half, sl2[buf].src_bytes,
sl2[buf].src_bytes, sl2[buf].src_bytes > 0 ? 1 : 0);
}
}
dma_queue_flush(dma_q);
FARF(HIGH, "conv2d_dw-f32-dma %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n",
ith, nth, kp->w, kp->h, kp->c, dst->ne[3], kp->ow, kp->oh, kp->c, dst->ne[3], first, last);
}
int op_conv_2d_dw(struct htp_ops_context * octx) {
const struct htp_conv2d_dw_kernel_params * kp =
(const struct htp_conv2d_dw_kernel_params *) octx->kernel_params;
if (kp->total_tasks == 0) {
return HTP_STATUS_OK;
}
if (kp->kernel_type <= HTP_CONV2D_DW_KERNEL_UNSUPPORTED ||
kp->kernel_type >= HTP_CONV2D_DW_KERNEL_COUNT) {
return HTP_STATUS_NO_SUPPORT;
}
const uint32_t pad_rows = (kp->pad_top_stride > 0) ? 4 : 0;
const uint32_t max_ih_chunk = MIN(kp->h, (kp->oh_chunk - 1) * (uint32_t) kp->s1 + (kp->kh - 1) * (uint32_t) kp->d1 + 1);
const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * kp->row_src_bytes + 128;
const uint32_t max_dst_bytes = kp->oh_chunk * kp->row_dst_bytes + 128;
const struct htp_tensor * src0 = octx->src[0];
const bool is_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0;
const uint32_t elem_size = is_f16 ? sizeof(__fp16) : sizeof(float);
const uint32_t w_size = src0->size;
struct htp_conv2d_dw_vtcm_layout layout;
htp_conv2d_dw_vtcm_layout_build(&layout, max_src_bytes, max_dst_bytes, w_size, kp->n_hvx);
uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base;
void * w_vtcm = VTCM_LAYOUT_PTR(void, vtcm_base, layout.off_w);
struct htp_tensor w_vtcm_tensor = *src0;
w_vtcm_tensor.data = (dma_addr_t) w_vtcm;
if (src0->nb[0] == elem_size) {
dma_cpy_sametype_sameshape(octx->ctx->dma[0], &w_vtcm_tensor, src0, elem_size);
} else {
dma_sync_read(octx->ctx->dma[0], w_vtcm, src0->data, w_size);
}
dma_queue_flush(octx->ctx->dma[0]);
uint32_t task_start = 0;
uint32_t task_count = kp->total_tasks;
if (octx->ctx->mdev.count > 1) {
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
task_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
task_start = range.start;
task_count = range.count;
}
if (task_count == 0) {
return HTP_STATUS_OK;
}
const uint32_t nth = MIN(kp->n_hvx, task_count);
const uint32_t tasks_per_hvx = (task_count + nth - 1) / nth;
struct conv2d_dw_dma_context ctx = {
.octx = octx,
.kp = kp,
.layout = layout,
.w_vtcm = w_vtcm,
.compute_fn = conv2d_dw_kernels[kp->kernel_type][is_f16 ? 1 : 0],
.task_start = task_start,
.task_count = task_count,
.tasks_per_hvx = tasks_per_hvx,
};
work_queue_run(octx->ctx->hvx_queue, conv2d_dw_dma_thread, &ctx, nth);
return HTP_STATUS_OK;
}
-82
View File
@@ -88,88 +88,6 @@ static_assert(sizeof(struct htp_conv2d_kernel_params) <= 128, "htp_conv2d_kernel
_Static_assert(sizeof(struct htp_conv2d_kernel_params) <= 128, "htp_conv2d_kernel_params is too large for kernel_params blob");
#endif
enum htp_conv2d_dw_kernel_type {
HTP_CONV2D_DW_KERNEL_UNSUPPORTED = 0,
HTP_CONV2D_DW_KERNEL_CWHN, // CWHN channel-contiguous layout
HTP_CONV2D_DW_KERNEL_WHCN_S1, // WHCN general stride-1
HTP_CONV2D_DW_KERNEL_WHCN_S2, // WHCN general stride-2
HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3, // WHCN aligned w%32==0, 3x3 s=1 p=1 d=1
HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W32, // WHCN w=32->ow=16, 3x3 s=2 p=1 d=1 (2 rows per vector)
HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W64, // WHCN w=64->ow=32, 3x3 s=2 p=1 d=1 (1 vector rolling kh)
HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3, // WHCN aligned w%32==0 (w>=96), 3x3 s=2 p=1 d=1
HTP_CONV2D_DW_KERNEL_COUNT,
};
enum htp_conv2d_dw_flags {
HTP_CONV2D_DW_FLAG_CWHN = (1u << 0),
HTP_CONV2D_DW_FLAG_F16 = (1u << 1),
};
struct htp_conv2d_dw_kernel_params {
uint8_t kernel_type;
uint8_t flags; // bitmask of enum htp_conv2d_dw_flags
uint8_t n_hvx;
uint32_t total_tasks;
uint32_t vtcm_size;
uint32_t w;
uint32_t h;
uint32_t c;
uint32_t kw;
uint32_t kh;
uint32_t ow;
uint32_t oh;
int32_t s0;
int32_t s1;
int32_t p0;
int32_t p1;
int32_t d0;
int32_t d1;
uint32_t oh_chunk;
uint32_t n_chunks;
uint32_t row_src_bytes;
uint32_t row_dst_bytes;
uint32_t pad_top_stride;
struct fastdiv_values div_c;
struct fastdiv_values div_n_chunks;
};
#if defined(__cplusplus)
static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob");
#else
_Static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob");
#endif
struct htp_conv2d_dw_vtcm_layout {
size_t total_bytes;
size_t off_w;
size_t off_src;
size_t off_dst;
size_t src_spad_half_size;
size_t dst_spad_half_size;
size_t src_bytes_per_hvx;
size_t dst_bytes_per_hvx;
};
static inline void htp_conv2d_dw_vtcm_layout_build(
struct htp_conv2d_dw_vtcm_layout * L,
uint32_t max_src_bytes,
uint32_t max_dst_bytes,
uint32_t w_size,
uint32_t n_hvx
) {
L->src_spad_half_size = hex_round_up(max_src_bytes + 256, 128);
L->dst_spad_half_size = hex_round_up(max_dst_bytes + 128, 128);
L->src_bytes_per_hvx = 2 * L->src_spad_half_size;
L->dst_bytes_per_hvx = 2 * L->dst_spad_half_size;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_w, hex_round_up(w_size, 128));
VTCM_LAYOUT_ALLOC(off, off_src, L->src_bytes_per_hvx * n_hvx);
VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx);
L->total_bytes = off;
}
struct htp_conv2d_vtcm_layout {
size_t total_bytes;
size_t off_scales;
+57 -80
View File
@@ -338,11 +338,13 @@ struct ggml_backend_rpc_device_context {
};
struct ggml_backend_rpc_buffer_type_context {
std::string endpoint;
uint32_t device;
std::string name;
size_t alignment;
size_t max_size;
std::string endpoint;
uint32_t device;
std::string name;
size_t alignment;
size_t max_size;
std::mutex alloc_size_mutex;
std::unordered_map<uint64_t, size_t> alloc_size_cache;
};
class rpc_dispatcher;
@@ -372,6 +374,37 @@ static uint64_t fnv_hash(const uint8_t * data, size_t len, uint64_t hash = 0xcbf
return hash;
}
// full layout of the op and its sources, without ids, addresses, names and buffers
// used as the cache key for both supports_op and get_alloc_size
static uint64_t op_layout_key(const ggml_tensor * op) {
struct op_layout_key_tensor {
uint32_t type;
uint32_t op;
int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
int64_t ne[GGML_MAX_DIMS];
uint64_t nb[GGML_MAX_DIMS];
};
op_layout_key_tensor key[1 + GGML_MAX_SRC];
memset(key, 0, sizeof(key));
for (int i = 0; i < 1 + GGML_MAX_SRC; i++) {
const ggml_tensor * t = i == 0 ? op : op->src[i - 1];
if (t == nullptr) {
key[i].type = UINT32_MAX;
continue;
}
key[i].type = t->type;
if (i == 0) {
key[i].op = t->op;
memcpy(key[i].op_params, t->op_params, sizeof(key[i].op_params));
}
for (int j = 0; j < GGML_MAX_DIMS; j++) {
key[i].ne[j] = t->ne[j];
key[i].nb[j] = t->nb[j];
}
}
return fnv_hash((const uint8_t *)key, sizeof(key));
}
// builds a variable-size request; the buffer must not change once queued
struct rpc_writer {
std::shared_ptr<std::vector<uint8_t>> buf = std::make_shared<std::vector<uint8_t>>();
@@ -1156,43 +1189,15 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty
// TODO: change rpc_tensor nb to 64-bit int
const size_t min_size = ggml_nbytes(tensor);
// Cache key for calls to read the alloc_size.
// We deliberately exclude src tensor dimensions from the key because:
// 1. For CPU backends, alloc_size = ggml_nbytes(output) regardless of src shapes
// 2. For GPU backends, the reservation graph uses max dimensions, so the
// cached value from reservation is always >= any subsequent request
// 3. Including src dims causes cache misses per-ubatch (e.g. growing KV cache)
// which blocks the main thread behind in-flight GRAPH_COMPUTE commands
struct alloc_size_cache_key {
uint32_t device;
uint32_t type;
uint32_t op;
int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
uint32_t ne[GGML_MAX_DIMS];
uint64_t nb[GGML_MAX_DIMS];
};
alloc_size_cache_key key = {};
key.device = buft_ctx->device;
key.type = tensor->type;
key.op = tensor->op;
memcpy(key.op_params, tensor->op_params, sizeof(key.op_params));
for (int i = 0; i < GGML_MAX_DIMS; i++) {
key.ne[i] = (uint32_t)tensor->ne[i];
key.nb[i] = (uint64_t)tensor->nb[i];
}
uint64_t cache_hash = fnv_hash((const uint8_t *)&key, sizeof(key));
cache_hash = fnv_hash((const uint8_t *)buft_ctx->endpoint.data(), buft_ctx->endpoint.size(), cache_hash);
// alloc sizes are immutable for a given tensor configuration
static std::mutex cache_mutex;
static std::unordered_map<uint64_t, size_t> cache;
// alloc sizes are immutable for a given layout of the tensor and its srcs
// the srcs must be part of the key: some backends reserve extra memory that scales with a src,
// e.g. FLASH_ATTN_EXT with the KV length or TOP_K with nelements(src0)
// ref: https://github.com/ggml-org/llama.cpp/issues/30794
const uint64_t key = op_layout_key(tensor);
{
std::lock_guard<std::mutex> lock(cache_mutex);
auto it = cache.find(cache_hash);
if (it != cache.end()) {
std::lock_guard<std::mutex> lock(buft_ctx->alloc_size_mutex);
auto it = buft_ctx->alloc_size_cache.find(key);
if (it != buft_ctx->alloc_size_cache.end()) {
LOG_DBG3("[%s] cache hit: %s -> %s\n", __func__, rpc_log_format_tensor(tensor).c_str(),
rpc_log_format_size(it->second).c_str());
return std::max<size_t>(it->second, min_size);
@@ -1216,8 +1221,8 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty
const auto response = dispatcher->call<RPC_CMD_GET_ALLOC_SIZE>(request);
{
std::lock_guard<std::mutex> lock(cache_mutex);
cache[cache_hash] = response.alloc_size;
std::lock_guard<std::mutex> lock(buft_ctx->alloc_size_mutex);
buft_ctx->alloc_size_cache[key] = response.alloc_size;
}
LOG_DBG2("[%s] %s -> alloc_size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(),
@@ -1412,11 +1417,13 @@ ggml_backend_buffer_type_t ggml_backend_rpc_buffer_type(const char * endpoint, u
size_t alignment = get_alignment(dispatcher, device);
size_t max_size = get_max_size(dispatcher, device);
ggml_backend_rpc_buffer_type_context * buft_ctx = new ggml_backend_rpc_buffer_type_context {
/* .endpoint = */ endpoint,
/* .device = */ device,
/* .name = */ buft_name,
/* .alignment = */ alignment,
/* .max_size = */ max_size
/* .endpoint = */ endpoint,
/* .device = */ device,
/* .name = */ buft_name,
/* .alignment = */ alignment,
/* .max_size = */ max_size,
/* .alloc_size_mutex = */ {},
/* .alloc_size_cache = */ {},
};
auto reg = ggml_backend_rpc_add_server(endpoint);
ggml_backend_buffer_type_t buft = new ggml_backend_buffer_type {
@@ -2891,36 +2898,6 @@ static ggml_backend_buffer_type_t ggml_backend_rpc_device_get_buffer_type(ggml_b
GGML_UNUSED(dev);
}
// full layout of the op and its sources, without ids, addresses, names and buffers
static uint64_t supports_op_key(const ggml_tensor * op) {
struct supports_op_key_tensor {
uint32_t type;
uint32_t op;
int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
int64_t ne[GGML_MAX_DIMS];
uint64_t nb[GGML_MAX_DIMS];
};
supports_op_key_tensor key[1 + GGML_MAX_SRC];
memset(key, 0, sizeof(key));
for (int i = 0; i < 1 + GGML_MAX_SRC; i++) {
const ggml_tensor * t = i == 0 ? op : op->src[i - 1];
if (t == nullptr) {
key[i].type = UINT32_MAX;
continue;
}
key[i].type = t->type;
if (i == 0) {
key[i].op = t->op;
memcpy(key[i].op_params, t->op_params, sizeof(key[i].op_params));
}
for (int j = 0; j < GGML_MAX_DIMS; j++) {
key[i].ne[j] = t->ne[j];
key[i].nb[j] = t->nb[j];
}
}
return fnv_hash((const uint8_t *)key, sizeof(key));
}
// ask the server about the whole graph in a single round trip, unless every node already has an answer
static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev, const struct ggml_cgraph * graph) {
ggml_backend_rpc_device_context * ctx = (ggml_backend_rpc_device_context *)dev->context;
@@ -2934,7 +2911,7 @@ static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev,
{
std::lock_guard<std::mutex> lock(ctx->supports_op_mutex);
for (int i = 0; i < graph->n_nodes; i++) {
keys[i] = supports_op_key(graph->nodes[i]);
keys[i] = op_layout_key(graph->nodes[i]);
all_cached = all_cached && ctx->supports_op_cache.count(keys[i]) > 0;
}
}
@@ -2955,7 +2932,7 @@ static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev,
// cached answer if the layout was seen, else ask the server about this op
static bool ggml_backend_rpc_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
ggml_backend_rpc_device_context * ctx = (ggml_backend_rpc_device_context *)dev->context;
const uint64_t key = supports_op_key(op);
const uint64_t key = op_layout_key(op);
{
std::lock_guard<std::mutex> lock(ctx->supports_op_mutex);
auto it = ctx->supports_op_cache.find(key);
@@ -825,6 +825,7 @@ struct vk_op_ssm_scan_push_constants {
uint32_t nb02, nb03, nb12, nb13;
uint32_t nb21, nb22, nb31;
uint32_t nb42, nb43, nb52, nb53;
uint32_t off0, off1, off2, off3, off4, off5, off6; // bytes from each source's binding to its data
uint32_t s_off;
uint32_t n_head, d_head, n_group, n_tok;
uint32_t n_seq, K;
+7
View File
@@ -829,6 +829,7 @@ struct vk_device_struct {
bool coopmat2;
bool coopmat2_bf16_support {};
bool coopmat2_gdn_support {};
bool coopmat2_ssm_support {};
bool coopmat2_decode_vector;
uint32_t coopmat2_reserved_shmem {};
@@ -1033,6 +1034,7 @@ struct vk_device_struct {
vk_pipeline pipeline_snake_f16;
vk_pipeline pipeline_snake_bf16;
vk_pipeline pipeline_pool1d_f32;
vk_pipeline pipeline_pool1d_subgroup_f32;
vk_pipeline pipeline_pool2d_f32;
vk_pipeline pipeline_pool2d_subgroup_f32;
vk_pipeline pipeline_rwkv_wkv6_f32;
@@ -1047,6 +1049,11 @@ struct vk_device_struct {
vk_pipeline pipeline_ssm_scan_f32_d96;
vk_pipeline pipeline_ssm_scan_f32_d128;
vk_pipeline pipeline_ssm_scan_f32_d256;
vk_pipeline pipeline_ssm_scan_prefill_f32_d96;
vk_pipeline pipeline_ssm_scan_prefill_f32_d128;
vk_pipeline pipeline_ssm_scan_prefill_f32_d256;
vk_pipeline pipeline_ssm_scan_cm2_f32_d96;
vk_pipeline pipeline_ssm_scan_cm2_f32_d128;
vk_pipeline pipeline_ssm_conv_f32;
vk_pipeline pipeline_ssm_conv_silu_f32;
vk_pipeline pipeline_ssm_conv_bias_silu_f32;
+159 -20
View File
@@ -1759,6 +1759,61 @@ static uint32_t ggml_vk_gated_delta_net_shmem_size(uint32_t v, bool coopmat2, bo
return qk + state + p_inv + delta_solved + lower + scan;
}
// Specialization constants of ssm_scan_cm2.comp and ssm_scan_prefill.comp.
static constexpr uint32_t GGML_VK_SSM_CM2_T = 32;
static constexpr uint32_t GGML_VK_SSM_CM2_ROWS = 32;
static constexpr uint32_t GGML_VK_SSM_PREFILL_WG_SIZE = 128;
static constexpr uint32_t GGML_VK_SSM_PREFILL_LPR = 16;
static constexpr uint32_t GGML_VK_SSM_PREFILL_R = 2;
#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
static constexpr uint32_t GGML_VK_SSM_CM2_WG_SIZE = 128;
static constexpr uint32_t GGML_VK_SSM_CM2_PAD = 8;
static uint32_t ggml_vk_ssm_scan_cm2_shmem_size(uint32_t d_state) {
const uint32_t T = GGML_VK_SSM_CM2_T;
const uint32_t rows = GGML_VK_SSM_CM2_ROWS;
const uint32_t pad = GGML_VK_SSM_CM2_PAD;
const uint32_t f16_size = sizeof(ggml_fp16_t);
const uint32_t c_b = 2 * T * (d_state + pad) * f16_size;
const uint32_t s = rows * (d_state + pad) * f16_size;
const uint32_t x = 3 * T * (rows + pad) * f16_size;
const uint32_t m = T * (T + pad) * f16_size;
const uint32_t scan = 2 * T * sizeof(float);
return c_b + s + x + m + scan;
}
#endif
// d_state must be a multiple of 4 * LPR.
static constexpr uint32_t ggml_vk_ssm_scan_prefill_lpr(uint32_t d_state) {
return d_state % (4 * GGML_VK_SSM_PREFILL_LPR) == 0 ? GGML_VK_SSM_PREFILL_LPR : GGML_VK_SSM_PREFILL_LPR / 2;
}
static constexpr uint32_t ggml_vk_ssm_scan_prefill_rows(uint32_t d_state) {
return GGML_VK_SSM_PREFILL_WG_SIZE / ggml_vk_ssm_scan_prefill_lpr(d_state) * GGML_VK_SSM_PREFILL_R;
}
// Tokens per chunk. 16 at d_state 128 uses enough shared memory to lower the occupancy on AMD.
static constexpr uint32_t ggml_vk_ssm_scan_prefill_tokens(uint32_t d_state) {
return d_state == 96 ? 16 : 8;
}
template <uint32_t d_state>
static constexpr uint32_t ggml_vk_ssm_scan_prefill_shmem_size() {
constexpr uint32_t T = ggml_vk_ssm_scan_prefill_tokens(d_state);
constexpr uint32_t rows = ggml_vk_ssm_scan_prefill_rows(d_state);
constexpr uint32_t wg = GGML_VK_SSM_PREFILL_WG_SIZE;
constexpr uint32_t lpr = ggml_vk_ssm_scan_prefill_lpr(d_state);
static_assert((lpr & (lpr - 1)) == 0 && wg % lpr == 0);
static_assert(d_state % (4 * lpr) == 0);
static_assert((T * d_state / 4) % wg == 0 && rows % 4 == 0 && T * rows / 4 <= wg);
static_assert((T * GGML_VK_SSM_PREFILL_R) % lpr == 0);
return 2 * T * (2 * d_state + rows + 1) * sizeof(float);
}
static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
uint32_t lut_size = 0;
@@ -4299,7 +4354,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_snake_f16, "snake_f16", snake_f16_len, snake_f16_data, "main", 4, sizeof(vk_op_snake_push_constants), {256, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_snake_bf16, "snake_bf16", snake_bf16_len, snake_bf16_data, "main", 4, sizeof(vk_op_snake_push_constants), {256, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_pool1d_f32, "pool1d_f32", pool1d_f32_len, pool1d_f32_data, "main", 2, sizeof(vk_op_pool1d_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_pool1d_f32, "pool1d_f32", pool1d_f32_len, pool1d_f32_data, "main", 2, sizeof(vk_op_pool1d_push_constants), {1, 1, 1}, {512}, 1);
if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
ggml_vk_create_pipeline(device, device->pipeline_pool1d_subgroup_f32, "pool1d_subgroup_f32", pool1d_subgroup_f32_len, pool1d_subgroup_f32_data, "main", 2, sizeof(vk_op_pool1d_push_constants), {1, 1, 1}, {128}, 1, false, true, device->subgroup_size);
}
ggml_vk_create_pipeline(device, device->pipeline_pool2d_f32, "pool2d_f32", pool2d_f32_len, pool2d_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {1, 1, 1}, {512}, 1);
if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
ggml_vk_create_pipeline(device, device->pipeline_pool2d_subgroup_f32, "pool2d_subgroup_f32", pool2d_subgroup_f32_len, pool2d_subgroup_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {1, 1, 1}, {128}, 1, false, true, device->subgroup_size);
@@ -4467,6 +4525,35 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true);
}
// The prefill shader spills and is slower than the per-token shader on Intel.
if (device->vendor_id != VK_VENDOR_ID_INTEL &&
device->subgroup_shuffle && device->subgroup_require_full_support &&
device->subgroup_size >= GGML_VK_SSM_PREFILL_LPR &&
device->properties.limits.maxComputeWorkGroupInvocations >= GGML_VK_SSM_PREFILL_WG_SIZE &&
device->properties.limits.maxComputeWorkGroupSize[0] >= GGML_VK_SSM_PREFILL_WG_SIZE) {
const uint32_t max_shmem = device->properties.limits.maxComputeSharedMemorySize;
if (ggml_vk_ssm_scan_prefill_shmem_size<96>() <= max_shmem) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d96, "ssm_scan_prefill_d96_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_PREFILL_WG_SIZE, 96, ggml_vk_ssm_scan_prefill_tokens(96), ggml_vk_ssm_scan_prefill_lpr(96), GGML_VK_SSM_PREFILL_R}, 1, true, true);
}
if (ggml_vk_ssm_scan_prefill_shmem_size<128>() <= max_shmem) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d128, "ssm_scan_prefill_d128_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_PREFILL_WG_SIZE, 128, ggml_vk_ssm_scan_prefill_tokens(128), ggml_vk_ssm_scan_prefill_lpr(128), GGML_VK_SSM_PREFILL_R}, 1, true, true);
}
if (ggml_vk_ssm_scan_prefill_shmem_size<256>() <= max_shmem) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d256, "ssm_scan_prefill_d256_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_PREFILL_WG_SIZE, 256, ggml_vk_ssm_scan_prefill_tokens(256), ggml_vk_ssm_scan_prefill_lpr(256), GGML_VK_SSM_PREFILL_R}, 1, true, true);
}
}
#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
if (device->coopmat2 && device->coopmat2_ssm_support) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_cm2_f32_d96, "ssm_scan_cm2_d96_f32", ssm_scan_f32_cm2_len, ssm_scan_f32_cm2_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_CM2_WG_SIZE, 96, GGML_VK_SSM_CM2_T, GGML_VK_SSM_CM2_ROWS, GGML_VK_SSM_CM2_PAD}, 1, true, true, GGML_VK_SSM_CM2_T);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_cm2_f32_d128, "ssm_scan_cm2_d128_f32", ssm_scan_f32_cm2_len, ssm_scan_f32_cm2_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_CM2_WG_SIZE, 128, GGML_VK_SSM_CM2_T, GGML_VK_SSM_CM2_ROWS, GGML_VK_SSM_CM2_PAD}, 1, true, true, GGML_VK_SSM_CM2_T);
}
#endif
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1);
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_f32, "ssm_conv_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 1}, 1);
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_bias_silu_f32, "ssm_conv_bias_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 1, 1}, 1);
@@ -5448,6 +5535,16 @@ vk_device ggml_vk_get_device(size_t idx) {
found_fp32_128 = true;
}
}
// The SSM scan's matrix dimensions are d_state (96 or 128), T and ROWS.
const auto ssm_dims_ok = [](uint32_t g) {
return g != 0 && 96 % g == 0 && 128 % g == 0 && GGML_VK_SSM_CM2_T % g == 0 && GGML_VK_SSM_CM2_ROWS % g == 0;
};
if (prop.workgroupInvocations == GGML_VK_SSM_CM2_WG_SIZE &&
prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
ssm_dims_ok(prop.MGranularity) && ssm_dims_ok(prop.NGranularity) && ssm_dims_ok(prop.KGranularity)) {
device->coopmat2_ssm_support = true;
}
if (prop.workgroupInvocations == 256 &&
prop.MGranularity <= 32 &&
prop.NGranularity <= 32 &&
@@ -5493,6 +5590,15 @@ vk_device ggml_vk_get_device(size_t idx) {
#endif
}
}
// The shared memory of d_state 128 also covers 96.
device->coopmat2_ssm_support = device->coopmat2_ssm_support &&
coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= GGML_VK_SSM_CM2_WG_SIZE &&
device->properties.limits.maxComputeWorkGroupInvocations >= GGML_VK_SSM_CM2_WG_SIZE &&
device->properties.limits.maxComputeWorkGroupSize[0] >= GGML_VK_SSM_CM2_WG_SIZE &&
device->subgroup_size_control &&
device->subgroup_min_size <= GGML_VK_SSM_CM2_T && GGML_VK_SSM_CM2_T <= device->subgroup_max_size &&
uint64_t(ggml_vk_ssm_scan_cm2_shmem_size(128)) + coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory <=
device->properties.limits.maxComputeSharedMemorySize;
device->coopmat2_gdn_support = device->coopmat2_gdn_support &&
coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= 128 &&
device->properties.limits.maxComputeWorkGroupInvocations >= 128 &&
@@ -10845,6 +10951,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
}
case GGML_OP_POOL_1D:
if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
if (ctx->device->pipeline_pool1d_subgroup_f32 && dst->op_params[1] >= int32_t(ctx->device->subgroup_size)) {
return ctx->device->pipeline_pool1d_subgroup_f32;
}
return ctx->device->pipeline_pool1d_f32;
}
return nullptr;
@@ -11298,10 +11407,12 @@ static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, co
} break;
case GGML_OP_POOL_1D:
{
const uint32_t N = dst->ne[3] * dst->ne[2];
const uint32_t OC = dst->ne[1];
const uint32_t OL = dst->ne[0];
elements = { N * OC * OL, 1, 1};
const uint32_t outputs = ggml_nelements(dst);
const uint32_t outputs_per_workgroup = pipeline == ctx->device->pipeline_pool1d_subgroup_f32 ? 128 / ctx->device->subgroup_size : 512;
const uint32_t workgroups = CEIL_DIV(outputs, outputs_per_workgroup);
const uint32_t groups_y = CEIL_DIV(workgroups, ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
const uint32_t groups_x = CEIL_DIV(workgroups, groups_y);
elements = { groups_x, groups_y, 1 };
} break;
case GGML_OP_POOL_2D:
{
@@ -12249,7 +12360,40 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
bool is_mamba2 = (src3->nb[1] == sizeof(float));
GGML_ASSERT(is_mamba2);
// The shaders add each source's offset from its aligned binding.
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
vk_subbuffer src_buf[7] = {};
uint32_t src_off[7] = {};
for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i], true);
src_off[i] = get_misalign_bytes(ctx, dst->src[i]);
}
const uint32_t d_state = src0->ne[0];
const uint32_t K = (uint32_t) ggml_get_op_params_i32(dst, 0);
// The prefill shaders read x, B and C as vec4.
auto vec4_aligned = [&](int i) {
const ggml_tensor * t = dst->src[i];
return src_off[i] % 16 == 0 && t->nb[2] % 16 == 0 && t->nb[3] % 16 == 0;
};
const bool vec4 = head_dim % 4 == 0 && vec4_aligned(1) && vec4_aligned(4) && vec4_aligned(5);
vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
uint32_t prefill_rows = 0;
if (vec4 && K <= 1 && n_tok >= 8) {
vk_pipeline cm2 = d_state == 96 ? ctx->device->pipeline_ssm_scan_cm2_f32_d96 :
d_state == 128 ? ctx->device->pipeline_ssm_scan_cm2_f32_d128 : nullptr;
vk_pipeline prefill = d_state == 96 ? ctx->device->pipeline_ssm_scan_prefill_f32_d96 :
d_state == 128 ? ctx->device->pipeline_ssm_scan_prefill_f32_d128 :
d_state == 256 ? ctx->device->pipeline_ssm_scan_prefill_f32_d256 : nullptr;
if (n_tok >= GGML_VK_SSM_CM2_T && cm2) {
pipeline = cm2;
prefill_rows = GGML_VK_SSM_CM2_ROWS;
} else if (prefill) {
pipeline = prefill;
prefill_rows = ggml_vk_ssm_scan_prefill_rows(d_state);
}
}
GGML_ASSERT(pipeline != nullptr);
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
@@ -12263,24 +12407,19 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
(uint32_t)src3->nb[1],
(uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
(uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
src_off[0], src_off[1], src_off[2], src_off[3], src_off[4], src_off[5], src_off[6],
(uint32_t)s_off,
n_head, head_dim, n_group, n_tok,
n_seq, (uint32_t) ggml_get_op_params_i32(dst, 0)
n_seq, K
};
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
vk_subbuffer src_buf[7] = {};
for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
}
std::array<uint32_t, 3> elements;
const uint32_t d_state = src0->ne[0];
uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size;
const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups);
const uint32_t num_workgroups_y = n_seq;
elements = { num_workgroups_x, num_workgroups_y, 1 };
if (prefill_rows) {
elements = { CEIL_DIV(head_dim, prefill_rows), n_head, n_seq };
} else {
const uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size;
elements = { CEIL_DIV(n_head * head_dim, num_subgroups), n_seq, 1 };
}
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
@@ -18082,14 +18221,14 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
case GGML_OP_SSM_SCAN:
{
for (int i = 0; i < 6; i++) {
if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
if (op->src[i]->type != GGML_TYPE_F32) {
return false;
}
}
if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
return false;
}
if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
if (op->type != GGML_TYPE_F32) {
return false;
}
@@ -22,6 +22,16 @@ layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
#error unimplemented
#endif
// Hoisting pays off when the per-block unpack is expensive (K-quants and
// i-quants). For the legacy 4/8-bit types the unpack is already cheap and the
// indexed a_tile array can spill on some drivers, so keep those on the base
// per-column path.
#if defined(DATA_A_QUANT_LEGACY) || defined(DATA_A_MXFP4)
#define MMVQ_USE_HOIST 0
#else
#define MMVQ_USE_HOIST 1
#endif
uint a_offset, b_offset, d_offset;
int32_t cache_b_qs[K_PER_ITER / 4];
@@ -30,6 +40,17 @@ vec2 cache_b_ds;
#include "mul_mat_vecq_funcs.glsl"
void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const uint num_rows, const uint col, const uint b_qs_idx) {
#if MMVQ_USE_HOIST
// Load and unpack the weight block once per row, then reuse it for all columns.
a_tile a_tiles[NUM_ROWS];
uint ibi = first_row*p.ncols;
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
const uint a_block_idx = (ibi + col)/QUANT_K_Q8_1 + a_offset;
ibi += p.ncols;
a_tiles[n] = load_a_tile(a_block_idx, b_qs_idx);
}
#endif
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
// Preload data_b block
const uint b_block_idx = (j*p.batch_stride_b + col) / QUANT_K_Q8_1 + b_offset;
@@ -64,13 +85,18 @@ void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const
#endif
#endif
#if MMVQ_USE_HOIST
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
temp[j][n] += dot_a_tile(a_tiles[n]);
}
#else
uint ibi = first_row*p.ncols;
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
const uint a_block_idx = (ibi + col)/QUANT_K_Q8_1 + a_offset;
ibi += p.ncols;
temp[j][n] += mmvq_dot_product(a_block_idx, b_qs_idx);
}
#endif
}
}
@@ -137,6 +163,13 @@ void main() {
if (first_row >= p.stride_d) {
return;
}
#if MMVQ_USE_HOIST
// Pass the known tail size to allow unrolling.
if (NUM_ROWS == 2u) {
compute_outputs(first_row, 1u);
return;
}
#endif
compute_outputs(first_row, p.stride_d - first_row);
}
}
@@ -158,38 +158,63 @@ FLOAT_TYPE mul_q8_1(const int32_t q_sum, const float da, const vec2 dsb, const i
#endif
#if defined(DATA_A_Q2_0)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
FLOAT_TYPE dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs), get_dm(ib_a));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
// 16 quants per call => divide sums by 32/16 = 2
return mul_q8_1(q_sum, get_dm(ib_a), cache_b_ds, 2);
return mul_q8_1(q_sum, t.dm, cache_b_ds, 2);
}
#elif defined(DATA_A_QUANT_LEGACY) || defined(DATA_A_MXFP4)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
int32_t q_sum = 0;
#if defined(DATA_A_Q4_1) || defined(DATA_A_Q5_1)
#define A_TILE_DM_TYPE FLOAT_TYPEV2
#else
// Q4_0/Q5_0/Q8_0/MXFP4 only need the scale. Keeping a scalar here avoids
// broadcasting it to a vec2 and carrying the unused component across the
// column loop.
#define A_TILE_DM_TYPE FLOAT_TYPE
#endif
struct a_tile {
int32_t qs0;
int32_t qs1;
A_TILE_DM_TYPE dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
a_tile t;
#if QUANT_R == 2
const i32vec2 data_a_qs = repack(ib_a, iqs);
q_sum += dotPacked4x8EXT(data_a_qs.x,
cache_b_qs[0]);
q_sum += dotPacked4x8EXT(data_a_qs.y,
cache_b_qs[1]);
t.qs0 = data_a_qs.x;
t.qs1 = data_a_qs.y;
#else
int32_t data_a_qs = repack(ib_a, iqs * 2);
q_sum += dotPacked4x8EXT(data_a_qs,
cache_b_qs[0]);
data_a_qs = repack(ib_a, iqs * 2 + 1);
q_sum += dotPacked4x8EXT(data_a_qs,
cache_b_qs[1]);
t.qs0 = repack(ib_a, iqs * 2);
t.qs1 = repack(ib_a, iqs * 2 + 1);
#endif
t.dm = get_dm(ib_a);
return t;
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
q_sum += dotPacked4x8EXT(t.qs0, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs1, cache_b_qs[1]);
// 2 quants per call => divide sums by 8/2 = 4
return mul_q8_1(q_sum, get_dm(ib_a), cache_b_ds, 4);
return mul_q8_1(q_sum, t.dm, cache_b_ds, 4);
}
#undef A_TILE_DM_TYPE
#endif
#if defined(DATA_A_Q2_K)
@@ -214,28 +239,35 @@ uint8_t get_scale(uint ib, uint iqs) {
return data_a[ib_k].scales[iqs_k / 4];
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
int32_t scale;
vec2 dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), int32_t(get_scale(ib_a, iqs * 4)), vec2(get_dm(ib_a)));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t sum_d = 0;
int32_t sum_m = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const uint8_t scale = get_scale(ib_a, iqs * 4);
const vec2 dm = vec2(get_dm(ib_a));
const int32_t scale_m = int32_t(scale >> 4) * 0x01010101; // Duplicate 8-bit value across 32-bits.
const int32_t scale_m = int32_t(t.scale >> 4) * 0x01010101; // Duplicate 8-bit value across 32-bits.
sum_d += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[0]);
sum_d += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[1]);
sum_d += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[2]);
sum_d += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * (float(dm.x) * float(sum_d) - float(dm.y) * float(sum_m)));
return FLOAT_TYPE(float(cache_b_ds.x) * (float(t.dm.x) * float(sum_d) - float(t.dm.y) * float(sum_m)));
}
#endif
@@ -295,18 +327,24 @@ float get_d_scale(uint ib, uint iqs) {
return float(data_a[ib_k].d) * float(scale - 32);
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
float d_scale;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), get_d_scale(ib_a, iqs * 4));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const float d_scale = get_d_scale(ib_a, iqs * 4);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * d_scale * float(q_sum));
return FLOAT_TYPE(float(cache_b_ds.x) * t.d_scale * float(q_sum));
}
#endif
@@ -365,18 +403,24 @@ vec2 get_dm_scale(uint ib, uint iqs) {
return FLOAT_TYPEV2(data_a_packed32[ib_k].dm) * FLOAT_TYPEV2(scale_dm);
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
vec2 dm_scale;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), get_dm_scale(ib_a, iqs * 4));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const vec2 dm_scale = get_dm_scale(ib_a, iqs * 4);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * float(dm_scale.x) * float(q_sum) - float(dm_scale.y) * float(cache_b_ds.y / 2));
return FLOAT_TYPE(float(cache_b_ds.x) * float(t.dm_scale.x) * float(q_sum) - float(t.dm_scale.y) * float(cache_b_ds.y / 2));
}
#endif
@@ -433,40 +477,67 @@ float get_d_scale(uint ib, uint iqs) {
return float(data_a[ib_k].d) * float(data_a[ib_k].scales[iqs_k / 4]);
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
float d_scale;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), get_d_scale(ib_a, iqs * 4));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const float d_scale = get_d_scale(ib_a, iqs * 4);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * float(d_scale) * float(q_sum));
return FLOAT_TYPE(float(cache_b_ds.x) * float(t.d_scale) * float(q_sum));
}
#endif
#if defined(DATA_A_IQ4_XS)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
uvec4 qs;
float d;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
const uint ib = ib_a / 8;
const uint ib32 = ib_a % 8;
int32_t q_sum = 0;
[[unroll]] for (uint j = 0; j < 4; ++j) {
const uint32_t vui = data_a_packed32[ib].qs[4 * ib32 + j];
const i32vec2 qs_a = iq4nl_to_i8x8(vui);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[j]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[j + 4]);
}
a_tile t;
t.qs.x = data_a_packed32[ib].qs[4 * ib32 + 0];
t.qs.y = data_a_packed32[ib].qs[4 * ib32 + 1];
t.qs.z = data_a_packed32[ib].qs[4 * ib32 + 2];
t.qs.w = data_a_packed32[ib].qs[4 * ib32 + 3];
const uint sl = (data_a_packed32[ib].scales_l >> (4 * ib32)) & 0xF;
const uint sh = (data_a_packed32[ib].scales_h >> (2 * ib32)) & 3;
const float d = float(data_a[ib].d) * float(int(sl | (sh << 4)) - 32);
t.d = float(data_a[ib].d) * float(int(sl | (sh << 4)) - 32);
return FLOAT_TYPE(float(cache_b_ds.x) * d * float(q_sum));
return t;
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec2 qs_a0 = iq4nl_to_i8x8(t.qs.x);
const i32vec2 qs_a1 = iq4nl_to_i8x8(t.qs.y);
const i32vec2 qs_a2 = iq4nl_to_i8x8(t.qs.z);
const i32vec2 qs_a3 = iq4nl_to_i8x8(t.qs.w);
q_sum += dotPacked4x8EXT(qs_a0.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a0.y, cache_b_qs[4]);
q_sum += dotPacked4x8EXT(qs_a1.x, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a1.y, cache_b_qs[5]);
q_sum += dotPacked4x8EXT(qs_a2.x, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a2.y, cache_b_qs[6]);
q_sum += dotPacked4x8EXT(qs_a3.x, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a3.y, cache_b_qs[7]);
return FLOAT_TYPE(float(cache_b_ds.x) * t.d * float(q_sum));
}
#endif
@@ -517,33 +588,50 @@ vec2 get_dm(uint ib, uint iqs) {
return FLOAT_TYPEV2(dl, dl * (delta - 1));
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
int32_t q_sum = 0;
struct a_tile {
i32vec4 qs0;
i32vec4 qs1;
vec2 dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
const uint ib_k = ib_a / 8;
const uint iqs_k = (ib_a % 8) * 32 + iqs * 32;
i32vec4 qs_a0;
i32vec4 qs_a1;
repack8(ib_k, iqs_k, qs_a0, qs_a1);
a_tile t;
repack8(ib_k, iqs_k, t.qs0, t.qs1);
t.dm = get_dm(ib_k, iqs_k);
return t;
}
const vec2 dm = get_dm(ib_k, iqs_k);
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
q_sum += dotPacked4x8EXT(qs_a0.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a0.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a0.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a0.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a1.x, cache_b_qs[4]);
q_sum += dotPacked4x8EXT(qs_a1.y, cache_b_qs[5]);
q_sum += dotPacked4x8EXT(qs_a1.z, cache_b_qs[6]);
q_sum += dotPacked4x8EXT(qs_a1.w, cache_b_qs[7]);
q_sum += dotPacked4x8EXT(t.qs0.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs0.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs0.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs0.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(t.qs1.x, cache_b_qs[4]);
q_sum += dotPacked4x8EXT(t.qs1.y, cache_b_qs[5]);
q_sum += dotPacked4x8EXT(t.qs1.z, cache_b_qs[6]);
q_sum += dotPacked4x8EXT(t.qs1.w, cache_b_qs[7]);
return FLOAT_TYPE(float(cache_b_ds.x) * float(dm.x) * float(q_sum) + float(dm.y) * float(cache_b_ds.y));
return FLOAT_TYPE(float(cache_b_ds.x) * float(t.dm.x) * float(q_sum) + float(t.dm.y) * float(cache_b_ds.y));
}
#endif
#if defined(DATA_A_IQ1_M)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
float dl0;
float dl1;
int32_t grid0;
int32_t grid1;
int32_t grid2;
int32_t grid3;
uint qh16;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
const uint ib_k = ib_a / 8;
const uint iqs_k = (ib_a % 8) * 32 + iqs * 32;
@@ -556,17 +644,25 @@ FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
const uint qs32 = data_a_packed32[ib_k].qs[ib32];
const uint qh16 = data_a_packed16[ib_k].qh[ib32];
float sum = 0;
const uint sc = data_a[ib_k].scales[ib64];
[[unroll]] for (int l = 0; l < 4; ++l) {
const uint ib16 = 2 * ib32 + l / 2;
const float dl = d * (2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1);
const uint qh = qh16 >> (4 * l);
const uint qs = (qs32 >> (8 * l)) & 0xFF;
const float delta = ((qh & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA;
const int32_t grid = int32_t(iq1s_grid_gpu[qs | ((qh & 7) << 8)]);
a_tile t;
t.dl0 = d * (2 * bitfieldExtract(sc, 3 * int((2 * ib32) & 3), 3) + 1);
t.dl1 = d * (2 * bitfieldExtract(sc, 3 * int((2 * ib32 + 1) & 3), 3) + 1);
t.qh16 = qh16;
t.grid0 = int32_t(iq1s_grid_gpu[(qs32 & 0xFF) | ((qh16 & 7) << 8)]);
t.grid1 = int32_t(iq1s_grid_gpu[((qs32 >> 8) & 0xFF) | (((qh16 >> 4) & 7) << 8)]);
t.grid2 = int32_t(iq1s_grid_gpu[((qs32 >> 16) & 0xFF) | (((qh16 >> 8) & 7) << 8)]);
t.grid3 = int32_t(iq1s_grid_gpu[((qs32 >> 24) & 0xFF) | (((qh16 >> 12) & 7) << 8)]);
return t;
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
float sum = 0;
[[unroll]] for (int l = 0; l < 4; ++l) {
const float dl = (l < 2) ? t.dl0 : t.dl1;
const int32_t grid = (l == 0) ? t.grid0 : (l == 1) ? t.grid1 : (l == 2) ? t.grid2 : t.grid3;
const float delta = (((t.qh16 >> (4 * l)) & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA;
int32_t q_sum = 0;
q_sum += dotPacked4x8EXT((grid >> 0) & 0x0F0F0F0F, cache_b_qs[2 * l + 0]);
@@ -584,3 +680,9 @@ FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
return sum;
}
#endif
// Non-hoisted path (legacy 4/8-bit types): reproduce the base per-column
// load+dot without an indexed a_tile array.
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
return dot_a_tile(load_a_tile(ib_a, iqs));
}
@@ -1,5 +1,10 @@
#version 450
#if defined(USE_SUBGROUP)
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_arithmetic : require
#endif
#include "types.glsl"
#extension GL_EXT_shader_16bit_storage : require
@@ -15,18 +20,27 @@ layout(push_constant) uniform parameter {
int p0;
} p;
#define BLOCK_SIZE 512
layout(constant_id = 0) const uint BLOCK_SIZE = 512;
#define FLT_MAX 3.402823466e+38F
#define OP_POOL_MAX 0u
#define OP_POOL_AVG 1u
layout (local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
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) writeonly buffer D {D_TYPE data_d[];};
void main() {
const uint idx = gl_GlobalInvocationID.x;
const uint workgroup = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;
#if defined(USE_SUBGROUP)
const uint idx = workgroup * gl_NumSubgroups + gl_SubgroupID;
const int lane = int(gl_SubgroupInvocationID);
const int step = int(gl_SubgroupSize);
#else
const uint idx = workgroup * BLOCK_SIZE + gl_LocalInvocationID.x;
const int lane = 0;
const int step = 1;
#endif
if (idx >= p.pelements) {
return;
}
@@ -51,7 +65,7 @@ void main() {
}
#pragma unroll
for (uint i = bl; i < el; i++) {
for (int i = bl + lane; i < el; i += step) {
const float cur = D_TYPE(data_a[nc * p.IL + i]);
if (p.op == OP_POOL_AVG) {
@@ -61,5 +75,11 @@ void main() {
}
}
#if defined(USE_SUBGROUP)
res = p.op == OP_POOL_AVG ? subgroupAdd(res) : subgroupMax(res);
if (!subgroupElect()) {
return;
}
#endif
data_d[nc * p.OL + cur_ol] = res;
}
@@ -7,6 +7,7 @@
#endif
#include "types.glsl"
#include "utils.glsl"
layout(constant_id = 0) const uint BLOCK_SIZE = 128;
layout(constant_id = 1) const uint SUBGROUP_SIZE = 32;
@@ -25,10 +26,12 @@ layout(binding = 5) readonly buffer Src5 { float C[]; };
layout(binding = 6) readonly buffer Src6 { int ids[]; };
layout(binding = 7) buffer Dst { float d[]; };
// Strides and offsets are in bytes.
layout(push_constant) uniform PushConstants {
uint nb02; uint nb03; uint nb12; uint nb13;
uint nb21; uint nb22; uint nb31;
uint nb42; uint nb43; uint nb52; uint nb53;
uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
uint s_off;
uint n_head;
uint d_head;
@@ -40,7 +43,7 @@ layout(push_constant) uniform PushConstants {
float softplus(float x) {
if (x <= 20.0) {
return log(1.0 + exp(x));
return log1p(exp(x));
} else {
return x;
}
@@ -61,12 +64,12 @@ void main() {
const uint seq_idx = gl_WorkGroupID.y;
const uint group_off = (head_idx / (n_head / n_group)) * D_STATE * 4;
const uint s0_base_idx = (uint(ids[seq_idx]) * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
const uint x_base_idx = (seq_idx * nb13 + subgroup_idx * 4) / 4;
const uint dt_base_idx = (seq_idx * nb22 + head_idx * 4) / 4;
const uint A_base_idx = (head_idx * nb31) / 4;
const uint B_base_idx = (seq_idx * nb43 + group_off) / 4;
const uint C_base_idx = (seq_idx * nb53 + group_off) / 4;
const uint s0_base_idx = (off0 + uint(ids[off6 / 4 + seq_idx]) * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
const uint x_base_idx = (off1 + seq_idx * nb13 + subgroup_idx * 4) / 4;
const uint dt_base_idx = (off2 + seq_idx * nb22 + head_idx * 4) / 4;
const uint A_base_idx = (off3 + head_idx * nb31) / 4;
const uint B_base_idx = (off4 + seq_idx * nb43 + group_off) / 4;
const uint C_base_idx = (off5 + seq_idx * nb53 + group_off) / 4;
const uint y_base_idx = seq_idx * n_tok * n_head * d_head + subgroup_idx;
const uint s_base_idx = (s_off + seq_idx * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
@@ -0,0 +1,231 @@
#version 450
#extension GL_EXT_control_flow_attributes : require
#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require
#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_arithmetic : require
#extension GL_KHR_shader_subgroup_shuffle : require
#extension GL_KHR_memory_scope_semantics : require
#extension GL_KHR_cooperative_matrix : require
#extension GL_NV_cooperative_matrix2 : require
#include "utils.glsl"
// Mamba-2 selective scan in chunks of T tokens (SSD form). A workgroup computes
// ROWS rows of one head, with the state S in an accumulator. Per chunk, with cs
// the cumulative sum of dt * A:
// M = (C * B^T) .* exp(cs_t - cs_s) for s <= t [T x T]
// y = exp(cs_t) * (S * C^T) + X_dt^T * M^T [ROWS x T]
// S = exp(cs_last) * S + X_w^T * B [ROWS x D_STATE]
// where X_dt[s] = dt_s * x_s and X_w[s] = exp(cs_last - cs_s) * X_dt[s].
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout(constant_id = 0) const uint WG_SIZE = 128;
layout(constant_id = 1) const uint D_STATE = 128;
layout(constant_id = 2) const uint T = 32; // tokens per chunk, one per subgroup lane
layout(constant_id = 3) const uint ROWS = 32; // rows per workgroup
layout(constant_id = 4) const uint PAD = 8;
// Padded row strides of the shared arrays, in f16vec4.
const uint D_STRIDE = (D_STATE + PAD) / 4;
const uint ROWS_STRIDE = (ROWS + PAD) / 4;
const uint T_STRIDE = (T + PAD) / 4;
layout(binding = 0) readonly buffer Src0 { float s0[]; };
layout(binding = 1) readonly buffer Src1 { vec4 x[]; };
layout(binding = 2) readonly buffer Src2 { float dt[]; };
layout(binding = 3) readonly buffer Src3 { float A[]; };
layout(binding = 4) readonly buffer Src4 { vec4 B[]; };
layout(binding = 5) readonly buffer Src5 { vec4 C[]; };
layout(binding = 6) readonly buffer Src6 { int ids[]; };
layout(binding = 7) writeonly buffer Dst { float d[]; };
// Strides and offsets are in bytes.
layout(push_constant) uniform PushConstants {
uint nb02; uint nb03; uint nb12; uint nb13;
uint nb21; uint nb22; uint nb31;
uint nb42; uint nb43; uint nb52; uint nb53;
uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
uint s_off;
uint n_head;
uint d_head;
uint n_group;
uint n_tok;
uint n_seq;
uint K;
};
// coopMatLoad/Store offsets and strides are in f16vec4.
shared f16vec4 sh_c[T * D_STRIDE]; // C [T x D_STATE]
shared f16vec4 sh_b[T * D_STRIDE]; // B [T x D_STATE]
shared f16vec4 sh_s[ROWS * D_STRIDE]; // S [ROWS x D_STATE]
shared f16vec4 sh_x[2][T * ROWS_STRIDE]; // X_dt [T x ROWS], read after the second barrier
shared f16vec4 sh_w[T * ROWS_STRIDE]; // X_w [T x ROWS]
shared f16vec4 sh_m[T * T_STRIDE]; // M [T x T]
shared float sh_cs[T]; // cs_t
shared float sh_ecs[T]; // exp(cs_t)
#define WG gl_ScopeWorkgroup
#define MUA gl_MatrixUseA
#define MUB gl_MatrixUseB
#define MACC gl_MatrixUseAccumulator
#define ROW gl_CooperativeMatrixLayoutRowMajor
#define COL gl_CooperativeMatrixLayoutColumnMajor
float softplus(float v) {
return v <= 20.0 ? log1p(exp(v)) : v;
}
float DecayMask(const in uint32_t r, const in uint32_t c, const in float cb) {
return c <= r ? cb * exp(sh_cs[r] - sh_cs[c]) : 0.0;
}
float ScaleCol(const in uint32_t r, const in uint32_t c, const in float v) {
return v * sh_ecs[c];
}
const uint NB = T * D_STATE / 4 / WG_SIZE; // vec4 of B (and C) per thread and chunk
const uint NX = T * ROWS / 4 / WG_SIZE; // vec4 of x per thread and chunk
// The next chunk's inputs.
vec4 next_b[NB], next_c[NB], next_x[NX];
float next_dt;
// Reads past the end clamp to the last token and row.
void load_chunk(const uint t0, const uint B_base, const uint C_base, const uint x_base, const uint dt_base, const uint row0) {
const uint tid = gl_LocalInvocationIndex;
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = min(t0 + e / (D_STATE / 4), n_tok - 1);
next_b[i] = B[B_base + t * (nb42 / 16) + e % (D_STATE / 4)];
next_c[i] = C[C_base + t * (nb52 / 16) + e % (D_STATE / 4)];
}
[[unroll]] for (uint i = 0; i < NX; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = min(t0 + e / (ROWS / 4), n_tok - 1);
const uint q = min(e % (ROWS / 4), (d_head - row0) / 4 - 1);
next_x[i] = x[x_base + t * (nb12 / 16) + q];
}
next_dt = dt[dt_base + min(t0 + gl_SubgroupInvocationID, n_tok - 1) * (nb21 / 4)];
}
void main() {
const uint tid = gl_LocalInvocationIndex;
const uint lane = gl_SubgroupInvocationID;
const uint head = gl_WorkGroupID.y;
const uint seq = gl_WorkGroupID.z;
const uint row0 = gl_WorkGroupID.x * ROWS;
const uint rows = min(ROWS, d_head - row0);
const uint group = head / (n_head / n_group);
const float a = A[(off3 + head * nb31) / 4];
const uint B_base = (off4 + seq * nb43 + group * D_STATE * 4) / 16;
const uint C_base = (off5 + seq * nb53 + group * D_STATE * 4) / 16;
const uint x_base = (off1 + seq * nb13 + (head * d_head + row0) * 4) / 16;
const uint dt_base = (off2 + seq * nb22) / 4 + head;
const uint stride_y = n_head * d_head;
const uint y_base = seq * n_tok * stride_y + head * d_head + row0;
// Rows past the end load as zero and are not stored.
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> layout_s = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
layout_s = setTensorLayoutDimensionNV(layout_s, rows, D_STATE);
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> layout_y = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
layout_y = setTensorLayoutDimensionNV(layout_y, n_tok, rows);
layout_y = setTensorLayoutStrideNV(layout_y, stride_y, 1);
tensorViewNV<2, false, 1, 0> transpose = createTensorViewNV(2, false, 1, 0);
coopmat<float, WG, ROWS, D_STATE, MACC> S;
coopMatLoadTensorNV(S, s0, (off0 + uint(ids[off6 / 4 + seq]) * nb03 + head * nb02) / 4 + row0 * D_STATE, sliceTensorLayoutNV(layout_s, 0, ROWS, 0, D_STATE));
load_chunk(0, B_base, C_base, x_base, dt_base, row0);
uint buf = 0; // sh_x buffer of the current chunk
for (uint t0 = 0; t0 < n_tok; t0 += T) {
const uint valid = min(T, n_tok - t0);
// One token per lane. Every subgroup computes the scan, so the staging
// below can shuffle dt_t and cs_t without a barrier.
const float dts = lane < valid ? softplus(next_dt) : 0.0;
const float cs = subgroupInclusiveAdd(dts * a);
const float cs_last = subgroupShuffle(cs, T - 1);
if (gl_SubgroupID == 0) {
sh_cs[lane] = cs;
sh_ecs[lane] = exp(cs);
}
// Stage B and C as fp16, row t holding token t.
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
const uint o = (e / (D_STATE / 4)) * D_STRIDE + e % (D_STATE / 4);
sh_b[o] = f16vec4(next_b[i]);
sh_c[o] = f16vec4(next_c[i]);
}
// Stage X_dt and X_w. Tokens past the end have dt_t = 0.
[[unroll]] for (uint i = 0; i < NX; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = e / (ROWS / 4), q = e % (ROWS / 4);
const float dt_t = subgroupShuffle(dts, t);
const float cs_t = subgroupShuffle(cs, t);
sh_x[buf][t * ROWS_STRIDE + q] = f16vec4(next_x[i] * dt_t);
sh_w[t * ROWS_STRIDE + q] = f16vec4(next_x[i] * (exp(cs_last - cs_t) * dt_t));
}
if (t0 + T < n_tok) {
load_chunk(t0 + T, B_base, C_base, x_base, dt_base, row0);
}
coopMatStore(coopmat<float16_t, WG, ROWS, D_STATE, MACC>(S), sh_s, 0, D_STRIDE, ROW);
barrier();
// M = (C * B^T) .* decay [T x T]
{
coopmat<float, WG, T, T, MACC> cb = coopmat<float, WG, T, T, MACC>(0.0);
coopmat<float16_t, WG, T, D_STATE, MUA> c;
coopmat<float16_t, WG, D_STATE, T, MUB> b;
coopMatLoad(c, sh_c, 0, D_STRIDE, ROW);
coopMatLoad(b, sh_b, 0, D_STRIDE, COL);
cb = coopMatMulAdd(c, b, cb);
coopMatPerElementNV(cb, cb, DecayMask);
coopMatStore(coopmat<float16_t, WG, T, T, MACC>(cb), sh_m, 0, T_STRIDE, ROW);
}
// y = exp(cs_t) * (S * C^T) [ROWS x T]
coopmat<float, WG, ROWS, T, MACC> y = coopmat<float, WG, ROWS, T, MACC>(0.0);
{
coopmat<float16_t, WG, ROWS, D_STATE, MUA> s;
coopmat<float16_t, WG, D_STATE, T, MUB> c;
coopMatLoad(s, sh_s, 0, D_STRIDE, ROW);
coopMatLoad(c, sh_c, 0, D_STRIDE, COL);
y = coopMatMulAdd(s, c, y);
}
coopMatPerElementNV(y, y, ScaleCol);
// S = exp(cs_last) * S + X_w^T * B
{
coopmat<float16_t, WG, ROWS, T, MUA> w;
coopmat<float16_t, WG, T, D_STATE, MUB> b;
coopMatLoad(w, sh_w, 0, ROWS_STRIDE, COL);
coopMatLoad(b, sh_b, 0, D_STRIDE, ROW);
S *= exp(cs_last);
S = coopMatMulAdd(w, b, S);
}
barrier();
// y += X_dt^T * M^T
{
coopmat<float16_t, WG, ROWS, T, MUA> xm;
coopmat<float16_t, WG, T, T, MUB> m;
coopMatLoad(xm, sh_x[buf], 0, ROWS_STRIDE, COL);
coopMatLoad(m, sh_m, 0, T_STRIDE, COL);
y = coopMatMulAdd(xm, m, y);
}
coopMatStoreTensorNV(y, d, y_base, sliceTensorLayoutNV(layout_y, t0, T, 0, ROWS), transpose);
buf ^= 1;
}
coopMatStoreTensorNV(S, d, (s_off + seq * nb03 + head * nb02) / 4 + row0 * D_STATE, sliceTensorLayoutNV(layout_s, 0, ROWS, 0, D_STATE));
}
@@ -0,0 +1,203 @@
#version 450
#extension GL_EXT_control_flow_attributes : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_shuffle : require
#include "utils.glsl"
// Mamba-2 selective scan over several tokens (fp32). A workgroup computes ROWS
// rows of one head, and the LPR lanes of a row group keep the state of R rows
// in registers. Chunks of T tokens are staged in shared memory, and the sums
// are reduced once per chunk.
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout(constant_id = 0) const uint WG_SIZE = 128;
layout(constant_id = 1) const uint D_STATE = 128;
layout(constant_id = 2) const uint T = 16; // tokens per chunk
layout(constant_id = 3) const uint LPR = 16; // lanes per row group
layout(constant_id = 4) const uint R = 2; // rows per thread
const uint S = D_STATE / LPR; // state values per lane and row
const uint ROWS = WG_SIZE / LPR * R; // rows per workgroup
const uint NB = T * D_STATE / 4 / WG_SIZE; // vec4 of B (and C) per thread and chunk
const uint NF = T * R / LPR; // reduced sums per lane per chunk
layout(binding = 0) readonly buffer Src0 { float s0[]; };
layout(binding = 1) readonly buffer Src1 { vec4 x[]; };
layout(binding = 2) readonly buffer Src2 { float dt[]; };
layout(binding = 3) readonly buffer Src3 { float A[]; };
layout(binding = 4) readonly buffer Src4 { vec4 B[]; };
layout(binding = 5) readonly buffer Src5 { vec4 C[]; };
layout(binding = 6) readonly buffer Src6 { int ids[]; };
layout(binding = 7) writeonly buffer Dst { float d[]; };
// Strides and offsets are in bytes.
layout(push_constant) uniform PushConstants {
uint nb02; uint nb03; uint nb12; uint nb13;
uint nb21; uint nb22; uint nb31;
uint nb42; uint nb43; uint nb52; uint nb53;
uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
uint s_off;
uint n_head;
uint d_head;
uint n_group;
uint n_tok;
uint n_seq;
uint K;
};
shared vec4 sh_b[2][T][D_STATE / 4];
shared vec4 sh_c[2][T][D_STATE / 4];
shared float sh_x[2][T][ROWS]; // x * dt
shared float sh_da[2][T]; // exp(dt * A)
float softplus(float v) {
return v <= 20.0 ? log1p(exp(v)) : v;
}
// The next chunk's inputs.
vec4 next_b[NB], next_c[NB], next_x;
float next_dt;
// Reads past the end clamp to the last token and row. store_chunk gives
// tokens past the end dt = 0 and dA = 1.
void load_chunk(const uint t0, const uint B_base, const uint C_base, const uint x_base, const uint dt_base, const uint row0) {
const uint tid = gl_LocalInvocationIndex;
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = min(t0 + e / (D_STATE / 4), n_tok - 1);
next_b[i] = B[B_base + t * (nb42 / 16) + e % (D_STATE / 4)];
next_c[i] = C[C_base + t * (nb52 / 16) + e % (D_STATE / 4)];
}
// 4 rows of x of one token, and that token's dt.
if (tid < T * ROWS / 4) {
const uint t = min(t0 + tid / (ROWS / 4), n_tok - 1);
const uint q = min(row0 / 4 + tid % (ROWS / 4), d_head / 4 - 1);
next_x = x[x_base + t * (nb12 / 16) + q];
next_dt = dt[dt_base + t * (nb21 / 4)];
}
}
void store_chunk(const uint b, const uint t0, const float a) {
const uint tid = gl_LocalInvocationIndex;
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
sh_b[b][e / (D_STATE / 4)][e % (D_STATE / 4)] = next_b[i];
sh_c[b][e / (D_STATE / 4)][e % (D_STATE / 4)] = next_c[i];
}
if (tid < T * ROWS / 4) {
const uint t = tid / (ROWS / 4), q = tid % (ROWS / 4);
const bool valid = t0 + t < n_tok;
const float dts = valid ? softplus(next_dt) : 0.0;
[[unroll]] for (uint k = 0; k < 4; ++k) {
sh_x[b][t][q * 4 + k] = next_x[k] * dts;
}
if (q == 0) {
sh_da[b][t] = valid ? exp(dts * a) : 1.0;
}
}
}
// Lane ln keeps every LPR-th vec4 of a row, so a row group reads contiguous
// vec4s of B and C.
uint state_col(const uint k, const uint ln) {
return ((k / 4) * LPR + ln) * 4 + k % 4;
}
void main() {
// Number row groups in subgroup lane order for the shuffle reduction.
const uint tid = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID;
const uint rg = tid / LPR; // row group within the workgroup
const uint ln = tid % LPR; // lane within the row group
const uint head = gl_WorkGroupID.y;
const uint seq = gl_WorkGroupID.z;
const uint row0 = gl_WorkGroupID.x * ROWS;
const uint group = head / (n_head / n_group);
const float a = A[(off3 + head * nb31) / 4];
const uint B_base = (off4 + seq * nb43 + group * D_STATE * 4) / 16;
const uint C_base = (off5 + seq * nb53 + group * D_STATE * 4) / 16;
const uint x_base = (off1 + seq * nb13 + head * d_head * 4) / 16;
const uint dt_base = (off2 + seq * nb22) / 4 + head;
const uint stride_y = n_head * d_head;
const uint y_base = seq * n_tok * stride_y + head * d_head + row0;
// state[j][k] is row row0 + rg * R + j, column state_col(k, ln).
float state[R][S];
const uint s0_base = (off0 + uint(ids[off6 / 4 + seq]) * nb03 + head * nb02) / 4;
const uint s_base = (s_off + seq * nb03 + head * nb02) / 4;
[[unroll]] for (uint j = 0; j < R; ++j) {
const uint row = row0 + rg * R + j;
[[unroll]] for (uint k = 0; k < S; ++k) {
state[j][k] = row < d_head ? s0[s0_base + row * D_STATE + state_col(k, ln)] : 0.0;
}
}
load_chunk(0, B_base, C_base, x_base, dt_base, row0);
store_chunk(0, 0, a);
barrier();
uint buf = 0;
for (uint t0 = 0; t0 < n_tok; t0 += T) {
const bool more = t0 + T < n_tok;
if (more) {
load_chunk(t0 + T, B_base, C_base, x_base, dt_base, row0);
}
float part[T * R];
[[unroll]] for (uint t = 0; t < T; ++t) {
const float dA = sh_da[buf][t];
vec4 bv[S / 4], cv[S / 4];
[[unroll]] for (uint q = 0; q < S / 4; ++q) {
bv[q] = sh_b[buf][t][q * LPR + ln];
cv[q] = sh_c[buf][t][q * LPR + ln];
}
[[unroll]] for (uint j = 0; j < R; ++j) {
const float xdt = sh_x[buf][t][rg * R + j];
float p = 0.0;
[[unroll]] for (uint k = 0; k < S; ++k) {
state[j][k] = fma(state[j][k], dA, bv[k / 4][k % 4] * xdt);
p = fma(state[j][k], cv[k / 4][k % 4], p);
}
part[t * R + j] = p;
}
}
// Butterfly reduction over the row group. Lane ln ends with the sums
// ln * NF .. ln * NF + NF - 1 of part.
[[unroll]] for (uint l = 0; (LPR >> l) > 1; ++l) {
const uint m = LPR >> (l + 1);
const uint h = (T * R) >> (l + 1);
const bool upper = (ln & m) != 0;
[[unroll]] for (uint i = 0; i < h; ++i) {
const float keep = upper ? part[i + h] : part[i];
const float send = upper ? part[i] : part[i + h];
part[i] = keep + subgroupShuffleXor(send, m);
}
}
[[unroll]] for (uint i = 0; i < NF; ++i) {
const uint f = ln * NF + i;
const uint t = f / R, row = rg * R + f % R;
if (t0 + t < n_tok && row0 + row < d_head) {
d[y_base + (t0 + t) * stride_y + row] = part[i];
}
}
if (more) {
store_chunk(buf ^ 1, t0 + T, a);
}
barrier();
buf ^= 1;
}
[[unroll]] for (uint j = 0; j < R; ++j) {
const uint row = row0 + rg * R + j;
if (row < d_head) {
[[unroll]] for (uint k = 0; k < S; ++k) {
d[s_base + row * D_STATE + state_col(k, ln)] = state[j][k];
}
}
}
}
@@ -1146,6 +1146,7 @@ void process_shaders() {
string_to_spv("snake_bf16", "snake.comp", {{"DATA_A_BF16", "1"}, {"DATA_D_BF16", "1"}, {"A_TYPE", "uint16_t"}, {"D_TYPE", "uint16_t"}});
string_to_spv("pool1d_f32", "pool1d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("pool1d_subgroup_f32", "pool1d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"USE_SUBGROUP", "1"}}));
string_to_spv("pool2d_f32", "pool2d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
string_to_spv("pool2d_subgroup_f32", "pool2d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"USE_SUBGROUP", "1"}}));
@@ -1267,6 +1268,10 @@ void process_shaders() {
string_to_spv("ssm_scan_f32", "ssm_scan.comp", {{"A_TYPE", "float"}});
string_to_spv("ssm_scan_subgroup_f32", "ssm_scan.comp", {{"A_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}});
string_to_spv("ssm_scan_prefill_f32", "ssm_scan_prefill.comp", {});
#if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
string_to_spv("ssm_scan_f32", "ssm_scan_cm2.comp", {}, true, false, true);
#endif
string_to_spv("ssm_conv_f32", "ssm_conv.comp", {{"A_TYPE", "float"}});
+3
View File
@@ -3984,6 +3984,9 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.SSM_BETA,
MODEL_TENSOR.SSM_ALPHA,
MODEL_TENSOR.SSM_OUT,
MODEL_TENSOR.FFN_GATE,
MODEL_TENSOR.FFN_UP,
MODEL_TENSOR.FFN_DOWN,
MODEL_TENSOR.FFN_GATE_INP,
MODEL_TENSOR.FFN_GATE_INP_SHEXP,
MODEL_TENSOR.FFN_UP_SHEXP,
@@ -41,6 +41,7 @@ byteswap_tensors: dict[gguf.GGMLQuantizationType, tuple[tuple[int, type[np.unsig
gguf.GGMLQuantizationType.MXFP4: (), # noop
gguf.GGMLQuantizationType.NVFP4: (), # noop
gguf.GGMLQuantizationType.F8_E4M3: (), # noop
gguf.GGMLQuantizationType.I8: (), # noop
}
@@ -62,6 +63,10 @@ def convert_byteorder(reader: gguf.GGUFReader, args: argparse.Namespace) -> None
gguf.GGMLQuantizationType.F32,
gguf.GGMLQuantizationType.F16,
gguf.GGMLQuantizationType.BF16,
gguf.GGMLQuantizationType.F64,
gguf.GGMLQuantizationType.I16,
gguf.GGMLQuantizationType.I32,
gguf.GGMLQuantizationType.I64,
):
raise ValueError(f"Cannot handle type {tensor.tensor_type.name} for tensor {repr(tensor.name)}")
logger.info(f"* Preparing to convert from {file_endian} to {order}")
+10 -2
View File
@@ -9,7 +9,7 @@ from pathlib import Path
if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from gguf import GGUFReader # noqa: E402
from gguf import GGUFReader, GGUFValueType # noqa: E402
logger = logging.getLogger("gguf-set-metadata")
@@ -54,7 +54,15 @@ def set_metadata(reader: GGUFReader, args: argparse.Namespace) -> None:
logger.error(f'! This tool only supports changing simple values, {repr(args.key)} has unsupported type {field.types}')
sys.exit(1)
current_value = field.parts[field.data[0]][0]
new_value = handler(args.value)
if field.types[0] == GGUFValueType.BOOL:
# np.bool_ of any non-empty string is True, so "false" must be parsed
value = args.value.lower()
if value not in ('true', 'false', '1', '0', ''):
logger.error(f'! Invalid value {repr(args.value)} for bool field {repr(args.key)}, use true/false or 1/0')
sys.exit(1)
new_value = handler(value in ('true', '1'))
else:
new_value = handler(args.value)
logger.info(f'* Preparing to change field {repr(args.key)} from {current_value} to {new_value}')
if current_value == new_value:
logger.info(f'- Key {repr(args.key)} already set to requested value {current_value}')
+220
View File
@@ -0,0 +1,220 @@
{#- Qwen4 Jinja chat template for compatibility only. Deliberate omissions:
- tool-result ordering is limited to text-only runs with explicit tool_call_id.
Media runs keep input order: HF collects media before rendering this template.
Missing/null tool_call_id never falls back to id: newer HF versions strip null
fields before rendering, so these cases cannot be distinguished here.
For full Python ordering semantics, reorder messages before media collection.
- tool_calls[].function.arguments is only read as a dict; other types cause exceptions.
- no anti-injection: the encoder tokenizes data with allow_special=false, so message
text can never become a control token. A flat string cannot express that, and
re-tokenizing it does not reproduce the encoder's token ids -- use the Qwen4
tokenizer's apply_chat_template(tokenize=True) for exact ids.
- the generation blocks (return_assistant_tokens_mask) cover a whole assistant
body; the encoder additionally masks out media placeholders inside it.
-#}
{%- macro render_content(content) -%}
{%- if content is string -%}
{{- content -}}
{%- elif content is iterable and content is not mapping -%}
{%- for item in content -%}
{%- if item is string -%}
{{- item -}}
{%- elif item.get('type') == 'text' -%}
{{- item.get('text', '') | default('', true) -}}
{%- elif item.get('type') in ('image', 'image_url') -%}
{{- '<|vision_start|><|image_pad|><|vision_end|>' -}}
{%- elif item.get('type') in ('video', 'video_url') -%}
{{- '<|vision_start|><|video_pad|><|vision_end|>' -}}
{%- elif item.get('type') in ('audio', 'audio_url') -%}
{{- '<|audio_start|><|audio_pad|><|audio_end|>' -}}
{%- else -%}
{{- raise_exception('Unexpected content part type ' ~ item.get('type') ~ '. Supported types are text, image, image_url, video, video_url, audio and audio_url.') -}}
{%- endif -%}
{%- endfor -%}
{%- elif content is not none -%}
{{- content | tojson -}}
{%- endif -%}
{%- endmacro -%}
{%- macro render_reasoning(reasoning) -%}
{%- if reasoning is string -%}
{{- reasoning -}}
{%- elif reasoning is iterable and reasoning is not mapping -%}
{%- for item in reasoning -%}
{%- if item is string -%}
{{- item -}}
{%- elif item.get('type') in (none, 'text') -%}
{{- item.get('text', '') | default('', true) -}}
{%- else -%}
{{- item | tojson -}}
{%- endif -%}
{%- endfor -%}
{%- elif reasoning is not none -%}
{{- reasoning | tojson -}}
{%- endif -%}
{%- endmacro -%}
{%- macro render_tools(tools) -%}
{{- '# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>\n' -}}
{%- for tool in tools -%}
{%- if tool is not mapping -%}
{{- raise_exception('Unexpected tool spec ' ~ tool ~ '. Expected a function schema dict.') -}}
{%- elif tool.get('type') == 'function' and 'function' in tool -%}
{{- tool | tojson -}}
{%- elif 'function' in tool -%}
{{- ({'type': 'function', 'function': tool['function']}) | tojson -}}
{%- else -%}
{{- ({'type': 'function', 'function': tool}) | tojson -}}
{%- endif -%}
{{- '\n' -}}
{%- endfor -%}
{{- '</tools>\n\nIf you choose to call a function, use exactly this format:\n' -}}
{{- '<tool_call>\n<function={function-name}>\n<parameter={parameter-name}>\n{parameter-value}\n</parameter>\n</function>\n</tool_call>' -}}
{%- endmacro -%}
{%- macro render_tool_calls(tool_calls) -%}
{%- for tool_call in tool_calls -%}
{%- if tool_call.function is mapping -%}
{%- set name = tool_call.function.get('name', '') -%}
{%- set arguments = tool_call.function.get('arguments') -%}
{%- else -%}
{%- set name = tool_call.get('name', '') -%}
{%- set arguments = tool_call.get('arguments') -%}
{%- endif -%}
{{- '<tool_call>\n<function=' ~ name ~ '>\n' -}}
{%- if arguments is mapping -%}
{%- for arg_name, arg_value in arguments | items -%}
{{- '<parameter=' ~ (arg_name if arg_name is string else arg_name | tojson) ~ '>\n' -}}
{{- arg_value if arg_value is string else arg_value | tojson -}}
{{- '\n</parameter>\n' -}}
{%- endfor -%}
{%- elif arguments is not none and (arguments is not string or (arguments | trim) != '') -%}
{{- raise_exception('Unexpected argument types. Expected dict.') -}}
{%- endif -%}
{{- '</function>\n</tool_call>' -}}
{%- endfor -%}
{%- endmacro -%}
{%- set enable_thinking = enable_thinking | default(none) -%}
{%- if enable_thinking is not none and enable_thinking is not boolean -%}
{{- raise_exception('Unexpected enable_thinking ' ~ enable_thinking ~ '. Expected true, false or none.') -}}
{%- endif -%}
{%- set reasoning_effort = reasoning_effort | default(none) -%}
{%- if reasoning_effort is not none and reasoning_effort not in ('xhigh', 'high', 'low', 'off') -%}
{{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported efforts are xhigh, high, low and off.') -}}
{%- endif -%}
{%- if enable_thinking is none -%}
{%- set effort = reasoning_effort if reasoning_effort is not none else 'high' -%}
{%- elif enable_thinking -%}
{%- if reasoning_effort == 'off' -%}
{{- raise_exception('Conflicting thinking settings: enable_thinking=true with reasoning_effort=off.') -}}
{%- endif -%}
{%- set effort = reasoning_effort if reasoning_effort is not none else 'high' -%}
{%- else -%}
{%- if reasoning_effort is not none and reasoning_effort != 'off' -%}
{{- raise_exception('Conflicting thinking settings: enable_thinking=false with reasoning_effort=' ~ reasoning_effort ~ '.') -}}
{%- endif -%}
{%- set effort = 'off' -%}
{%- endif -%}
{%- set preserve_thinking = preserve_thinking | default(true) -%}
{%- if preserve_thinking is not none and preserve_thinking is not boolean -%}
{{- raise_exception('Unexpected preserve_thinking ' ~ preserve_thinking ~ '. Expected true, false or none.') -}}
{%- endif -%}
{%- set preserve_thinking = true if preserve_thinking is none else preserve_thinking -%}
{{- '<|im_start|>system\n' + 'Reasoning effort is set to ' + effort + '.' -}}
{%- if tools -%}
{{- '\n\n' -}}
{{- render_tools(tools) -}}
{%- endif -%}
{{- '<|im_end|>\n' -}}
{#- Sort text-only tool-result runs only when every explicit tool_call_id resolves. -#}
{%- set order = namespace(messages=[], call_ids=[], pending=[], unresolved=false) -%}
{%- for message in messages + [none] -%}
{%- if message is none or message.get('role') != 'tool' -%}
{%- if not order.unresolved -%}
{%- set order.pending = order.pending | sort(attribute='position') -%}
{%- endif -%}
{%- for item in order.pending -%}
{%- set order.messages = order.messages + [item.message] -%}
{%- endfor -%}
{%- set order.pending = [] -%}
{%- set order.unresolved = false -%}
{%- if message is not none -%}
{%- if message.get('role') == 'assistant' -%}
{%- set order.call_ids = [] -%}
{%- for call in message.get('tool_calls') or [] -%}
{%- if call is mapping and call.get('id') is not none -%}
{%- set order.call_ids = order.call_ids + [call.id | string] -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- set order.messages = order.messages + [message] -%}
{%- endif -%}
{%- else -%}
{#- Do not reorder media independently of the processor's already-collected inputs. -#}
{%- set content = message.get('content') -%}
{%- if content is iterable and content is not string and content is not mapping -%}
{%- for part in content -%}
{%- if part is not string and (part is not mapping or part.get('type') != 'text') -%}
{%- set order.unresolved = true -%}
{%- endif -%}
{%- endfor -%}
{%- elif content is not none and content is not string -%}
{%- set order.unresolved = true -%}
{%- endif -%}
{%- set cid = message.get('tool_call_id') -%}
{%- set match = namespace(position=none) -%}
{%- for call_id in order.call_ids -%}
{%- if cid is not none and call_id == (cid | string) and match.position is none -%}
{%- set match.position = loop.index0 -%}
{%- endif -%}
{%- endfor -%}
{%- if match.position is none -%}
{%- set order.unresolved = true -%}
{%- endif -%}
{%- set order.pending = order.pending + [{'position': match.position, 'message': message}] -%}
{%- endif -%}
{%- endfor -%}
{%- set messages = order.messages -%}
{#- with preserve_thinking=false, reasoning survives only on and after the last user turn -#}
{%- set ns = namespace(last_user=-1) -%}
{%- if not preserve_thinking -%}
{%- for message in messages -%}
{%- if message.get('role') == 'user' -%}
{%- set ns.last_user = loop.index0 -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- for message in messages -%}
{%- set role = 'system' if message.get('role') == 'developer' else message.get('role') -%}
{%- if role in ('system', 'user') -%}
{{- '<|im_start|>' + role + '\n' + render_content(message.get('content')) + '<|im_end|>\n' -}}
{%- elif role == 'assistant' -%}
{%- if not preserve_thinking and loop.index0 < ns.last_user -%}
{%- set reasoning = '' -%}
{%- elif 'reasoning_content' in message -%}
{%- set reasoning = render_reasoning(message['reasoning_content']) | trim -%}
{%- elif 'reasoning' in message -%}
{%- set reasoning = render_reasoning(message['reasoning']) | trim -%}
{%- else -%}
{%- set reasoning = '' -%}
{%- endif -%}
{%- set content = render_content(message.get('content')) | trim -%}
{{- '<|im_start|>assistant\n' -}}
{%- generation -%}
{{- '<think>' + reasoning + '</think>' + content -}}
{%- if message.get('tool_calls') -%}
{{- render_tool_calls(message['tool_calls']) -}}
{%- endif -%}
{{- '<|im_end|>' -}}
{%- endgeneration -%}
{{- '\n' -}}
{%- elif role == 'tool' -%}
{{- '<|im_start|>tool\n' + render_content(message.get('content')) + '\n<|im_end|>\n' -}}
{%- else -%}
{{- raise_exception('Unexpected message role ' ~ message.get('role') ~ '. Supported roles are system, developer, user, assistant and tool.') -}}
{%- endif -%}
{%- endfor -%}
{%- if add_generation_prompt -%}
{{- '<|im_start|>assistant\n' -}}
{{- '<think>' -}}
{%- if effort == 'off' -%}
{{- '</think>' -}}
{%- endif -%}
{%- endif -%}
+5
View File
@@ -2582,6 +2582,11 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
tokenizer_pre == "qwen35") {
pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35;
clean_spaces = false;
} else if (
tokenizer_pre == "qwen4") {
pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35;
ignore_merges = true;
clean_spaces = false;
} else if (
tokenizer_pre == "stablelm2") {
pre_type = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
+5 -5
View File
@@ -174,6 +174,11 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(cur, "attn_gated", il);
// now apply output projection
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_o_proj", il);
}
@@ -184,11 +189,6 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
LLM_NORM_RMS, il);
cb(cur, "attn_post_norm", il);
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
cb(ffn_inp, "ffn_inp", il);
+5 -5
View File
@@ -251,15 +251,15 @@ llama_model_laguna::graph::graph(const llm_graph_params & params) : llm_graph_co
}
cb(cur, "attn_gated", il);
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_o_proj", il);
}
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
cb(ffn_inp, "ffn_inp", il);
+19 -2
View File
@@ -166,6 +166,7 @@ void llama_model_qwen4exp::load_arch_hparams(llama_model_loader & ml) {
}
switch (hparams.n_layer()) {
case 40: type = LLM_TYPE_35B_A3B; break;
case 48: type = LLM_TYPE_A3B; break;
default: type = LLM_TYPE_UNKNOWN;
}
@@ -225,7 +226,7 @@ void llama_model_qwen4exp::load_arch_tensors(llama_model_loader & ml) {
auto load_block = [&](int il, int flags) {
auto & layer = layers[il];
const int64_t n_ff_exp = hparams.n_ff_exp() ? hparams.n_ff_exp() : n_ff / n_expert_used;
const int64_t n_ff_exp = hparams.n_ff_exp() ? hparams.n_ff_exp() : n_ff / std::max<int64_t>(n_expert_used, 1);
const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
const int64_t head_k_dim = hparams.ssm_d_state;
@@ -297,6 +298,13 @@ void llama_model_qwen4exp::load_arch_tensors(llama_model_loader & ml) {
layer.ple_conv1d = create_tensor(tn(LLM_TENSOR_PLE_CONV1D, "weight", il), { hparams.ple_conv_kernel, 1, hc_dim }, flags | TENSOR_ALLOW_RESHAPE);
}
if (n_expert == 0) {
layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", il), { n_embd, hparams.n_ff(il) }, flags);
layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", il), { n_embd, hparams.n_ff(il) }, flags);
layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", il), { hparams.n_ff(il), n_embd }, flags);
return;
}
layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", il), { n_embd, n_expert }, flags);
layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", il), { n_ff_exp, n_embd, n_expert }, flags);
create_tensor_gate_up_exps(layer, il, n_embd, n_ff_exp, n_expert, flags);
@@ -1217,7 +1225,16 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_attn_linear(
}
ggml_tensor * llama_model_qwen4exp::graph::build_layer_ffn(ggml_tensor * cur, const int il) {
GGML_ASSERT(model.layers[il].ffn_gate_inp != nullptr);
if (model.layers[il].ffn_gate_inp == nullptr) {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
return cur;
}
ggml_tensor * moe_out =
build_moe_ffn(cur,
+2 -2
View File
@@ -1,8 +1,8 @@
# test-fusion baseline for device MTL
# arch ,moe ,mode ,label , count
afmoe ,1 ,any ,MUL+ADD , 2
afmoe ,1 ,any ,RMS_NORM+MUL , 10
afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3
afmoe ,1 ,any ,RMS_NORM+MUL , 9
afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 4
afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
apertus ,0 ,any ,RMS_NORM+MUL , 9
arcee ,0 ,any ,RMS_NORM+MUL , 5
1 # test-fusion baseline for device MTL
2 # arch ,moe ,mode ,label , count
3 afmoe ,1 ,any ,MUL+ADD , 2
4 afmoe ,1 ,any ,RMS_NORM+MUL , 10 afmoe ,1 ,any ,RMS_NORM+MUL , 9
5 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 4
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
+25
View File
@@ -1167,6 +1167,30 @@ static void test_buft_get_alloc_size_n_does_not_allocate() {
GGML_ASSERT(x[1]->data == nullptr);
}
// Parent larger than max_size splits off a view-only tail with size 0.
// That tail is not in the alloc plan, so views must be initialized after the split.
static void test_view_init_after_max_size_split() {
const size_t max_size = 16;
dummy_backend backend = dummy_backend_init(max_size);
auto [ctx, graph, ctx_ptr] = make_context();
(void) graph;
ggml_tensor * parent = make_input_with_size(ctx, 24); // 6 x f32, > max_size
ggml_tensor * view0 = ggml_view_1d(ctx, parent, 2, 0);
ggml_tensor * view1 = ggml_view_1d(ctx, parent, 2, 2 * sizeof(float));
assign_names(ctx);
ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors_from_buft(ctx, &backend.buffer_type));
GGML_ASSERT(buf);
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t; t = ggml_get_next_tensor(ctx, t)) {
GGML_ASSERT(t->buffer != nullptr);
GGML_ASSERT(t->data != nullptr);
}
GGML_ASSERT(view0->view_src == parent);
GGML_ASSERT(view1->view_src == parent);
}
static void run(const char * name, void (*f)()) {
printf("%s ", name);
fflush(stdout);
@@ -1208,5 +1232,6 @@ int main() {
run("test_buft_get_alloc_size_n_custom_override", test_buft_get_alloc_size_n_custom_override);
run("test_buft_get_alloc_size_n_custom_override_ctx_size", test_buft_get_alloc_size_n_custom_override_ctx_size);
run("test_buft_get_alloc_size_n_does_not_allocate", test_buft_get_alloc_size_n_does_not_allocate);
run("test_view_init_after_max_size_split", test_view_init_after_max_size_split);
return 0;
}
+93 -22
View File
@@ -5682,6 +5682,8 @@ struct test_ssm_conv_concat_fusion : public test_case {
};
// GGML_OP_SSM_SCAN
// xbc_graph: x, B and C are views of one tensor with rows [xbc_off | x | B | C | pad], as in the Mamba-2 graph.
// off: s, dt, A and ids start off elements into their tensors.
struct test_ssm_scan : public test_case {
const ggml_type type;
@@ -5694,9 +5696,15 @@ struct test_ssm_scan : public test_case {
const bool xbc_overlap;
const int64_t K;
const bool weak_decay;
const bool xbc_graph;
const int64_t off;
const int64_t xbc_off;
const int64_t pad;
const bool seq_major;
std::string vars() override {
return VARS_TO_STR10(type, d_state, head_dim, n_head, n_group, n_seq_tokens, n_seqs, xbc_overlap, K, weak_decay);
return VARS_TO_STR15(type, d_state, head_dim, n_head, n_group, n_seq_tokens, n_seqs, xbc_overlap, K, weak_decay,
xbc_graph, off, xbc_off, pad, seq_major);
}
test_ssm_scan(ggml_type type = GGML_TYPE_F32,
@@ -5708,23 +5716,41 @@ struct test_ssm_scan : public test_case {
int64_t n_seqs = 32,
bool xbc_overlap = false,
int64_t K = 1,
bool weak_decay = false)
: type(type), d_state(d_state), head_dim(head_dim), n_head(n_head), n_group(n_group), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), xbc_overlap(xbc_overlap), K(K), weak_decay(weak_decay) {}
bool weak_decay = false,
bool xbc_graph = false,
int64_t off = 0,
int64_t xbc_off = 0,
int64_t pad = 0,
bool seq_major = false)
: type(type), d_state(d_state), head_dim(head_dim), n_head(n_head), n_group(n_group), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), xbc_overlap(xbc_overlap), K(K), weak_decay(weak_decay),
xbc_graph(xbc_graph), off(off), xbc_off(xbc_off), pad(pad), seq_major(seq_major) {}
double max_nmse_err() override {
// SSD path (head_dim > 1) uses FP16 intermediates (M matrix, X_dt); Mamba-1 is pure FP32.
return (head_dim > 1) ? 2e-7 : 1e-7;
}
int64_t n_slots() const {
return xbc_graph ? n_seqs + 2 : n_seqs;
}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * s = ggml_new_tensor_4d(ctx, type, d_state, head_dim, n_head, n_seqs);
ggml_tensor * dt = ggml_new_tensor_3d(ctx, type, n_head, n_seq_tokens, n_seqs);
ggml_tensor * A = ggml_new_tensor_2d(ctx, type, (head_dim > 1) ? 1 : d_state, n_head);
const size_t f = ggml_type_size(type);
ggml_tensor * x;
ggml_tensor * B;
ggml_tensor * C;
if (xbc_overlap) {
if (xbc_graph) {
const int64_t d_inner = head_dim * n_head;
const int64_t row = xbc_off + d_inner + 2 * n_group * d_state + pad;
ggml_tensor * xbc = seq_major ? ggml_new_tensor_3d(ctx, type, row, n_seqs, n_seq_tokens)
: ggml_new_tensor_3d(ctx, type, row, n_seq_tokens, n_seqs);
const size_t nb_tok = seq_major ? xbc->nb[2] : xbc->nb[1];
const size_t nb_seq = seq_major ? xbc->nb[1] : xbc->nb[2];
x = ggml_view_4d(ctx, xbc, head_dim, n_head, n_seq_tokens, n_seqs, head_dim * f, nb_tok, nb_seq, xbc_off * f);
B = ggml_view_4d(ctx, xbc, d_state, n_group, n_seq_tokens, n_seqs, d_state * f, nb_tok, nb_seq, (xbc_off + d_inner) * f);
C = ggml_view_4d(ctx, xbc, d_state, n_group, n_seq_tokens, n_seqs, d_state * f, nb_tok, nb_seq, (xbc_off + d_inner + n_group * d_state) * f);
} else if (xbc_overlap) {
ggml_tensor * xbc = ggml_new_tensor_4d(ctx, type, d_state, n_head, n_seq_tokens, 2 * n_seqs);
x = ggml_view_4d(ctx, xbc, head_dim, n_head, n_seq_tokens, n_seqs,
xbc->nb[1], xbc->nb[2], xbc->nb[3], xbc->nb[3]);
@@ -5737,7 +5763,19 @@ struct test_ssm_scan : public test_case {
B = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
C = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
}
ggml_tensor * ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs);
const int64_t A_ne0 = (head_dim > 1) ? 1 : d_state;
ggml_tensor * s_all = ggml_new_tensor_1d(ctx, type, off + d_state * head_dim * n_head * n_slots());
ggml_tensor * dt_all = ggml_new_tensor_1d(ctx, type, off + n_head * n_seq_tokens * n_seqs);
ggml_tensor * A_all = ggml_new_tensor_1d(ctx, type, off + A_ne0 * n_head);
ggml_tensor * ids_all = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, off + n_seqs);
ggml_set_name(A_all, "A");
ggml_tensor * s = ggml_view_4d(ctx, s_all, d_state, head_dim, n_head, n_slots(),
d_state * f, d_state * head_dim * f, d_state * head_dim * n_head * f, off * f);
ggml_tensor * dt = ggml_view_3d(ctx, dt_all, n_head, n_seq_tokens, n_seqs, n_head * f, n_head * n_seq_tokens * f, off * f);
ggml_tensor * A = ggml_view_2d(ctx, A_all, A_ne0, n_head, A_ne0 * f, off * f);
ggml_tensor * ids = ggml_view_1d(ctx, ids_all, n_seqs, off * sizeof(int32_t));
ggml_tensor * out = ggml_ssm_scan(ctx, s, x, dt, A, B, C, ids, K);
return out;
}
@@ -5747,21 +5785,23 @@ struct test_ssm_scan : public test_case {
std::random_device rd;
std::default_random_engine rng(rd());
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
if (t->type == GGML_TYPE_I32) {
if (ggml_is_view_op(t->op)) { continue; }
// ids: permutation of [0..n_seqs)
for (int64_t r = 0; r < ggml_nrows(t); r++) {
std::vector<int32_t> data(t->ne[0]);
for (int i = 0; i < t->ne[0]; i++) {
data[i] = i;
}
std::shuffle(data.begin(), data.end(), rng);
ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(int32_t));
}
} else if (ggml_is_view_op(t->op)) {
if (ggml_is_view_op(t->op)) {
continue;
} else if (t->ne[1] == n_head && t->ne[2] == 1) {
// A {1 or d_state, n_head}: negative decay (2-D tensor, ne[2]==1 distinguishes from 3-D/4-D tensors)
}
if (t->type == GGML_TYPE_I32) {
// ids: distinct random state slots
std::vector<int32_t> slots(n_slots());
for (size_t i = 0; i < slots.size(); i++) {
slots[i] = (int32_t) i;
}
std::shuffle(slots.begin(), slots.end(), rng);
std::vector<int32_t> data(ggml_nelements(t), 0);
for (int64_t i = 0; i < n_seqs; i++) {
data[off + i] = slots[i];
}
ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
} else if (strcmp(t->name, "A") == 0) {
// negative decay
init_tensor_uniform(t, weak_decay ? -0.02f : -1.0f, weak_decay ? -0.005f : -0.5f);
} else {
init_tensor_uniform(t);
@@ -12933,6 +12973,13 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_conv_2d_dw({17, 34, 9, 1}, {3, 3, 1, 9}, GGML_TYPE_F16, 1, 0, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({17, 34, 9, 1}, {3, 3, 1, 9}, GGML_TYPE_F16, 1, 0, 1, true));
// 5x5 s=1 p=2 d=1 (dedicated HTP kernel)
test_cases.emplace_back(new test_conv_2d_dw({32, 24, 16, 1}, {5, 5, 1, 16}, GGML_TYPE_F16, 1, 2, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({33, 17, 9, 2}, {5, 5, 1, 9}, GGML_TYPE_F16, 1, 2, 1, false));
// batched, fewer channels than HVX threads
test_cases.emplace_back(new test_conv_2d_dw({16, 16, 2, 4}, {5, 5, 1, 2}, GGML_TYPE_F16, 1, 2, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({16, 16, 1, 4}, {5, 5, 1, 1}, GGML_TYPE_F16, 1, 2, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({104, 80, 32, 1}, {5, 5, 1, 32}, GGML_TYPE_F16, 1, 2, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({32, 8, 64, 1}, {3, 3, 1, 64}, GGML_TYPE_F16, 2, 1, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({32, 8, 64, 1}, {3, 3, 1, 64}, GGML_TYPE_F16, 2, 1, 1, true));
@@ -13648,6 +13695,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_ssm_scan_rollback(GGML_TYPE_F32, 96, 64, 16, 8, 8, 2, /*K=*/3)); // d_state=96 rollback snapshots match prefix states
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 32, 4)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 32, 4)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 8, 2)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 31, 2)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 9, 2)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 128, 4, 4, 16, 2, true)); // x/B/C overlap
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 256, 1)); // Nemotron-9B SSD path
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 512, 1)); // Nemotron-9B SSD multi-chunk (2 aligned chunks)
@@ -13659,6 +13709,25 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 65, 2)); // SSD one chunk + 1-token sequential tail
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 128, 2)); // SSD multi-chunk, no tail (exercises the chunk-to-chunk state handoff)
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 128, 2, false, /*K=*/1, /*weak_decay=*/true)); // SSD multi-chunk, carried state not numerically negligible
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 2048, 1)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 300, 2)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 16, 16, 2, 64, 2)); // head_dim 16
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 48, 16, 2, 64, 2)); // head_dim 48
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 16, 8, 16, 2)); // Nemotron-3-Puzzle
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 48, 16, 8, 16, 2)); // head_dim 48
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 48, 16, 8, 64, 2)); // head_dim 48
// Mamba-2 with the inputs laid out like the model graph, then with unaligned offsets and strides.
for (int64_t n_tok : {4, 16, 100}) {
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, /*xbc_graph=*/true));
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, /*off=*/1)); // s, dt, A and ids
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, 0, /*xbc_off=*/1)); // x, B and C
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, 0, 0, /*pad=*/1)); // token stride
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 3, false, 1, false, true, 0, 0, 0, /*seq_major=*/true));
}
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 40, 2, false, 1, false, true, 1)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 8, 1, 40, 2, false, 1, false, true, 1, 4, 4)); // Nemotron-9B
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 16, 8, 40, 2, false, 1, false, true, 1)); // Nemotron-3-Puzzle
// ssm_scan + cache cpy fusion
test_cases.emplace_back(new test_ssm_scan_cache_fusion(GGML_TYPE_F32, 128, 64, 16, 2, 4, 1, 4));
@@ -16434,6 +16503,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
test_cases.emplace_back(new test_conv_2d_dw({112, 112, 32, 1}, {3, 3, 1, 32}, GGML_TYPE_F32, 1, 1, 1, true));
test_cases.emplace_back(new test_conv_2d_dw({56, 56, 128, 1}, {5, 5, 1, 128}, GGML_TYPE_F32, 2, 2, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({56, 56, 128, 1}, {5, 5, 1, 128}, GGML_TYPE_F32, 2, 2, 1, true));
test_cases.emplace_back(new test_conv_2d_dw({56, 56, 128, 1}, {5, 5, 1, 128}, GGML_TYPE_F16, 1, 2, 1, false));
test_cases.emplace_back(new test_conv_2d_dw({112, 112, 64, 1}, {5, 5, 1, 64}, GGML_TYPE_F16, 1, 2, 1, false));
for (ggml_type kernel_type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
test_cases.emplace_back(new test_conv_transpose_2d({256, 256, 256, 1}, {3, 3, 16, 256}, 1, kernel_type));
+145
View File
@@ -2903,6 +2903,77 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
}
}
{
// Qwen4: Qwen3-Coder tool calls, compact "<think>...</think>" with no separators
auto tst = peg_tester("models/templates/Qwen4-35B-A3B.jinja", detailed_debug);
tst.specials(qwen3_coder_specials);
tst.test("I'm\nthinking</think>Hello, world!\nWhat's up?")
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
.enable_thinking(true)
.expect(message_assist_thoughts)
.run();
tst.test("I'm\nthinking</think>Hello, world!\nWhat's up?")
.enable_thinking(true)
.reasoning_format(COMMON_REASONING_FORMAT_NONE)
.expect_content("<think>I'm\nthinking</think>Hello, world!\nWhat's up?")
.run();
tst.test("Hello, world!\nWhat's up?")
.enable_thinking(false)
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
.expect(message_assist)
.run();
tst.test(
"I'm\nthinking</think>"
"<tool_call>\n"
"<function=special_function>\n"
"<parameter=arg1>\n1\n</parameter>\n"
"</function>\n"
"</tool_call>")
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
.enable_thinking(true)
.tools({ special_function_tool })
.expect(message_assist_call_thoughts)
.run();
tst.test(
"<tool_call>\n"
"<function=special_function>\n"
"<parameter=arg1>\n1\n</parameter>\n"
"</function>\n"
"</tool_call>"
"<tool_call>\n"
"<function=special_function_with_opt>\n"
"<parameter=arg1>\n1\n</parameter>\n"
"<parameter=arg2>\n2\n</parameter>\n"
"</function>\n"
"</tool_call>")
.enable_thinking(false)
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
.parallel_tool_calls(true)
.tools({
special_function_tool, special_function_tool_with_optional_param
})
.expect_tool_calls({
{ "special_function", R"({"arg1": 1})", {} },
{ "special_function_with_opt", R"({"arg1": 1, "arg2": 2})", {} },
})
.run();
tst.test(
"I need to output the invoice details in JSON</think>"
R"({"amount": 123.45, "date": "2025-12-03"})")
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
.enable_thinking(true)
.json_schema(invoice_schema)
.expect_reasoning("I need to output the invoice details in JSON")
.expect_content(R"({"amount": 123.45, "date": "2025-12-03"})")
.run();
}
{
// Ministral-3-14B-Reasoning-2512
auto tst = peg_tester("models/templates/mistralai-Ministral-3-14B-Reasoning-2512.jinja", detailed_debug);
@@ -8639,6 +8710,13 @@ static void test_template_generation_prompt() {
assert_ends_with(params.prompt.str(), expected_generation_prompt);
};
{
auto tmpls = read_templates("models/templates/Qwen4-35B-A3B.jinja");
check(tmpls, basic(), "<|im_start|>assistant\n<think>");
check(tmpls, continuation_content(), "<|im_start|>assistant\n<think>I'm thinking</think>Hello, ");
check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n<think>I'm");
}
{
auto tmpls = read_templates("models/templates/Qwen3.5-4B.jinja");
check(tmpls, basic(), "<|im_start|>assistant\n<think>\n");
@@ -9597,6 +9675,71 @@ static void test_chat_session() {
}
}
// Qwen4 writes "<think>" + reasoning + "</think>" + content with no separators
static void test_qwen4_chat_session() {
LOG_DBG("%s\n", __func__);
auto tmpls = read_templates("models/templates/Qwen4-35B-A3B.jinja");
common_chat_templates_inputs inputs;
inputs.messages = { message_user };
inputs.tools = { special_function_tool };
inputs.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
{
common_chat_session session(tmpls.get(), nullptr, inputs);
assert_equals(std::string("<|im_start|>assistant\n<think>"), session.generation_prompt());
// the reasoning budget closes with the bare tag, the template never writes a newline before it
assert_equals(json(std::vector<std::string>{ "</think>", "<tool_call>" }).dump(), json(session.thinking_end_tags()).dump());
const std::string output =
"I'm\nthinking</think>"
"Let me check."
"<tool_call>\n"
"<function=special_function>\n"
"<parameter=arg1>\n1\n</parameter>\n"
"</function>\n"
"</tool_call>";
for (size_t i = 0; i < output.size(); i += 3) {
session.feed(common_chat_input(output.substr(i, 3)));
}
assert_msg_equals(simple_assist_msg("Let me check.", "I'm\nthinking", "special_function", "{\"arg1\":1}"), session.finish());
}
// thinking off renders an empty think block, the output is content only
{
common_chat_templates_inputs off = inputs;
off.enable_thinking = false;
common_chat_session session(tmpls.get(), nullptr, off);
assert_equals(std::string("<|im_start|>assistant\n<think></think>"), session.generation_prompt());
session.feed(common_chat_input("Hello, world!"));
assert_msg_equals(simple_assist_msg("Hello, world!"), session.finish());
}
// a continued message is written back the way the template renders it
{
common_chat_templates_inputs cont;
cont.messages = { message_user, message_assist_prefill_content };
cont.add_generation_prompt = false;
cont.continue_final_message = COMMON_CHAT_CONTINUATION_CONTENT;
cont.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
common_chat_session session(tmpls.get(), nullptr, cont);
assert_equals(std::string("<|im_start|>assistant\n<think>I'm thinking</think>Hello, "), session.generation_prompt());
session.feed(common_chat_input("world!"));
assert_msg_equals(simple_assist_msg("Hello, world!", "I'm thinking"), session.msg());
}
// tool results are their own turn, "<|im_start|>tool"
{
bool found = false;
common_chat_session session(tmpls.get(), nullptr, inputs);
for (const auto & d : session.message_delimiters().delimiters) {
found |= d.role == COMMON_CHAT_ROLE_TOOL && d.delimiter == "<|im_start|>tool\n";
}
assert_equals(true, found);
}
}
static void test_chat_json_depth() {
LOG_DBG("%s\n", __func__);
const auto arrays = [](size_t n) {
@@ -9747,6 +9890,7 @@ static void test_reasoning_effort_caps() {
assert_effort_levels("models/templates/muse-spark.jinja", { "minimal", "low", "medium", "high" });
assert_effort_levels("models/templates/upstage-Solar-Open-100B.jinja", { "low" });
assert_effort_levels("models/templates/muse-glimmer.jinja", all_levels);
assert_effort_levels("models/templates/Qwen4-35B-A3B.jinja", { "low", "high", "xhigh" });
assert_effort_levels("models/templates/openai-gpt-oss-120b.jinja", all_levels);
assert_effort_levels("models/templates/Cohere2MoE.jinja", { "none" });
assert_effort_levels("models/templates/thinkingmachines-Inkling-2-Small.jinja", { "none", "minimal", "low", "medium", "high", "max" });
@@ -9931,6 +10075,7 @@ int main(int argc, char ** argv) {
test_reasoning_effort_caps();
test_prompt_parts();
test_chat_session();
test_qwen4_chat_session();
test_chat_json_depth();
test_reasoning_budget_tokens_per_request();
test_reasoning_budget_message_per_request();
+30 -1
View File
@@ -17,7 +17,7 @@ int main(int argc, char ** argv) {
GGML_ASSERT(backend_b != nullptr);
ggml_init_params params = {
/* .mem_size = */ 3*ggml_tensor_overhead() + ggml_graph_overhead_custom(1, false),
/* .mem_size = */ 10*ggml_tensor_overhead() + ggml_graph_overhead_custom(1, false),
/* .mem_buffer = */ nullptr,
/* .no_alloc = */ true,
};
@@ -62,6 +62,35 @@ int main(int argc, char ** argv) {
GGML_ASSERT(ggml_backend_buft_get_alloc_size(buft, packed) >= ggml_nbytes(packed));
GGML_ASSERT(ggml_backend_buft_get_alloc_size(buft, strided) >= ggml_nbytes(strided));
// Two TOP_K tensors with the same output layout but different srcs must not share a cached alloc size.
// ref: https://github.com/ggml-org/llama.cpp/issues/30794
ggml_tensor * src_small = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 8);
ggml_tensor * top_k_small = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4);
top_k_small->op = GGML_OP_TOP_K;
top_k_small->src[0] = src_small;
ggml_tensor * src_large = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4096*8);
ggml_tensor * top_k_large = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4);
top_k_large->op = GGML_OP_TOP_K;
top_k_large->src[0] = src_large;
// uncached baseline for the large src: a different op_params value gives a separate cache entry
ggml_tensor * top_k_large_probe = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4);
top_k_large_probe->op = GGML_OP_TOP_K;
top_k_large_probe->src[0] = src_large;
top_k_large_probe->op_params[0] = 1;
size_t size_large_uncached = ggml_backend_buft_get_alloc_size(buft, top_k_large_probe);
// ask for the small src first, so a cache keyed without srcs holds the smaller size
size_t size_small = ggml_backend_buft_get_alloc_size(buft, top_k_small);
size_t size_large = ggml_backend_buft_get_alloc_size(buft, top_k_large);
GGML_ASSERT(size_large >= size_large_uncached);
GGML_ASSERT(size_small <= size_large);
// the small src must not be affected by the larger one
size_t size_small_again = ggml_backend_buft_get_alloc_size(buft, top_k_small);
GGML_ASSERT(size_small_again >= size_small);
ggml_free(ctx);
ggml_backend_free(backend_b);
ggml_backend_free(backend_a);
+4 -3
View File
@@ -17,7 +17,7 @@ trap cleanup EXIT
wait_for_port() {
local port=$1
for _ in {1..600}; do
for _ in {1..2400}; do
if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then
exec 3>&-
exec 3<&-
@@ -28,7 +28,8 @@ wait_for_port() {
return 1
}
"$server" --device CPU --host 127.0.0.1 --port "$port_a" >"$test_dir/server-a.log" 2>&1 &
# the TOP_K alloc size check needs a device whose alloc size depends on src0, e.g. Metal
"$server" --device "${TEST_RPC_DEVICE:-CPU}" --host 127.0.0.1 --port "$port_a" >"$test_dir/server-a.log" 2>&1 &
pid_a=$!
"$server" --device CPU --host 127.0.0.1 --port "$port_b" >"$test_dir/server-b.log" 2>&1 &
pid_b=$!
@@ -37,7 +38,7 @@ wait_for_port "$port_b"
"$client" "$endpoint_a" "$endpoint_b"
if grep -q "invalid data ptr" "$test_dir/server-b.log"; then
if grep -q "has a data pointer but no buffer" "$test_dir/server-b.log"; then
cat "$test_dir/server-b.log"
exit 1
fi
+1
View File
@@ -190,6 +190,7 @@ Get a list of tools, each tool has these fields:
- `tool` (string): the ID name of the tool, to be used in POST call. Example: `read_file`
- `display_name` (string): the name to be displayed on UI. Example: `Read file`
- `type` (string): `"server"` for a server tool, or `"mcp"` for a tool exposed by an MCP server
- `mcp_server` (string, only when `type` is `"mcp"`): the name of the MCP server the tool comes from, as declared in `--mcp-servers-config`. Example: `imcp`
- `permissions` (object): a mapping string --> boolean that indicates the permission required by this tool. This is useful for the UI to ask the user before calling the tool. For now, the only permission supported is `"write"`
- `definition` (object): the OAI-compat definition of this tool
+1 -1
View File
@@ -393,7 +393,7 @@ The same JSON can be passed inline with `--mcp-servers-json`. Each entry under `
| `cwd` | working directory of the child process |
| `timeout_ms` | per-tool-call timeout (default: 30000) |
Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `<server>_<tool>` alongside the built-in ones: they show up in Llama Chat and in `GET /tools`, and the model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available.
Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `<server>_<tool>` alongside the built-in ones: they show up in Llama Chat, which lists each of these servers on its MCP servers page, and in `GET /tools`, with `"type": "mcp"` and the server's name in `mcp_server`. The model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available.
The child process runs with the same privileges as the server, so only declare commands you trust. As with `--tools`, `--cors-origins` then defaults to `localhost`.
+2 -2
View File
@@ -1650,11 +1650,11 @@ json oaicompat_chat_params_parse(
throw std::invalid_argument("invalid type for \"enable_thinking\" (expected boolean, got string)");
}
// Parse the OAI "reasoning_effort" field; "none" disables reasoning.
// Parse the OAI "reasoning_effort" field; "none" (or "off") disables reasoning.
if (body.contains("reasoning_effort")) {
auto reasoning_effort = json_value(body, "reasoning_effort", std::string(""));
const auto levels = caps.at("reasoning_effort_levels").get<std::vector<std::string>>();
if (reasoning_effort == "none") {
if (reasoning_effort == "none" || reasoning_effort == "off") {
inputs.enable_thinking = false;
// Some models use reasoning_effort = none and some throw an exception, so check the model's list of effort levels first
if (std::find(levels.begin(), levels.end(), reasoning_effort) != levels.end()) {
+16 -5
View File
@@ -437,13 +437,22 @@ bool server_http_context::init_listener(const common_params & params) {
);
return httplib::Server::HandlerResponse::Handled;
}
if (params.cors_credentials && params.cors_origins == "*") {
// special case: echo back the Origin header to allow any origin to access the server with credentials
res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
if (params.cors_origins == "*") {
// any origin: with credentials the header can't be "*", so the request's own origin is echoed back
res.set_header("Access-Control-Allow-Origin", params.cors_credentials ? req.get_header_value("Origin") : "*");
} else if (params.cors_origins == "localhost") {
// special case: same-origin only, no CORS header needed
} else {
res.set_header("Access-Control-Allow-Origin", params.cors_origins);
// a list of origins: the header takes one origin, never the list, so the request's
// own origin is echoed back when it is one of them, and left out otherwise
const std::string origin = req.get_header_value("Origin");
for (const auto & allowed : string_split<std::string>(params.cors_origins, ',')) {
if (!origin.empty() && string_strip(allowed) == origin) {
res.set_header("Access-Control-Allow-Origin", origin);
res.set_header("Vary", "Origin");
break;
}
}
}
// If this is OPTIONS request, skip validation because browsers don't include Authorization header
if (req.method == "OPTIONS") {
@@ -537,7 +546,9 @@ bool server_http_context::init_listener(const common_params & params) {
return false;
}
if (isolation) {
res.set_header("Cross-Origin-Embedder-Policy", "require-corp");
// credentialless, not require-corp: remote images such as MCP server icons
// load straight from their host, without credentials
res.set_header("Cross-Origin-Embedder-Policy", "credentialless");
res.set_header("Cross-Origin-Opener-Policy", "same-origin");
}
res.set_header("Cache-Control", cache_control);
+7
View File
@@ -2826,6 +2826,13 @@ struct server_mcp_tool : server_tool {
std::string type() const override { return "mcp"; }
// names the server, so a client can group its tools without splitting <server>_<tool>
json to_json() const override {
json res = server_tool::to_json();
res["mcp_server"] = server_name;
return res;
}
json get_definition() const override {
json schema = def.input_schema;
if (schema.is_null() || !schema.is_object()) {
+1 -1
View File
@@ -30,7 +30,7 @@ struct server_tool {
// should_stop: true once the caller stopped waiting, e.g. the client dropped the connection; a null should_stop means "never stop"
virtual json invoke(json params, stream * st = nullptr, const std::function<bool()> & should_stop = nullptr) const = 0;
json to_json() const;
virtual json to_json() const;
};
struct server_tools_runtime; // impl detail, defined in server-tools.cpp
@@ -77,6 +77,9 @@ def test_mcp_tools_listed_in_tools_endpoint():
# Verify tool structure
echo_tool = next(t for t in mcp_tools if get_tool_name(t) == "echo_echo")
assert "description" in echo_tool or "definition" in echo_tool
assert echo_tool["type"] == "mcp"
assert echo_tool["mcp_server"] == "echo"
assert all("mcp_server" not in t for t in tools if t["type"] != "mcp")
finally:
server.stop()
+17 -9
View File
@@ -87,15 +87,21 @@ def test_openai_library_correct_api_key():
assert len(res.choices) == 1
@pytest.mark.parametrize("origin,cors_header,cors_header_value", [
("localhost", "Access-Control-Allow-Origin", "localhost"),
("web.mydomain.fr", "Access-Control-Allow-Origin", "web.mydomain.fr"),
("origin", "Access-Control-Allow-Credentials", "true"),
("web.mydomain.fr", "Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"),
("web.mydomain.fr", "Access-Control-Allow-Headers", "*"),
@pytest.mark.parametrize("cors_origins,cors_credentials,origin,cors_header,cors_header_value", [
(None, None, "localhost", "Access-Control-Allow-Origin", "localhost"),
(None, None, "web.mydomain.fr", "Access-Control-Allow-Origin", "web.mydomain.fr"),
(None, None, "origin", "Access-Control-Allow-Credentials", "true"),
(None, None, "web.mydomain.fr", "Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"),
(None, None, "web.mydomain.fr", "Access-Control-Allow-Headers", "*"),
("*", False, "web.mydomain.fr", "Access-Control-Allow-Origin", "*"),
("https://a.example, https://b.example", None, "https://a.example", "Access-Control-Allow-Origin", "https://a.example"),
("https://a.example, https://b.example", None, "https://b.example", "Access-Control-Allow-Origin", "https://b.example"),
("https://a.example, https://b.example", None, "https://c.example", "Access-Control-Allow-Origin", None),
])
def test_cors_options(origin: str, cors_header: str, cors_header_value: str):
def test_cors_options(cors_origins: str | None, cors_credentials: bool | None, origin: str, cors_header: str, cors_header_value: str | None):
global server
server.cors_origins = cors_origins
server.cors_credentials = cors_credentials
server.start()
res = server.make_request("OPTIONS", "/completions", headers={
"Origin": origin,
@@ -103,8 +109,10 @@ def test_cors_options(origin: str, cors_header: str, cors_header_value: str):
"Access-Control-Request-Headers": "Authorization",
})
assert res.status_code == 200
assert cors_header in res.headers
assert res.headers[cors_header] == cors_header_value
if cors_header_value is None:
assert cors_header not in res.headers
else:
assert res.headers[cors_header] == cors_header_value
@pytest.mark.parametrize("origin", [
+3
View File
@@ -141,6 +141,7 @@ class ServerProcess:
mcp_servers_config: str | None = None
mcp_servers_json: str | None = None
cors_origins: str | None = None
cors_credentials: bool | None = None
llama_cache: str | None = None
share_console: bool = False # Windows: console control events only reach a server on the console of the tests
@@ -209,6 +210,8 @@ class ServerProcess:
server_args.extend(["--models-preset", self.models_preset])
if self.cors_origins:
server_args.extend(["--cors-origins", self.cors_origins])
if self.cors_credentials is not None:
server_args.append("--cors-credentials" if self.cors_credentials else "--no-cors-credentials")
if self.n_batch:
server_args.extend(["--batch-size", self.n_batch])
if self.n_ubatch:
+4
View File
@@ -114,6 +114,8 @@ colors:
action-primary-hover: 'color-mix(in oklch, {colors.action-primary} 90%, transparent)'
action-danger: '{colors.fill-danger}'
action-danger-hover: 'color-mix(in oklch, {colors.action-danger} 90%, transparent)'
action-danger-secondary: 'color-mix(in oklch, {colors.fill-danger} 8%, transparent)'
action-danger-secondary-hover: 'color-mix(in oklch, {colors.fill-danger} 16%, transparent)'
action-quiet: 'oklch(0.97 0 0 / 0.3)'
action-quiet-hover: '{colors.neutral-100}'
action-ghost-hover: 'oklch(0.556 0 0 / 0.1)'
@@ -165,6 +167,8 @@ colors:
action-primary-hover-dark: 'color-mix(in oklch, {colors.action-primary-dark} 90%, transparent)'
action-danger-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 58%, transparent)'
action-danger-hover-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 68%, transparent)'
action-danger-secondary-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 12%, transparent)'
action-danger-secondary-hover-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 22%, transparent)'
action-quiet-dark: 'oklch(0.708 0 0 / 0.15)'
action-quiet-hover-dark: 'oklch(0.708 0 0 / 0.25)'
action-ghost-hover-dark: 'oklch(0.708 0 0 / 0.1)'
-6
View File
@@ -353,12 +353,6 @@ export default ts.config(
'svelte/no-navigation-without-resolve': 'off'
}
},
{
// type information for the app's own modules too, so svelte/no-navigation-without-resolve
// accepts a URL typed as ResolvedPathname, such as RouterService.chat(id)
files: ['src/**/*.ts'],
languageOptions: { parserOptions: { projectService: true } }
},
{
// Exclude generated build output and Storybook files from ESLint
ignores: [
@@ -0,0 +1,31 @@
<!--
An image of the thread shown in place, a tool's output for one: a click opens the conversation's
slideshow at it.
-->
<script lang="ts">
import { IMAGE_PREVIEW_LABEL } from '#lib/constants/index.ts';
import { mediaGalleryStore } from '#lib/stores/index.ts';
import type { DatabaseMessageExtraImageFile } from '#lib/types/database.js';
import type { ClassValue } from 'svelte/elements';
interface Props {
/** The button's classes. */
class?: ClassValue;
image: DatabaseMessageExtraImageFile;
imageClass?: ClassValue;
/** What the image is called, its file name unless given. */
name?: string;
}
let { class: className, image, imageClass, name }: Props = $props();
</script>
<button
aria-label={IMAGE_PREVIEW_LABEL(name ?? image.name)}
class={['block max-w-full cursor-zoom-in', className]}
onclick={() => mediaGalleryStore.show(image)}
type="button"
>
<!-- the button carries the name -->
<img alt="" class={imageClass} loading="lazy" src={image.base64Url} />
</button>
@@ -7,7 +7,11 @@
import ToolCallTitle from './ToolCallTitle.svelte';
import { simpleToolArgFields } from '@ggml-org/llama-harness';
import { Loader2 } from '@lucide/svelte';
import { MarkdownContent, SyntaxHighlightedCode } from '#lib/components/app/index.ts';
import {
ChatAttachmentsGalleryImage,
MarkdownContent,
SyntaxHighlightedCode
} from '#lib/components/app/index.ts';
import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts';
import { AttachmentType, FileTypeText, MimeTypeAudio, ToolResultKind } from '#lib/enums/index.ts';
import type { AgenticSection, DatabaseMessageExtra, ToolResultLine } from '#lib/types/index.ts';
@@ -145,11 +149,9 @@
</audio>
</div>
{:else}
<img
alt={line.media.name}
class="mt-2 mb-2 h-auto max-w-full rounded-lg"
loading="lazy"
src={line.media.base64Url}
<ChatAttachmentsGalleryImage
image={line.media}
imageClass="mt-2 mb-2 h-auto max-w-full rounded-lg"
/>
{/if}
{/if}
@@ -18,7 +18,7 @@
SquareArrowDown,
XCircle
} from '@lucide/svelte';
import { ShellPromptLine } from '#lib/components/app/index.ts';
import { ChatAttachmentsGalleryImage, ShellPromptLine } from '#lib/components/app/index.ts';
import {
BACKGROUND_TASK_DETACH_LABEL,
BACKGROUND_TASK_DETACH_TITLE,
@@ -314,11 +314,9 @@
</div>
{#if line.media?.type === AttachmentType.IMAGE}
<img
alt={line.media.name}
class="mt-2 mb-2 h-auto max-w-full rounded-lg"
loading="lazy"
src={line.media.base64Url}
<ChatAttachmentsGalleryImage
image={line.media}
imageClass="mt-2 mb-2 h-auto max-w-full rounded-lg"
/>
{/if}
{/each}
@@ -2,6 +2,7 @@
import { parseReadMediaMeta } from './parsers/read-media';
import ToolCallBlock from './ToolCallBlock.svelte';
import ToolCallTitle from './ToolCallTitle.svelte';
import { ChatAttachmentsGalleryImage } from '#lib/components/app/index.ts';
import { ATTACHMENT_SAVED_REGEX } from '#lib/constants/agentic.constants.ts';
import { AttachmentType, MimeTypeAudio } from '#lib/enums/index.ts';
import type {
@@ -70,11 +71,10 @@
</div>
{:else}
<div class="mt-2">
<img
alt={readMediaMeta?.fileName ?? 'media'}
class="max-h-[60vh] max-w-full rounded-lg object-contain shadow-(--elevation-raised)"
loading="lazy"
src={mediaAttachment.base64Url}
<ChatAttachmentsGalleryImage
image={mediaAttachment}
imageClass="max-h-[60vh] max-w-full rounded-lg object-contain shadow-(--elevation-raised)"
name={readMediaMeta?.fileName}
/>
</div>
{/if}
@@ -6,10 +6,13 @@
import { describeToolActivity, summarizeToolCalls } from './parsers/tool-call-phrasing';
import ToolCallElapsed from './ToolCallElapsed.svelte';
import { CollapsibleContentBlock } from '#lib/components/app/index.ts';
import { ScrollCarousel } from '#lib/components/app/index.ts';
import {
ChatAttachmentsGalleryImage,
CollapsibleContentBlock,
ScrollCarousel
} from '#lib/components/app/index.ts';
import { ScrollCarouselVariant } from '#lib/enums/index.ts';
import { mediaGalleryStore, settingsStore } from '#lib/stores/index.ts';
import { settingsStore } from '#lib/stores/index.ts';
import type { AgenticSection } from '#lib/types/index.ts';
import { imageExtras, toolCallShownArg } from '#lib/utils/index.ts';
import type { Snippet } from 'svelte';
@@ -86,19 +89,11 @@
<div transition:fade={{ duration: 150 }} class="tool-call-media">
<ScrollCarousel gapSize="2" variant={ScrollCarouselVariant.CENTER}>
{#each images as image, i (i)}
<button
aria-label={image.name ? `Preview ${image.name}` : 'Preview image'}
<ChatAttachmentsGalleryImage
class="h-16 shrink-0 overflow-hidden rounded-md border border-border/60 transition-opacity hover:opacity-80"
onclick={() => mediaGalleryStore.show(image)}
type="button"
>
<img
alt=""
class="h-full w-auto max-w-60 object-cover"
loading="lazy"
src={image.base64Url}
/>
</button>
{image}
imageClass="h-full w-auto max-w-60 object-cover"
/>
{/each}
</ScrollCarousel>
</div>
@@ -94,6 +94,9 @@ export { default as ChatAttachmentsListItemVoice } from './ChatAttachments/ChatA
*/
export { default as ChatAttachmentsListItemThumbnailImage } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailImage.svelte';
/** An image of the thread shown in place; a click opens the conversation's slideshow at it. */
export { default as ChatAttachmentsGalleryImage } from './ChatAttachments/ChatAttachmentsGalleryImage.svelte';
/**
* Unified attachment preview component for dialog display. Shows a single file
* preview without carousel, or a gallery/carousel view when multiple items exist.
@@ -30,9 +30,9 @@
SETTINGS_KEYS,
SVG
} from '#lib/constants/index.ts';
import { BooleanString, ColorMode, UrlProtocol } from '#lib/enums/index.ts';
import { AttachmentType, BooleanString, ColorMode, UrlProtocol } from '#lib/enums/index.ts';
import { createStickToBottom } from '#lib/hooks/use-stick-to-bottom.svelte.ts';
import { settingsStore } from '#lib/stores/index.ts';
import { mediaGalleryStore, settingsStore } from '#lib/stores/index.ts';
import type { DatabaseMessageExtra } from '#lib/types/database.js';
import {
copyCodeToClipboard,
@@ -456,8 +456,23 @@
* Also handles copy and preview button clicks for mermaid blocks.
* Uses event delegation: a single handler on the container.
*/
async function handleMermaidClick(event: MouseEvent) {
async function handleContentClick(event: MouseEvent) {
const target = event.target as HTMLElement;
// an attachment's image opens the conversation's slideshow at it
const image = target.closest('img');
const attachment =
image &&
attachments?.find(
(extra) =>
extra.type === AttachmentType.IMAGE && extra.base64Url === image.getAttribute('src')
);
if (attachment) {
event.preventDefault();
mediaGalleryStore.show(attachment);
return;
}
if (toggleDiagramSource(target)) {
event.preventDefault();
@@ -648,7 +663,7 @@
class="{className}{settingsStore.config[SETTINGS_KEYS.FULL_HEIGHT_CODE_BLOCKS]
? ' full-height-code-blocks'
: ''}"
onclick={handleMermaidClick}
onclick={handleContentClick}
>
{#each renderedBlocks as block (block.id)}
<div class="markdown-block" {...{ [MARKDOWN_DATA_ATTRS.BLOCK_ID]: block.id }}>
@@ -37,6 +37,14 @@ export const API_TOOLS_TASKS = {
// resume retry cadence while the owning model is still loading (server answers 503)
export const STREAM_RESUME_RETRY_MS = 2000;
// how often a stream that dropped mid-reply is rejoined before the reply is given up on. A
// phone that wakes from a locked screen has no network for its first seconds, so one try is
// not enough; each wait is STREAM_RESUME_RETRY_MS longer than the one before
export const STREAM_RESUME_MAX_ATTEMPTS = 6;
// the answers to a resume that mean the session is gone for good, so no retry helps
export const STREAM_RESUME_GONE_STATUSES: readonly number[] = [404, 410];
export const API_STREAM = {
BASE: './v1/stream',
LOOKUP: './v1/streams/lookup'
@@ -7,6 +7,10 @@ export const IMAGE = {
MEGAPIXELS_TO_PIXELS: 1_000_000
} as const;
/** What a screen reader calls an image that opens the slideshow at itself. */
export const IMAGE_PREVIEW_LABEL = (name?: string): string =>
name ? `Preview ${name}` : 'Preview image';
/**
* JPEG and EXIF binary format constants for orientation parsing.
*/
+102 -14
View File
@@ -19,7 +19,10 @@ import {
SSE_DONE_MARKER,
SSE_LINE_SEPARATOR,
STREAM_QUERY_PARAMS,
STREAM_RESUME_GONE_STATUSES,
STREAM_RESUME_LOCALSTORAGE_KEY_PREFIX,
STREAM_RESUME_MAX_ATTEMPTS,
STREAM_RESUME_RETRY_MS,
STREAM_VISIBILITY_KICK_MS
} from '#lib/constants/index.ts';
import {
@@ -500,6 +503,8 @@ export class ChatService {
// if a resume returns 200 but yields nothing, we abandon
// since the session has a bounded size, the total number of retries is bounded by construction
let madeProgress = true;
// resumes tried since the stream last made progress
let resumeAttempts = 0;
const encoder = new TextEncoder();
@@ -731,12 +736,9 @@ export class ChatService {
if (!conversationId) break;
if (!madeProgress) {
onConnectionState?.(StreamConnectionState.LOST);
onError?.(new Error('Stream resume produced no new bytes, giving up'));
break;
}
// a resume that brought nothing new counts against the same budget as one that
// failed outright; any byte of progress earns a fresh one
if (madeProgress) resumeAttempts = 0;
onConnectionState?.(StreamConnectionState.RESUMING);
madeProgress = false;
@@ -747,18 +749,61 @@ export class ChatService {
// resumeStream reads the offset from localStorage, so persist the
// freshest bytesParsed before asking the server to replay from it
ChatService.flushStreamState(conversationId);
const resumeResp = await ChatService.resumeStream(
conversationId,
abortSignal,
streamModel
).catch(() => null);
// an abort landing during the resume request is intentional, not a lost connection
let resumeResp: Response | null = null;
let isGone = false;
// A locked phone freezes the page and drops its sockets, and for the first seconds
// after it wakes the network is not back yet. So the stream is rejoined only once the
// page is in front and online again, and a failed try is repeated a few times before
// the reply is given up on; the server keeps the session meanwhile
while (resumeAttempts < STREAM_RESUME_MAX_ATTEMPTS) {
await ChatService.waitUntilReachable(abortSignal);
if (abortSignal?.aborted) break;
if (resumeAttempts > 0) {
await ChatService.sleep(resumeAttempts * STREAM_RESUME_RETRY_MS, abortSignal);
if (abortSignal?.aborted) break;
}
resumeAttempts++;
const response = await ChatService.resumeStream(
conversationId,
abortSignal,
streamModel
).catch(() => null);
// an abort landing during the resume request is intentional, not a lost connection
if (abortSignal?.aborted) break;
if (response?.status === 200) {
resumeResp = response;
break;
}
// the session is gone: the server restarted or it expired, no retry brings it back
if (response && STREAM_RESUME_GONE_STATUSES.includes(response.status)) {
isGone = true;
break;
}
}
if (abortSignal?.aborted) break;
if (!resumeResp || resumeResp.status !== 200) {
if (!resumeResp) {
onConnectionState?.(StreamConnectionState.LOST);
onError?.(new Error('Stream connection lost and could not be resumed'));
onError?.(
new Error(
isGone
? 'Stream connection lost and its session is gone'
: 'Stream connection lost and could not be resumed'
)
);
break;
}
@@ -1709,6 +1754,21 @@ export class ChatService {
}
}
/** Resolves after `ms`, or at once when the signal aborts. */
private static sleep(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve) => {
const timer = setTimeout(done, ms);
function done() {
clearTimeout(timer);
signal?.removeEventListener('abort', done);
resolve();
}
signal?.addEventListener('abort', done, { once: true });
});
}
/**
* Strips legacy inline reasoning content tags from message content.
* Handles both plain string content and multipart content arrays.
@@ -1732,6 +1792,34 @@ export class ChatService {
});
}
/**
* Resolves once the page can reach the server again: in front and online. A hidden page is
* throttled or frozen and an offline one cannot fetch, so a request made then only burns a try.
* Resolves at once where there is no document, and when the signal aborts.
*/
private static waitUntilReachable(signal?: AbortSignal): Promise<void> {
const isReachable = () =>
typeof document === 'undefined' ||
(document.visibilityState === 'visible' && navigator.onLine !== false);
if (isReachable() || signal?.aborted) return Promise.resolve();
return new Promise((resolve) => {
function check() {
if (!isReachable() && !signal?.aborted) return;
document.removeEventListener('visibilitychange', check);
window.removeEventListener('online', check);
signal?.removeEventListener('abort', check);
resolve();
}
document.addEventListener('visibilitychange', check);
window.addEventListener('online', check);
signal?.addEventListener('abort', check, { once: true });
});
}
// write the resume state straight to localStorage, bypassing the throttle
private static writeStreamState(
conversationId: string,
@@ -48,7 +48,7 @@ function getUploadedFileCategory(file: ChatUploadedFile): FileTypeCategory | nul
/**
* Creates a unified list of display items from uploaded files and stored attachments.
* Items are returned in reverse order (newest first).
* Items keep the order they were added in.
*/
export function getAttachmentDisplayItems(
options: AttachmentDisplayItemsOptions
@@ -96,5 +96,5 @@ export function getAttachmentDisplayItems(
});
}
return items.reverse();
return items;
}
+4
View File
@@ -83,6 +83,10 @@ export function filterByLeafNodeId(
currentNode = nodeMap.get(currentNode.parent);
}
// root first, so messages of the same timestamp (results of parallel tool calls) keep their
// order through the stable sort below
result.reverse();
// Sort: system messages first, then by timestamp
result.sort((a, b) => {
if (a.role === MessageRole.SYSTEM && b.role !== MessageRole.SYSTEM) return -1;
@@ -0,0 +1,23 @@
// The order getAttachmentDisplayItems returns: the order the attachments were added in, as the
// attachment lists show them.
import { AttachmentType } from '#lib/enums/index.ts';
import type { DatabaseMessageExtra } from '#lib/types/database.js';
import { getAttachmentDisplayItems } from '#lib/utils/attachment-display.ts';
import { describe, expect, it } from 'vitest';
const attachments = ['first.png', 'second.png'].map(
(name): DatabaseMessageExtra => ({
base64Url: `data:image/png;base64,${name}`,
name,
type: AttachmentType.IMAGE
})
);
describe('getAttachmentDisplayItems', () => {
it('keeps the order they were added in', () => {
const names = getAttachmentDisplayItems({ attachments }).map((item) => item.name);
expect(names).toEqual(['first.png', 'second.png']);
});
});
+10 -1
View File
@@ -4,7 +4,7 @@
import { MessageRole, MessageType } from '#lib/enums/index.ts';
import type { DatabaseMessage } from '#lib/types/database.js';
import { buildSiblingInfoMap, findLeafNode } from '#lib/utils/branching.ts';
import { buildSiblingInfoMap, filterByLeafNodeId, findLeafNode } from '#lib/utils/branching.ts';
import { describe, expect, it } from 'vitest';
function msg(id: string, parent: string | null, children: string[] = []): DatabaseMessage {
@@ -93,3 +93,12 @@ describe('buildSiblingInfoMap', () => {
}
});
});
describe('filterByLeafNodeId', () => {
it('keeps the path order for messages of the same timestamp', () => {
// every message of the chain has timestamp 0, as parallel tool results can
const ids = filterByLeafNodeId(linearChain(3), 'm3').map((message) => message.id);
expect(ids).toEqual(['m0', 'm1', 'm2', 'm3']);
});
});