Compare commits

...
7 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
41 changed files with 2258 additions and 1495 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."""
+6 -17
View File
@@ -5390,7 +5390,8 @@ static bool htp_kparams_solve_conv2d_dw(
}
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;
}
@@ -5437,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) {
@@ -5464,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);
@@ -5478,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;
@@ -5504,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 -1
View File
@@ -52,7 +52,7 @@ add_library(${HTP_LIB} SHARED
argsort-ops.c
im2col-ops.c
conv2d-ops.c
conv2d-dw5-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
-295
View File
@@ -1,295 +0,0 @@
// HVX + DMA kernel for 5x5 stride-1 pad-2 dilation-1 depthwise conv (f16/f32 weights, inputs, and outputs).
#include "conv2d-ops.h"
#include "dma-pipeline.h"
#include "hex-common.h"
#include "htp-ctx.h"
#include "htp-ops.h"
#include "htp-tensor.h"
#include "hvx-base.h"
#include "hvx-copy.h"
#include <HAP_farf.h>
typedef void (*conv_2d_dw5_prep_weights_fn)(const void * restrict, HVX_Vector * restrict);
typedef void (*conv_2d_dw5_plane_fn)(const uint8_t * restrict, const HVX_Vector * restrict, void * restrict, uint32_t, uint32_t, uint32_t);
struct conv_2d_dw5_hvx_context {
struct htp_ops_context * octx;
struct htp_conv2d_dw5_vtcm_layout layout;
conv_2d_dw5_prep_weights_fn prep_weights_fn;
conv_2d_dw5_plane_fn plane_fn;
uint32_t weight_bytes;
uint32_t halo_offset;
uint32_t plane_start;
uint32_t plane_count;
uint32_t planes_per_thread;
};
// Zero both source slots once per thread; DMA only writes the interior, so the 2-pixel halo stays zero.
static __attribute__((noinline)) void conv_2d_dw5_clear(uint8_t * restrict data, uint32_t bytes) {
const HVX_Vector zero = Q6_V_vzero();
for (uint32_t offset = 0; offset < bytes; offset += VLEN) {
*(HVX_Vector *) (data + offset) = zero;
}
}
static inline __attribute__((always_inline)) void conv_2d_dw5_splat_weights(HVX_Vector w, HVX_Vector * restrict wsplat) {
for (uint32_t t = 0; t < 25; ++t) {
wsplat[t] = hvx_vec_repl4(Q6_V_vror_VR(w, t * sizeof(float)));
}
}
static __attribute__((noinline)) void conv_2d_dw5_prep_weights_f16(const void * restrict wsrc, HVX_Vector * restrict wsplat) {
conv_2d_dw5_splat_weights(Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) wsrc)), wsplat);
}
static __attribute__((noinline)) void conv_2d_dw5_prep_weights_f32(const void * restrict wsrc, HVX_Vector * restrict wsplat) {
conv_2d_dw5_splat_weights(*(const HVX_Vector *) wsrc, wsplat);
}
// One output plane. src rows are 128B aligned with the 2-pixel left halo at the row start, so the five kx taps
// of a 32-wide output vector are valigns of two aligned loads.
static inline __attribute__((always_inline)) void conv_2d_dw5_plane_impl(const uint8_t * restrict src,
const HVX_Vector * restrict wsplat,
void * restrict dst,
uint32_t src_row_stride,
uint32_t ow,
uint32_t oh,
const bool src_f16,
const bool dst_f16) {
for (uint32_t oy = 0; oy < oh; ++oy) {
for (uint32_t ox = 0; ox < ow; ox += 2 * VLEN_FP32) {
HVX_Vector acc0 = Q6_V_vzero();
HVX_Vector acc1 = Q6_V_vzero();
for (uint32_t ky = 0; ky < 5; ++ky) {
const HVX_Vector * w = wsplat + ky * 5;
HVX_Vector v0, v1, v2;
if (src_f16) {
const HVX_Vector * row = (const HVX_Vector *) (src + (oy + ky) * src_row_stride + ox * sizeof(__fp16));
const HVX_VectorPair p0 = hvx_vec_f16_to_f32(row[0]);
v0 = Q6_V_lo_W(p0);
v1 = Q6_V_hi_W(p0);
v2 = Q6_V_lo_W(hvx_vec_f16_to_f32(row[1]));
} else {
const HVX_Vector * row = (const HVX_Vector *) (src + (oy + ky) * src_row_stride + ox * sizeof(float));
v0 = row[0];
v1 = row[1];
v2 = row[2];
}
const HVX_Vector a01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(v0, w[0]),
Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 4), w[1]));
const HVX_Vector a23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 8), w[2]),
Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 12), w[3]));
const HVX_Vector a4 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 16), w[4]));
acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a01, a23), a4);
const HVX_Vector b01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(v1, w[0]),
Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 4), w[1]));
const HVX_Vector b23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 8), w[2]),
Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 12), w[3]));
const HVX_Vector b4 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 16), w[4]));
acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(b01, b23), b4);
}
const uint32_t rem = ow - ox;
if (dst_f16) {
__fp16 * out = (__fp16 *) dst + oy * ow + ox;
const HVX_Vector out_f16 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(acc1, acc0)));
hvx_vec_store_u(out, MIN(rem, VLEN_FP16) * sizeof(__fp16), out_f16);
} else {
float * out = (float *) dst + oy * ow + ox;
hvx_vec_store_u(out, MIN(rem, VLEN_FP32) * sizeof(float), Q6_Vsf_equals_Vqf32(acc0));
if (rem > VLEN_FP32) {
hvx_vec_store_u(out + VLEN_FP32, MIN(rem - VLEN_FP32, VLEN_FP32) * sizeof(float),
Q6_Vsf_equals_Vqf32(acc1));
}
}
}
}
}
static __attribute__((noinline)) void conv_2d_dw5_plane_f32_f32(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) {
conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, false, false);
}
static __attribute__((noinline)) void conv_2d_dw5_plane_f32_f16(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) {
conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, false, true);
}
static __attribute__((noinline)) void conv_2d_dw5_plane_f16_f32(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) {
conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, true, false);
}
static __attribute__((noinline)) void conv_2d_dw5_plane_f16_f16(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) {
conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, true, true);
}
struct conv_2d_dw5_pipe_state {
dma_addr_t w_data;
dma_addr_t in_data;
dma_addr_t out_data;
HVX_Vector * wsplat;
conv_2d_dw5_prep_weights_fn prep_weights_fn;
conv_2d_dw5_plane_fn plane_fn;
uint32_t plane;
uint32_t last;
uint32_t c_next;
uint32_t channels;
uint32_t ih;
uint32_t ow;
uint32_t oh;
uint32_t stride;
uint32_t in_row;
uint32_t in_plane;
uint32_t out_row;
uint32_t out_plane;
uint32_t w_plane;
uint32_t weight_bytes;
uint32_t halo_offset;
};
static bool conv_2d_dw5_next_task(void * ctx, struct dma_pipe_task * task) {
struct conv_2d_dw5_pipe_state * s = (struct conv_2d_dw5_pipe_state *) ctx;
if (s->plane >= s->last) {
return false;
}
task->row = s->plane;
task->aux = s->c_next;
s->plane++;
s->c_next = (s->c_next + 1 == s->channels) ? 0 : s->c_next + 1;
return true;
}
static void conv_2d_dw5_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) {
const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx;
dma_queue_push(dma_q, dma_make_data(in0_spad, s->w_data + (dma_addr_t) task->aux * s->w_plane),
VLEN, s->w_plane, s->weight_bytes, 1);
dma_queue_push(dma_q, dma_make_data(in1_spad, s->in_data + (dma_addr_t) task->row * s->in_plane),
s->stride, s->in_row, s->in_row, s->ih);
}
static void conv_2d_dw5_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) {
(void) task;
const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx;
s->prep_weights_fn(in0_spad, s->wsplat);
s->plane_fn((const uint8_t *) in1_spad - s->halo_offset, s->wsplat, out_spad, s->stride, s->ow, s->oh);
}
static void conv_2d_dw5_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx;
dma_queue_push(dma_q, dma_make_data(s->out_data + (dma_addr_t) task->row * s->out_plane, out_spad),
s->out_row, s->out_row, s->out_row, s->oh);
}
// Planes are processed in memory order (plane = n * C + c). Each plane is three DMAs: weights in, src in, dst out.
// Two buffers per stream: plane i+1 is in flight while plane i is computed.
static void conv_2d_dw5_hvx_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
const struct conv_2d_dw5_hvx_context * ctx = (const struct conv_2d_dw5_hvx_context *) data;
const struct htp_ops_context * octx = ctx->octx;
const struct htp_conv2d_dw5_vtcm_layout * L = &ctx->layout;
const struct htp_tensor * weight = octx->src[0];
const struct htp_tensor * input = octx->src[1];
const struct htp_tensor * output = octx->dst;
const uint32_t first = ctx->plane_start + ith * ctx->planes_per_thread;
const uint32_t last = MIN(first + ctx->planes_per_thread, ctx->plane_start + ctx->plane_count);
if (first >= last) {
return;
}
uint8_t * vtcm = octx->ctx->vtcm_base;
uint8_t * src_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_src) + ith * 2 * L->src_slot_bytes;
uint8_t * weight_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_weight) + ith * HTP_CONV2D_DW5_W_BYTES;
uint8_t * dst_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_dst) + ith * 2 * L->dst_slot_bytes;
const uint32_t halo_offset = ctx->halo_offset;
void * in0_buf[2] = { weight_base, weight_base + VLEN };
void * in1_buf[2] = { src_base + halo_offset, src_base + L->src_slot_bytes + halo_offset };
void * out_buf[2] = { dst_base, dst_base + L->dst_slot_bytes };
conv_2d_dw5_clear(src_base, 2 * L->src_slot_bytes);
struct conv_2d_dw5_pipe_state s = {
.w_data = weight->data,
.in_data = input->data,
.out_data = output->data,
.wsplat = (HVX_Vector *) (weight_base + 2 * VLEN),
.prep_weights_fn = ctx->prep_weights_fn,
.plane_fn = ctx->plane_fn,
.plane = first,
.last = last,
.c_next = first % input->ne[2],
.channels = input->ne[2],
.ih = input->ne[1],
.ow = output->ne[0],
.oh = output->ne[1],
.stride = L->src_row_stride,
.in_row = input->nb[1],
.in_plane = input->nb[2],
.out_row = output->nb[1],
.out_plane = output->nb[2],
.w_plane = weight->nb[3],
.weight_bytes = ctx->weight_bytes,
.halo_offset = halo_offset,
};
dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf,
conv_2d_dw5_next_task, conv_2d_dw5_push_in, conv_2d_dw5_compute, conv_2d_dw5_push_out);
FARF(HIGH, "conv2d-dw-hvx-dma-5x5 %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n", ith, nth, input->ne[0],
input->ne[1], input->ne[2], input->ne[3], output->ne[0], output->ne[1], output->ne[2], output->ne[3], first,
last);
}
int op_conv_2d_dw5(struct htp_ops_context * octx) {
// Tensor shapes, types and VTCM sizing were validated by the host (htp_kparams_solve_conv2d_dw).
const struct htp_conv2d_dw_kernel_params * kp = (const struct htp_conv2d_dw_kernel_params *) octx->kernel_params;
uint32_t plane_start = 0;
uint32_t plane_count = kp->total_tasks;
if (octx->ctx->mdev.count > 1) {
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
plane_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
plane_start = range.start;
plane_count = range.count;
}
if (plane_count == 0) {
return HTP_STATUS_OK;
}
static const conv_2d_dw5_plane_fn plane_fns[2][2] = {
{ conv_2d_dw5_plane_f32_f32, conv_2d_dw5_plane_f32_f16 },
{ conv_2d_dw5_plane_f16_f32, conv_2d_dw5_plane_f16_f16 },
};
const bool w_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0;
const bool src_f16 = (octx->src[1]->type == HTP_TYPE_F16);
const bool dst_f16 = (octx->dst->type == HTP_TYPE_F16);
const size_t src_es = src_f16 ? sizeof(__fp16) : sizeof(float);
const size_t dst_es = dst_f16 ? sizeof(__fp16) : sizeof(float);
const uint32_t weight_bytes = 25 * (w_f16 ? sizeof(__fp16) : sizeof(float));
struct htp_conv2d_dw5_vtcm_layout layout;
htp_conv2d_dw5_vtcm_layout_build(&layout, kp->w, kp->h, src_es, dst_es, kp->n_hvx);
const uint32_t n_threads = MIN(kp->n_hvx, plane_count);
const uint32_t planes_per_thread = (plane_count + n_threads - 1) / n_threads;
struct conv_2d_dw5_hvx_context ctx = {
.octx = octx,
.layout = layout,
.prep_weights_fn = w_f16 ? conv_2d_dw5_prep_weights_f16 : conv_2d_dw5_prep_weights_f32,
.plane_fn = plane_fns[src_f16][dst_f16],
.weight_bytes = weight_bytes,
.halo_offset = 2 * layout.src_row_stride + 2 * src_es,
.plane_start = plane_start,
.plane_count = plane_count,
.planes_per_thread = planes_per_thread,
};
work_queue_run(octx->ctx->hvx_queue, conv_2d_dw5_hvx_thread, &ctx, n_threads);
return HTP_STATUS_OK;
}
-908
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,910 +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;
}
if (kp->kernel_type == HTP_CONV2D_DW_KERNEL_WHCN_5X5_DMA) {
return op_conv_2d_dw5(octx);
}
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;
}
-117
View File
@@ -88,123 +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_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 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_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;
}
struct htp_conv2d_vtcm_layout {
size_t total_bytes;
size_t off_scales;
-1
View File
@@ -185,7 +185,6 @@ int op_im2col(struct htp_ops_context * octx);
int op_im2col_3d(struct htp_ops_context * octx);
int op_conv_2d(struct htp_ops_context * octx);
int op_conv_2d_dw(struct htp_ops_context * octx);
int op_conv_2d_dw5(struct htp_ops_context * octx);
int op_pool_2d(struct htp_ops_context * octx);
int op_pool_1d(struct htp_ops_context * octx);
int op_allreduce(struct htp_ops_context * octx);
+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);
+1
View File
@@ -1034,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;
+13 -5
View File
@@ -4354,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);
@@ -10948,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;
@@ -11401,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:
{
@@ -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;
}
@@ -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"}}));
+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}")
+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;
+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,
+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
+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()) {
@@ -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']);
});
});