From 8af68d486a9473820d24d00af8f33334ca80124d Mon Sep 17 00:00:00 2001 From: "Piotr Wilkin (ilintar)" Date: Thu, 19 Nov 2026 14:36:30 +0100 Subject: [PATCH 01/88] llama: fixes for Inkling 2 attention mask (#32429) * llama : give Inkling2 its own relative-position attention input The Inkling2 graph built its flash attention mask from the hybrid iswa input and passed it to build_attn through a new kq_mask argument. That argument let a caller pair its own dense mask with the kv_rows of llm_graph_input_attn_kv_iswa, whose mask follows the per-sequence cell lists whenever kv_rows is enabled. Add llm_graph_input_attn_rel_pos instead. It owns dense KQ masks and the query-to-cell distances, fills both from the same cells, and its build_attn overload adds the per-head bias to its own mask and never passes kv_rows. The iswa build_attn is back to its previous signature; its body moves to build_attn_iswa_impl, which both overloads call. Inkling2 now folds the per-query sink into the bias with and without flash attention, so build_attn_mha no longer needs the per-query sink path. Assisted-By: Claude Opus 5.5 * inkling2 : make the expert weight scale and final logit softcap optional Load both keys as optional and skip them when they are zero, as other models do, instead of rejecting zero at load. Assisted-By: Claude Opus 5.5 * llama : build kv_rows masks for the hybrid iswa memory llm_graph_input_mem_hybrid_iswa checked its masks with can_reuse_attn_mask, which expects kv_rows whenever they are enabled, but built them dense. With a unified cache and flash attention the check always failed, and hybrid iswa models (LFM2, LFM3, Inkling2) never reused a graph. Build the masks with build_attn_inp_attn_mask, like the plain iswa input. Assisted-By: Claude Opus 5.5 * llama : make the relative-position input a hybrid iswa input Address review: llm_graph_input_mem_hybrid_iswa_rel derives from llm_graph_input_mem_hybrid_iswa and owns the attention and recurrent inputs, so Inkling2 builds one memory input instead of two. Its attention input is built with dense masks, can_reuse checks them as dense, and its build_attn asserts that the mask has no kv_rows (TODO: a kv_rows variant). build_attn_iswa_impl is now a static helper. Assisted-By: Claude Opus 5.5 * llama : compose the hybrid iswa rel input, format inkling2 Address review: llm_graph_input_mem_hybrid_iswa_rel owns its attention and recurrent inputs like the other composite inputs instead of deriving from llm_graph_input_mem_hybrid_iswa. Format src/models/inkling2.cpp like the other model sources: grouped and aligned key and tensor loading, descriptive per-layer names, blank lines and section comments between the steps, and cb() names for the intermediate tensors. The graph is unchanged. Assisted-By: Claude Opus 5.5 --- src/llama-graph.cpp | 233 ++++++++++++++++--- src/llama-graph.h | 64 +++++- src/models/inkling2.cpp | 486 ++++++++++++++++++++++++---------------- src/models/models.h | 9 +- 4 files changed, 568 insertions(+), 224 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 6706e238ed69..269b920fb8e3 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1400,6 +1400,91 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) return res; } +void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) { + const auto * attn_ctx = mctx->get_attn(); + + // base tensors may not be allocated if there are no non-SWA attention layers + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { + attn_ctx->get_base()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); + attn_ctx->get_base()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); + } + + if (inp_attn->self_attn_mask.raw && inp_attn->self_attn_mask.raw->buffer) { + attn_ctx->get_base()->set_input_attn_mask(inp_attn->self_attn_mask, ubatch, cparams.causal_attn); + } + + if (self_rel_pos->buffer) { + attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, ubatch, extent); + } + + // swa tensors may not be allocated if there are no SWA attention layers + if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { + attn_ctx->get_swa()->set_input_k_idxs(inp_attn->self_k_idxs_swa, ubatch); + attn_ctx->get_swa()->set_input_v_idxs(inp_attn->self_v_idxs_swa, ubatch); + } + + if (inp_attn->self_attn_mask_swa.raw && inp_attn->self_attn_mask_swa.raw->buffer) { + attn_ctx->get_swa()->set_input_attn_mask(inp_attn->self_attn_mask_swa, ubatch, cparams.causal_attn); + } + + if (self_rel_pos_swa->buffer) { + attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); + } + + const int64_t n_rs = mctx->get_recr()->get_n_rs(); + + if (inp_rs->s_copy) { + GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); + int32_t * data = (int32_t *) inp_rs->s_copy->data; + + // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n + for (uint32_t i = 0; i < n_rs; ++i) { + data[i] = mctx->get_recr()->s_copy(i); + } + } +} + +bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) { + const auto * mctx = static_cast(params.mctx); + + this->mctx = mctx; + + bool res = true; + + const auto * attn_ctx = mctx->get_attn(); + + // the masks are always dense, see build_inp_mem_hybrid_iswa_rel() + + // base tensors may not be allocated if there are no non-SWA attention layers + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { + res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; + } + + res &= can_reuse_kq_mask(inp_attn->self_attn_mask.raw, attn_ctx->get_base(), params.ubatch, params.cparams); + + res &= self_rel_pos->ne[0] == attn_ctx->get_base()->get_n_kv(); + res &= self_rel_pos->ne[1] == params.ubatch.n_tokens; + + // swa tensors may not be allocated if there are no SWA attention layers + if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { + res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; + } + + res &= can_reuse_kq_mask(inp_attn->self_attn_mask_swa.raw, attn_ctx->get_swa(), params.ubatch, params.cparams); + + res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); + res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; + + res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); + + res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; + + res &= inp_rs->head == mctx->get_recr()->get_head(); + res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + + return res; +} + void llm_graph_input_sampling::set_input(const llama_ubatch * ubatch) { // set the inputs only for the active samplers in the current ubatch std::unordered_set active_samplers; @@ -3113,7 +3198,7 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * cur; - const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr && (!sinks || ggml_is_vector(sinks)); + const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; GGML_ASSERT(use_flash_attn || kv_rows == nullptr); if (use_flash_attn) { GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet"); @@ -3196,16 +3281,8 @@ ggml_tensor * llm_graph_context::build_attn_mha( cb(kq, "kq_plus_kq_b", il); } - if (sinks && !ggml_is_vector(sinks)) { - // Per-query sinks are extra logits with zero values. - const int64_t n_kv = kq->ne[0]; - kq = ggml_add(ctx0, ggml_scale(ctx0, kq, kq_scale), ggml_cast(ctx0, kq_mask, GGML_TYPE_F32)); - kq = ggml_soft_max(ctx0, ggml_concat(ctx0, kq, sinks, 0)); - kq = ggml_cont(ctx0, ggml_view_4d(ctx0, kq, n_kv, kq->ne[1], kq->ne[2], kq->ne[3], kq->nb[1], kq->nb[2], kq->nb[3], 0)); - } else { - kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias); - ggml_soft_max_add_sinks(kq, sinks); - } + kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias); + ggml_soft_max_add_sinks(kq, sinks); cb(kq, "kq_soft_max", il); if (!v_trans) { @@ -3687,7 +3764,9 @@ ggml_tensor * llm_graph_context::build_attn( return cur; } -ggml_tensor * llm_graph_context::build_attn( +// the iswa build_attn with the KQ mask and kv_rows given by the caller, which has to keep them in sync +static ggml_tensor * build_attn_iswa_impl( + const llm_graph_context & gctx, llm_graph_input_attn_kv_iswa * inp, ggml_tensor * wo, ggml_tensor * wo_b, @@ -3696,11 +3775,18 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * k_cur, ggml_tensor * v_cur, ggml_tensor * kq_b, + ggml_tensor * kq_mask, + ggml_tensor * kv_rows, ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il, - ggml_tensor * kq_mask) const { + int il) { + ggml_context * ctx0 = gctx.ctx0; + ggml_cgraph * gf = gctx.gf; + + const auto & hparams = gctx.hparams; + const auto & cparams = gctx.cparams; + const bool is_swa = hparams.is_swa(il); auto * k_rot = is_swa ? inp->self_k_rot_swa[il] : inp->self_k_rot[il]; @@ -3738,7 +3824,7 @@ ggml_tensor * llm_graph_context::build_attn( // whole seq fits into batch in training mode const bool use_kv_cur = cparams.training && k_cur && v_cur; if (use_kv_cur) { - GGML_ASSERT(mctx_cur->get_n_kv() == n_tokens); + GGML_ASSERT(mctx_cur->get_n_kv() == gctx.n_tokens); } const bool store_kv = !use_kv_cur || hparams.n_layer_kv_from_start >= 0; @@ -3756,25 +3842,20 @@ ggml_tensor * llm_graph_context::build_attn( ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); } - if (!kq_mask) { - kq_mask = is_swa ? inp->self_attn_mask_swa.raw : inp->self_attn_mask.raw; - } - const auto & kv_rows = is_swa ? inp->self_attn_mask_swa.rows : inp->self_attn_mask.rows; - ggml_tensor * q = q_cur; ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); - cb(cur, "kqv_out", il); + gctx.cb(cur, "kqv_out", il); if (v_rot) { cur = llama_mul_mat_hadamard(ctx0, cur, v_rot); } if (wo) { - cur = build_lora_mm(wo, cur, wo_s); + cur = gctx.build_lora_mm(wo, cur, wo_s); } if (wo_b) { @@ -3788,6 +3869,27 @@ ggml_tensor * llm_graph_context::build_attn( return cur; } +ggml_tensor * llm_graph_context::build_attn( + llm_graph_input_attn_kv_iswa * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, + ggml_tensor * k_cur, + ggml_tensor * v_cur, + ggml_tensor * kq_b, + ggml_tensor * sinks, + ggml_tensor * v_mla, + float kq_scale, + int il) const { + const bool is_swa = hparams.is_swa(il); + + const auto & kq_mask = is_swa ? inp->self_attn_mask_swa.raw : inp->self_attn_mask.raw; + const auto & kv_rows = is_swa ? inp->self_attn_mask_swa.rows : inp->self_attn_mask.rows; + + return build_attn_iswa_impl(*this, inp, wo, wo_b, wo_s, q_cur, k_cur, v_cur, kq_b, kq_mask, kv_rows, sinks, v_mla, kq_scale, il); +} + ggml_tensor * llm_graph_context::build_attn( llm_graph_input_attn_k_iswa * inp, ggml_tensor * wo, @@ -4310,14 +4412,14 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + inp_attn->self_attn_mask = build_attn_inp_attn_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); } { inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + inp_attn->self_attn_mask_swa = build_attn_inp_attn_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); } inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); @@ -4331,6 +4433,87 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() return (llm_graph_input_mem_hybrid_iswa *) res->add_input(std::move(inp)); } +llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_iswa_rel( + uint32_t extent, + uint32_t extent_swa) const { + const auto * mctx_cur = static_cast(mctx); + + auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); + + const auto * attn_ctx = mctx_cur->get_attn(); + + auto inp_attn = std::make_unique(hparams, cparams, attn_ctx); + + // dense masks: the bias is gathered by the distance to each cell of the K/V view + { + inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); + inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); + + inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + } + + { + inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); + inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); + + inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + } + + inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); + inp_attn->self_v_rot = attn_ctx->get_base()->get_v_rot(); + + inp_attn->self_k_rot_swa = attn_ctx->get_swa()->get_k_rot(); + inp_attn->self_v_rot_swa = attn_ctx->get_swa()->get_v_rot(); + + auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur, extent, extent_swa); + + inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos); + ggml_set_name(inp->self_rel_pos, "attn_inp_rel_pos"); + + inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_swa()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos_swa); + ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); + + return (llm_graph_input_mem_hybrid_iswa_rel *) res->add_input(std::move(inp)); +} + +ggml_tensor * llm_graph_context::build_attn( + llm_graph_input_mem_hybrid_iswa_rel * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, + ggml_tensor * k_cur, + ggml_tensor * v_cur, + ggml_tensor * kq_b, + ggml_tensor * sinks, + float kq_scale, + int il) const { + const bool is_swa = hparams.is_swa(il); + + auto * inp_attn = inp->get_attn(); + + const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; + + // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, + // needs a kv_rows flash attention with a per-head mask (CUDA has none) + GGML_ASSERT(attn_mask.rows == nullptr); + + // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 + ggml_tensor * kq_mask = attn_mask.raw; + if (kq_mask->type != GGML_TYPE_F32) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } + kq_mask = ggml_add(ctx0, kq_b, kq_mask); + if (cparams.flash_attn) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } + cb(kq_mask, "kq_mask_rel_pos", il); + + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); +} + void llm_graph_context::build_dense_out( ggml_tensor * dense_2, ggml_tensor * dense_2_b, diff --git a/src/llama-graph.h b/src/llama-graph.h index 06ccc4075ad3..b5956ead9120 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -774,6 +774,48 @@ class llm_graph_input_mem_hybrid_iswa : public llm_graph_input_i { const llama_memory_hybrid_iswa_context * mctx; }; +// hybrid iswa memory with a per-head attention bias that depends on the distance from the query to the cell (Inkling) +// the KQ masks are always dense (rows == nullptr) and are filled from the same cells as the distances, so that the bias +// gathered by distance lines up with the mask +class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { +public: + llm_graph_input_mem_hybrid_iswa_rel( + const llama_cparams & cparams, + std::unique_ptr inp_attn, + std::unique_ptr inp_rs, + const llama_memory_hybrid_iswa_context * mctx, + uint32_t extent, + uint32_t extent_swa) : + inp_attn(std::move(inp_attn)), + inp_rs(std::move(inp_rs)), + extent(extent), + extent_swa(extent_swa), + cparams(cparams), + mctx(mctx) { } + virtual ~llm_graph_input_mem_hybrid_iswa_rel() = default; + + void set_input(const llama_ubatch * ubatch) override; + + bool can_reuse(const llm_graph_params & params) override; + + std::unique_ptr inp_attn; + std::unique_ptr inp_rs; + + llm_graph_input_attn_kv_iswa * get_attn() const { return inp_attn.get(); } + llm_graph_input_rs * get_recr() const { return inp_rs.get(); } + + // distance from the token to the cell, extent for the empty, future and more distant cells + ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] + ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] + + const uint32_t extent; + const uint32_t extent_swa; + + const llama_cparams cparams; + + const llama_memory_hybrid_iswa_context * mctx; +}; + class llm_graph_input_sampling : public llm_graph_input_i { public: llm_graph_input_sampling(std::map samplers) : @@ -1401,8 +1443,7 @@ struct llm_graph_context { ggml_tensor * sinks, // [n_head_q] ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] float kq_scale, - int il, - ggml_tensor * kq_mask = nullptr) const; + int il) const; llm_graph_input_attn_k_iswa * build_attn_inp_k_iswa() const; @@ -1495,6 +1536,25 @@ struct llm_graph_context { llm_graph_input_mem_hybrid_iswa * build_inp_mem_hybrid_iswa() const; + // extent, extent_swa: the distance that the bias tables of the full and the SWA layers stop at + llm_graph_input_mem_hybrid_iswa_rel * build_inp_mem_hybrid_iswa_rel( + uint32_t extent, + uint32_t extent_swa) const; + + // kq_b is added to the KQ mask, after the KQ scale + ggml_tensor * build_attn( + llm_graph_input_mem_hybrid_iswa_rel * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] + ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] + ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] + ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] + ggml_tensor * sinks, // [n_head_q] + float kq_scale, + int il) const; + // // pooling // diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 41eebd1908df..3ba20ffe83d4 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -2,111 +2,157 @@ #include "../llama-memory-hybrid-iswa.h" void llama_model_inkling2::load_arch_hparams(llama_model_loader & ml) { - ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_QK_CLIP, hparams.f_qk_clip); + ml.get_key(LLM_KV_ATTN_RES_BLOCK_SIZE, hparams.attn_res_block_size); + ml.get_key(LLM_KV_SHORTCONV_L_CACHE, hparams.n_shortconv_l_cache); + + // relative-position bias, and the log-scaled positions of the full-attention layers ml.get_key(LLM_KV_ATTENTION_RELATIVE_LENGTH, hparams.n_relative); ml.get_key(LLM_KV_ATTENTION_RELATIVE_EXTENT, hparams.n_relative_extent); - ml.get_key(LLM_KV_ATTENTION_QK_CLIP, hparams.f_qk_clip); - ml.get_key(LLM_KV_ATTENTION_RELATIVE_CLIP, hparams.f_relative_clip); + ml.get_key(LLM_KV_ATTENTION_RELATIVE_CLIP, hparams.f_relative_clip); ml.get_key(LLM_KV_ATTENTION_LOG_SCALE_FLOOR, hparams.n_log_scale_floor); ml.get_key(LLM_KV_ATTENTION_LOG_SCALE_ALPHA, hparams.f_log_scale_alpha); - ml.get_key(LLM_KV_ATTN_RES_BLOCK_SIZE, hparams.attn_res_block_size); - ml.get_key(LLM_KV_SHORTCONV_L_CACHE, hparams.n_shortconv_l_cache); - ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab_padded); + + // the embedding and output tensors are padded past the vocabulary + ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab_padded); ml.get_key(LLM_KV_VOCAB_SIZE_UNPADDED, hparams.n_vocab_unpadded); - ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta); + + // MoE + ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); + + ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta); ml.get_key(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, hparams.situ_linear_beta); - ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); - ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping); - ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale, false); + + hparams.f_final_logit_softcapping = 0.0f; + ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false); + + // sliding window + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + uint32_t n_pattern = 0; ml.get_arr_n(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, n_pattern); + if (n_pattern != hparams.n_layer() || !hparams.n_relative || !hparams.n_relative_extent || !hparams.n_swa || !hparams.attn_res_block_size || !hparams.n_log_scale_floor || hparams.n_shortconv_l_cache < 2 || hparams.n_shortconv_l_cache > 64 || hparams.n_relative_extent > INT32_MAX || hparams.n_swa > INT32_MAX || !hparams.n_vocab_unpadded || hparams.n_vocab_unpadded > hparams.n_vocab_padded) { throw std::runtime_error("inkling2: invalid dimensions, vocabulary, or layer pattern"); } - for (float value : {hparams.f_norm_rms_eps, hparams.f_qk_clip, hparams.f_relative_clip, hparams.situ_beta, - hparams.situ_linear_beta, hparams.expert_weights_scale, hparams.f_final_logit_softcapping}) { + + for (float value : {hparams.f_norm_rms_eps, hparams.f_qk_clip, hparams.f_relative_clip, hparams.situ_beta, hparams.situ_linear_beta}) { if (!std::isfinite(value) || value <= 0.0f) { throw std::runtime_error("inkling2: normalization, clipping and scaling parameters must be finite and positive"); } } + if (!std::isfinite(hparams.f_log_scale_alpha) || hparams.f_log_scale_alpha < 0.0f) { throw std::runtime_error("inkling2: invalid logarithmic scale"); } - hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; - hparams.expert_router_f32 = true; + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + hparams.expert_router_f32 = true; hparams.expert_weights_norm_eps = 1e-20f; + + // no RoPE, the relative-position bias carries the positions hparams.rope_pattern.fill(false); - uint64_t max_channels = 0; + + // the convolution state keeps K, V, the attention output and the FFN output of the widest layer + uint64_t n_channels_max = 0; + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { if (!hparams.n_head_kv(il) || hparams.n_head(il) % hparams.n_head_kv(il) || hparams.n_embd_head_k(il) != hparams.n_embd_head_v(il) || !hparams.n_expert_used(il) || hparams.n_expert_used(il) > hparams.n_expert || !hparams.n_ff_exp(il)) { throw std::runtime_error("inkling2: invalid attention or expert dimensions"); } - max_channels = std::max(max_channels, 2ull * hparams.n_embd_k_gqa(il) + 2ull * hparams.n_embd); + + n_channels_max = std::max(n_channels_max, 2ull * hparams.n_embd_k_gqa(il) + 2ull * hparams.n_embd); } - if (max_channels * (hparams.n_shortconv_l_cache - 1) > UINT32_MAX) { + + if (n_channels_max * (hparams.n_shortconv_l_cache - 1) > UINT32_MAX) { throw std::runtime_error("inkling2: convolution state is too large"); } - hparams.n_sconv_channels = max_channels; + + hparams.n_sconv_channels = n_channels_max; + type = LLM_TYPE_UNKNOWN; } void llama_model_inkling2::load_arch_tensors(llama_model_loader &) { LLAMA_LOAD_LOCALS; + if (hparams.n_vocab_unpadded != vocab.n_tokens()) { throw std::runtime_error("inkling2: tokenizer size must equal the unpadded vocabulary size"); } - tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, hparams.n_vocab_padded}, 0); + + const int64_t n_vocab_padded = hparams.n_vocab_padded; + const int64_t n_rel = hparams.n_relative; + const int64_t n_conv = hparams.n_shortconv_l_cache; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab_padded}, 0); tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight", 0), {n_embd}, 0); - output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, hparams.n_vocab_padded}, 0); - output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + + // output + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab_padded}, 0); + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); output_res_query = create_tensor(tn(LLM_TENSOR_OUTPUT_RES_QUERY, "weight"), {n_embd}, 0); + for (int i = 0; i < n_layer; ++i) { - auto & l = layers[i]; - const int64_t nh = hparams.n_head(i); - const int64_t nk = hparams.n_head_kv(i); - const int64_t hd = hparams.n_embd_head_k(i); - const int64_t nr = hparams.n_relative; - const int64_t kernel = hparams.n_shortconv_l_cache; - const int64_t extent = hparams.is_swa(i) ? hparams.n_swa : hparams.n_relative_extent; - l.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, nh*hd}, 0); - l.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, nk*hd}, 0); - l.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, nk*hd}, 0); - l.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {nh*hd, n_embd}, 0); - l.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, nh*hd}, 0); - l.attn_rel = create_tensor(tn(LLM_TENSOR_ATTN_REL, "weight", i), {n_embd, nh*nr}, 0); - l.attn_rel_bias = create_tensor(tn(LLM_TENSOR_ATTN_REL_BIAS, "weight", i), {nr, extent}, 0); - l.attn_q_clip = create_tensor(tn(LLM_TENSOR_ATTN_Q_CLIP, "weight", i), {hd, nh}, 0); - l.attn_rel_clip = create_tensor(tn(LLM_TENSOR_ATTN_REL_CLIP, "weight", i), {nr, nh}, 0); - l.attn_sink_proj = create_tensor(tn(LLM_TENSOR_ATTN_SINK_PROJ, "weight", i), {n_embd, nh}, 0); - l.attn_k_conv = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV, "weight", i), {kernel, nk*hd}, 0); - l.attn_v_conv = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV, "weight", i), {kernel, nk*hd}, 0); - l.attn_post_conv = create_tensor(tn(LLM_TENSOR_ATTN_POST_CONV, "weight", i), {kernel, n_embd}, 0); - l.ffn_post_conv = create_tensor(tn(LLM_TENSOR_FFN_POST_CONV, "weight", i), {kernel, n_embd}, 0); + auto & layer = layers[i]; + + const int64_t n_head = hparams.n_head(i); + const int64_t n_head_kv = hparams.n_head_kv(i); + const int64_t n_embd_head = hparams.n_embd_head_k(i); + const int64_t n_ff_exp = hparams.n_ff_exp(i); + const int64_t n_extent = hparams.is_swa(i) ? hparams.n_swa : hparams.n_relative_extent; + + // attention + layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head*n_head}, 0); + layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_head*n_head_kv}, 0); + layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_head*n_head_kv}, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head*n_head, n_embd}, 0); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_embd_head*n_head}, 0); + + layer.attn_q_clip = create_tensor(tn(LLM_TENSOR_ATTN_Q_CLIP, "weight", i), {n_embd_head, n_head}, 0); + layer.attn_sink_proj = create_tensor(tn(LLM_TENSOR_ATTN_SINK_PROJ, "weight", i), {n_embd, n_head}, 0); + + // relative-position bias + layer.attn_rel = create_tensor(tn(LLM_TENSOR_ATTN_REL, "weight", i), {n_embd, n_rel*n_head}, 0); + layer.attn_rel_bias = create_tensor(tn(LLM_TENSOR_ATTN_REL_BIAS, "weight", i), {n_rel, n_extent}, 0); + layer.attn_rel_clip = create_tensor(tn(LLM_TENSOR_ATTN_REL_CLIP, "weight", i), {n_rel, n_head}, 0); + + // short convolutions + layer.attn_k_conv = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV, "weight", i), {n_conv, n_embd_head*n_head_kv}, 0); + layer.attn_v_conv = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV, "weight", i), {n_conv, n_embd_head*n_head_kv}, 0); + layer.attn_post_conv = create_tensor(tn(LLM_TENSOR_ATTN_POST_CONV, "weight", i), {n_conv, n_embd}, 0); + layer.ffn_post_conv = create_tensor(tn(LLM_TENSOR_FFN_POST_CONV, "weight", i), {n_conv, n_embd}, 0); + if (hparams.is_swa(i)) { - l.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); } else { - l.attn_q_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_k_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_v_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_V_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_k_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV_PROJ, "weight", i), {n_embd, kernel*nk}, 0); - l.attn_v_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV_PROJ, "weight", i), {n_embd, kernel*nk}, 0); + // full-attention layers: separate Q, K and V input norms, and input-dependent taps for the K and V convolutions + layer.attn_q_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_k_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_v_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_V_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_k_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV_PROJ, "weight", i), {n_embd, n_conv*n_head_kv}, 0); + layer.attn_v_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV_PROJ, "weight", i), {n_embd, n_conv*n_head_kv}, 0); } + + // block attention residuals if (i > 0) { - l.attn_res_query = create_tensor(tn(LLM_TENSOR_ATTN_RES_QUERY, "weight", i), {n_embd, hparams.is_swa(i) ? 1 : 3}, 0); + layer.attn_res_query = create_tensor(tn(LLM_TENSOR_ATTN_RES_QUERY, "weight", i), {n_embd, hparams.is_swa(i) ? 1 : 3}, 0); } - l.ffn_res_query = create_tensor(tn(LLM_TENSOR_FFN_RES_QUERY, "weight", i), {n_embd}, 0); - l.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); - l.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); - l.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); - l.ffn_gate_up_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "weight", i), {n_embd, 2*hparams.n_ff_exp(i), n_expert}, 0); - l.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {hparams.n_ff_exp(i), n_embd, n_expert}, 0); + layer.ffn_res_query = create_tensor(tn(LLM_TENSOR_FFN_RES_QUERY, "weight", i), {n_embd}, 0); + + // MoE + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); + layer.ffn_gate_up_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "weight", i), {n_embd, 2*n_ff_exp, n_expert}, 0); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0); } } @@ -114,202 +160,250 @@ std::unique_ptr llama_model_inkling2::build_arch_graph(const return std::make_unique(params); } -class llm_graph_input_inkling2_pos : public llm_graph_input_i { -public: - const llama_kv_cache_context * cache[2]; - ggml_tensor * distance[2]; - uint32_t extent[2]; - - bool can_reuse(const llm_graph_params & params) override { - const auto * memory = static_cast(params.mctx); - cache[0] = memory->get_attn()->get_base(); - cache[1] = memory->get_attn()->get_swa(); - for (int i = 0; i < 2; ++i) { - if (distance[i]->ne[0] != cache[i]->get_n_kv() || distance[i]->ne[1] != params.ubatch.n_tokens) { - return false; - } - } - return true; - } - - void set_input(const llama_ubatch * ubatch) override { - for (int i = 0; i < 2; ++i) { - if (distance[i]->buffer) { - cache[i]->set_input_relative_pos(distance[i], ubatch, extent[i]); - } - } - } -}; - +// scale each row down to an L2 norm of at most threshold, after the optional per-channel scale ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * scale, float threshold) { if (scale) { cur = ggml_mul(ctx0, cur, scale); } - auto * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); + + ggml_tensor * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); norm = ggml_scale_bias(ctx0, norm, 1.0f, 1e-6f); - auto * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); + + ggml_tensor * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); + return ggml_mul(ctx0, cur, ggml_clamp(ctx0, factor, 0.0f, 1.0f)); } +// attention over the depth: mix the earlier block outputs and cur with learned queries ggml_tensor * llama_model_inkling2::graph::mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query) { - auto * states = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); - for (auto * block : blocks) { + ggml_tensor * states = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); + for (ggml_tensor * block : blocks) { states = ggml_concat(ctx0, ggml_reshape_3d(ctx0, block, n_embd, 1, n_tokens), states, 1); } states = ggml_rms_norm(ctx0, states, 1e-6f); - auto * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); - auto * scores = ggml_mul_mat(ctx0, states, queries); + + ggml_tensor * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); + + ggml_tensor * scores = ggml_mul_mat(ctx0, states, queries); scores = ggml_soft_max_ext(ctx0, scores, nullptr, 1.0f/sqrtf(n_embd), 0.0f); + return ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, states)), scores); } -ggml_tensor * llama_model_inkling2::graph::convolve(ggml_tensor * cur, ggml_tensor * weight, ggml_tensor * dynamic, - ggml_tensor * state, ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset) { - const int64_t kernel = hparams.n_shortconv_l_cache; - const int64_t channels = cur->ne[0]; - const int64_t nt = ubatch.n_seq_tokens; - const int64_t ns = ubatch.n_seqs; - auto * past = ggml_view_3d(ctx0, history, kernel - 1, channels, ns, history->nb[1], history->nb[2], offset*history->nb[1]); - auto * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, channels, nt, ns)); +// causal short convolution with a residual; dynamic adds input-dependent taps per head +// the last n_conv - 1 inputs of each sequence live in the recurrent state at channel offset `offset` +ggml_tensor * llama_model_inkling2::graph::convolve( + ggml_tensor * cur, + ggml_tensor * weight, + ggml_tensor * dynamic, + ggml_tensor * state, + ggml_tensor * history, + llm_graph_input_rs * inp, + int64_t offset) { + const int64_t n_conv = hparams.n_shortconv_l_cache; + const int64_t n_channels = cur->ne[0]; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + const int64_t n_seqs = ubatch.n_seqs; + + ggml_tensor * past = ggml_view_3d(ctx0, history, n_conv - 1, n_channels, n_seqs, history->nb[1], history->nb[2], offset*history->nb[1]); + + ggml_tensor * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, n_channels, n_seq_tokens, n_seqs)); x = ggml_concat(ctx0, past, x, 0); - build_conv_state_store(inp, state, x, kernel - 1, offset*(kernel - 1)*ggml_element_size(state)); - auto * out = ggml_ssm_conv(ctx0, x, weight); - out = ggml_reshape_2d(ctx0, out, channels, n_tokens); + + build_conv_state_store(inp, state, x, n_conv - 1, offset*(n_conv - 1)*ggml_element_size(state)); + + ggml_tensor * out = ggml_ssm_conv(ctx0, x, weight); + out = ggml_reshape_2d(ctx0, out, n_channels, n_tokens); + if (dynamic) { - const int64_t heads = dynamic->ne[0]/kernel; - dynamic = ggml_reshape_3d(ctx0, dynamic, kernel, heads, n_tokens); - for (int64_t lag = 0; lag < kernel; ++lag) { - auto * tap = ggml_view_3d(ctx0, dynamic, 1, heads, n_tokens, dynamic->nb[1], dynamic->nb[2], lag*dynamic->nb[0]); - auto * window = ggml_view_3d(ctx0, x, nt, channels, ns, x->nb[1], x->nb[2], (kernel - 1 - lag)*x->nb[0]); + const int64_t n_heads = dynamic->ne[0]/n_conv; + + dynamic = ggml_reshape_3d(ctx0, dynamic, n_conv, n_heads, n_tokens); + + for (int64_t lag = 0; lag < n_conv; ++lag) { + ggml_tensor * tap = ggml_view_3d(ctx0, dynamic, 1, n_heads, n_tokens, dynamic->nb[1], dynamic->nb[2], lag*dynamic->nb[0]); + ggml_tensor * window = ggml_view_3d(ctx0, x, n_seq_tokens, n_channels, n_seqs, x->nb[1], x->nb[2], (n_conv - 1 - lag)*x->nb[0]); + window = ggml_cont(ctx0, ggml_transpose(ctx0, window)); - window = ggml_reshape_3d(ctx0, window, channels/heads, heads, n_tokens); - auto * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), channels, n_tokens); + window = ggml_reshape_3d(ctx0, window, n_channels/n_heads, n_heads, n_tokens); + + ggml_tensor * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), n_channels, n_tokens); + out = ggml_add(ctx0, out, term); } } - return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*kernel + 1)); + + return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1)); } llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { - auto * inp = build_inp_mem_hybrid_iswa(); + auto * inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); auto * attn = inp->get_attn(); auto * recr = inp->get_recr(); - auto * positions = build_inp_pos(); - auto * out_ids = build_inp_out_ids(); - auto rel = std::make_unique(); - rel->cache[0] = attn->mctx->get_base(); - rel->cache[1] = attn->mctx->get_swa(); - rel->extent[0] = hparams.n_relative_extent; - rel->extent[1] = hparams.n_swa; - ggml_tensor * distances[2]; - for (int i = 0; i < 2; ++i) { - distances[i] = rel->distance[i] = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, rel->cache[i]->get_n_kv(), n_tokens); - ggml_set_input(distances[i]); - } - res->add_input(std::move(rel)); - auto * tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, positions, GGML_TYPE_F32), 1.0f, 1.0f); + + ggml_tensor * inp_pos = build_inp_pos(); + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + // log-scaled positions: 1 + alpha*log(max(1, (pos + 1)/floor)), multiplies q and r of the full-attention layers + ggml_tensor * tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, inp_pos, GGML_TYPE_F32), 1.0f, 1.0f); tau = ggml_log(ctx0, ggml_clamp(ctx0, ggml_scale(ctx0, tau, 1.0f/hparams.n_log_scale_floor), 1.0f, INFINITY)); tau = ggml_reshape_3d(ctx0, ggml_scale_bias(ctx0, tau, hparams.f_log_scale_alpha, 1.0f), 1, 1, n_tokens); - auto * cur = build_inp_embd(model.tok_embd); + + ggml_tensor * cur = build_inp_embd(model.tok_embd); + // important: do not normalize raw embeddings input (i.e. encoded image embeddings) if (ubatch.token) { cur = build_norm(cur, model.tok_norm, nullptr, LLM_NORM_RMS, -1); } + std::vector blocks; + for (int il = 0; il < n_layer; ++il) { - const auto & l = model.layers[il]; - const bool swa = hparams.is_swa(il); - const int64_t nh = hparams.n_head(il); - const int64_t nk = hparams.n_head_kv(il); - const int64_t hd = hparams.n_embd_head_k(il); - const int64_t kv = nk*hd; - auto * state = recr->mctx->get_r_l(il); - auto * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); + const auto & layer = model.layers[il]; + + const bool is_swa = hparams.is_swa(il); + const int64_t n_head = hparams.n_head(il); + const int64_t n_head_kv = hparams.n_head_kv(il); + const int64_t n_embd_head = hparams.n_embd_head_k(il); + const int64_t n_embd_k_gqa = n_embd_head*n_head_kv; + + ggml_tensor * state = recr->mctx->get_r_l(il); + ggml_tensor * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); - auto * residual = cur; + + ggml_tensor * inpSA = cur; + + // attention inputs: SWA layers mix one, full-attention layers one each for Q, K and V ggml_tensor * inputs[3] = {cur, cur, cur}; - if (l.attn_res_query) { - auto * mixed = mix(blocks, cur, l.attn_res_query); + if (layer.attn_res_query) { + ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); for (int j = 0; j < 3; ++j) { - inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (swa ? 0 : j)*mixed->nb[1])); + inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (is_swa ? 0 : j)*mixed->nb[1])); } } - if (swa) { - inputs[0] = build_norm(inputs[0], l.attn_norm, nullptr, LLM_NORM_RMS, il); + + if (is_swa) { + inputs[0] = build_norm(inputs[0], layer.attn_norm, nullptr, LLM_NORM_RMS, il); inputs[1] = inputs[2] = inputs[0]; } else { - inputs[0] = build_norm(inputs[0], l.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = build_norm(inputs[1], l.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[2] = build_norm(inputs[2], l.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); - } - auto * q = build_lora_mm(l.wq, inputs[0]); - auto * k = convolve(build_lora_mm(l.wk, inputs[1]), l.attn_k_conv, - swa ? nullptr : build_lora_mm(l.attn_k_conv_proj, inputs[1]), state, history, recr, 0); - auto * v = convolve(build_lora_mm(l.wv, inputs[2]), l.attn_v_conv, - swa ? nullptr : build_lora_mm(l.attn_v_conv_proj, inputs[2]), state, history, recr, kv); - auto * r = build_lora_mm(l.attn_rel, inputs[0]); - q = clip(ggml_reshape_3d(ctx0, q, hd, nh, n_tokens), l.attn_q_clip, hparams.f_qk_clip); - k = clip(ggml_reshape_3d(ctx0, k, hd, nk, n_tokens), nullptr, hparams.f_qk_clip); - v = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, v, hd, nk, n_tokens), hparams.f_norm_rms_eps); - r = clip(ggml_reshape_3d(ctx0, r, hparams.n_relative, nh, n_tokens), l.attn_rel_clip, hparams.f_relative_clip); - if (!swa) { - q = ggml_mul(ctx0, q, tau); - r = ggml_mul(ctx0, r, tau); - } - auto * mask = swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; - const int64_t streams = mask->ne[3]; - const int64_t n_kv = distances[swa]->ne[0]; - auto * sinks = build_lora_mm(l.attn_sink_proj, inputs[0]); - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x nh - auto * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, l.attn_rel_bias, 0, 1, 0, 0), r); - if (cparams.flash_attn) { - // exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))). - table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, nh, n_tokens)); - } else { - // build_attn scales the bias along with QK; FA adds the mask after scaling QK. - table = ggml_scale(ctx0, table, sqrtf(hd)); + inputs[0] = build_norm(inputs[0], layer.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = build_norm(inputs[1], layer.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[2] = build_norm(inputs[2], layer.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); } - table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - auto * bias = ggml_get_rows(ctx0, table, distances[swa]); - bias = ggml_cont(ctx0, ggml_permute(ctx0, ggml_reshape_4d(ctx0, bias, nh, n_kv, n_tokens/streams, streams), 2, 0, 1, 3)); - ggml_tensor * fa_mask = nullptr; - if (cparams.flash_attn) { - fa_mask = ggml_cast(ctx0, ggml_add(ctx0, bias, ggml_cast(ctx0, mask, GGML_TYPE_F32)), GGML_TYPE_F16); - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, nh), 0.0f); - bias = nullptr; - } else { - sinks = ggml_reshape_4d(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, - ggml_reshape_3d(ctx0, sinks, nh, n_tokens/streams, streams), 1, 0, 2, 3)), 1, n_tokens/streams, nh, streams); + + // self-attention + { + ggml_tensor * Qcur = build_lora_mm(layer.wq, inputs[0]); + ggml_tensor * Kcur = convolve(build_lora_mm(layer.wk, inputs[1]), layer.attn_k_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]), state, history, recr, 0); + ggml_tensor * Vcur = convolve(build_lora_mm(layer.wv, inputs[2]), layer.attn_v_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]), state, history, recr, n_embd_k_gqa); + ggml_tensor * Rcur = build_lora_mm(layer.attn_rel, inputs[0]); + + Qcur = clip(ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), layer.attn_q_clip, hparams.f_qk_clip); + Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip); + Vcur = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens), hparams.f_norm_rms_eps); + Rcur = clip(ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens), layer.attn_rel_clip, hparams.f_relative_clip); + + if (!is_swa) { + Qcur = ggml_mul(ctx0, Qcur, tau); + Rcur = ggml_mul(ctx0, Rcur, tau); + } + + cb(Qcur, "Qcur", il); + cb(Kcur, "Kcur", il); + cb(Vcur, "Vcur", il); + cb(Rcur, "Rcur", il); + + ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; + + const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; + const int64_t n_kv = rel_pos->ne[0]; + + ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + + // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head + ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); + + // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink + table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); + table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); + + ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + cb(kq_b, "kq_b", il); + + sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + + cur = build_attn(inp, + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + + cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); + cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); + cb(cur, "attn_out", il); } - cur = build_attn(attn, nullptr, nullptr, nullptr, q, k, v, bias, sinks, nullptr, 1.0f/sqrtf(hd), il, fa_mask); - cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(l.wqkv_gate, inputs[0]))); - cur = convolve(build_lora_mm(l.wo, cur), l.attn_post_conv, nullptr, state, history, recr, 2*kv); + + // the first layer of each block starts a new residual stream, the earlier one joins the mixed blocks if (il % hparams.attn_res_block_size == 0) { - blocks.push_back(residual); + blocks.push_back(inpSA); } else { - cur = ggml_add(ctx0, residual, cur); + cur = ggml_add(ctx0, inpSA, cur); } - residual = cur; - cur = ggml_reshape_2d(ctx0, mix(blocks, cur, l.ffn_res_query), n_embd, n_tokens); - cur = build_norm(cur, l.ffn_norm, nullptr, LLM_NORM_RMS, il); - cur = build_moe_ffn(cur, l.ffn_gate_inp, nullptr, nullptr, l.ffn_down_exps, l.ffn_exp_probs_b, - hparams.n_expert, hparams.n_expert_used(il), LLM_FFN_SITU, true, hparams.expert_weights_scale, - LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, nullptr, l.ffn_gate_up_exps); - cur = convolve(cur, l.ffn_post_conv, nullptr, state, history, recr, 2*kv + n_embd); - cur = ggml_add(ctx0, residual, cur); + + ggml_tensor * ffn_inp = cur; + cb(ffn_inp, "ffn_inp", il); + + // MoE + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + + cur = build_moe_ffn(cur, + layer.ffn_gate_inp, + nullptr, + nullptr, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + hparams.n_expert, + hparams.n_expert_used(il), + LLM_FFN_SITU, true, + hparams.expert_weights_scale, + LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, + il, + nullptr, + layer.ffn_gate_up_exps); + + cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); + cb(cur, "ffn_out", il); + + cur = ggml_add(ctx0, ffn_inp, cur); cb(cur, "l_out", il); } + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, model.output_res_query), n_embd, n_tokens); cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); - if (out_ids) { - cur = ggml_get_rows(ctx0, cur, out_ids); + + if (inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); } + + cb(cur, "result_norm", -1); res->t_embd = cur; + + // lm_head cur = build_lora_mm(model.output, cur); ggml_prec_set_acc(cur, GGML_PREC_F32); - const float cap = hparams.f_final_logit_softcapping; - cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + + if (hparams.f_final_logit_softcapping != 0.0f) { + const float cap = hparams.f_final_logit_softcapping; + + cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + } + + // drop the padded vocabulary cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, hparams.n_vocab_unpadded, cur->ne[1], cur->nb[1], 0)); - res->t_logits = cur; + cb(cur, "result_output", -1); + res->t_logits = cur; } diff --git a/src/models/models.h b/src/models/models.h index 8d74c5018920..e7849e07d3d9 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2480,7 +2480,14 @@ struct llama_model_inkling2 : public llama_model_base { graph(const llm_graph_params & params); ggml_tensor * mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query); ggml_tensor * clip(ggml_tensor * cur, ggml_tensor * scale, float threshold); - ggml_tensor * convolve(ggml_tensor * cur, ggml_tensor * weight, ggml_tensor * dynamic, ggml_tensor * state, ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset); + ggml_tensor * convolve( + ggml_tensor * cur, + ggml_tensor * weight, + ggml_tensor * dynamic, + ggml_tensor * state, + ggml_tensor * history, + llm_graph_input_rs * inp, + int64_t offset); }; std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; From ac830a9cbbfad748384a2e2268395b26e7d74e12 Mon Sep 17 00:00:00 2001 From: Andreas Kieslinger <47689530+aendk@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:40:13 +0100 Subject: [PATCH 02/88] ggml : add backend scheduler tests (#27258) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Adds initial scheduler stress tests * Adds new sleep op to simplify scheduler testing * Adds testcase addressing https://github.com/ggml-org/llama.cpp/issues/23321 * Adds experimental vulkan GGML_OP_SLEEP * Improves structure and naming of previous tests. Adds new tests, including one which detects the nkvo-bug correctly, and validates the proposed hotfix. * Cleanup: Removes CUDA specific comments and nvtx-markers * Fix: forgot to add sleep specific test case * Fix oversights identified by CI * Drops default prints so that it behaves like other ctests. Adds -v flag to toggle this behavior * Fix: Early exit in CPU-only settings (cause for graviton CI fails) * Improves stress_test_linked_list by removing overlap with test_chain_all_backends and test_pair_user_inputs. The latter ones test either activations or user inputs in isolation and just once, whereas the stress test tests all combinations multiple rounds * Exclude ACCEL devices from new tests due to incompatibility * Fixes vulkan test failure in llvmpipe * Adds asserts, improves comments and some checks * Fixes nitpicks in white-space and variable naming * Adds comments that certain vk drivers could time OP_SLEEP incorrectly * Drops limitiation to CPU/GPU in test-sleep * Aligns OP_SLEEP guards in cuda with vk guards (input shape and contiguity) * Implements feedback for OP_SLEEP to work in place (no copy) * Apply non-code suggestions from JohannesGaesslers code review Co-authored-by: Johannes Gäßler * Removes struct backend_supports; enables tests to return skip, instead of only pass/fail * Make clang-tidy happy * Removes sched_backend_caps, improves create_test_scheduler according to feedback (L149) * Removes "name" field from struct sched_check in favor of ggml_set_name/ggml_get_name * Drops unnecessary shader_clock.comp test and guards * Replaces sched_ prefixes with helper_ prefix * Moves test suite to new RAII types for better memory management * Adds sleep option to test_chain_all_backends * Adds sleep option to first-run arm of the y-shaped test * Fix switchcase order for legibility in stress_test_dag * Simplfies stress_test_linked_list via double for-loop * Adds pseudo-random input to stress_test_linked_list, and runs all transitions both with and without CPU input (next to activation copy as input) * Fix RPC Proto patch due to GGML_OPS bump * Adds ggml-cpp.h treatment to test-sleep.cpp * Adds TODO pointers for subsequent additional tests. * Apply suggestion to ggml.h Co-authored-by: Johannes Gäßler * Apply suggestion to tests/test-backend-sched.cpp Co-authored-by: Johannes Gäßler * Apply suggestion to tests/test-backend-sched.cpp Co-authored-by: Johannes Gäßler * Fixes node compatibility check to not take buffer locations into account. This led to skipped tests due to incorrectly rejected ops due to wrong buffer locations in multi-GPU (which is one of the scheduler behaviors under test) * Apply batched suggestions from gg code review Co-authored-by: Georgi Gerganov * Completes callsite change of gg-suggestion * Switch test-sleep from std::chrono::steady_clock::now() to ggml_time_us to avoid mac clock drift and spurious test failures. This makes the test a bit nonsensical on CPU (same clock checks itself), but the test still has merit on the other backends where independent device clocks are used. --------- Co-authored-by: Johannes Gäßler Co-authored-by: Georgi Gerganov --- ggml/include/ggml-rpc.h | 4 +- ggml/include/ggml.h | 8 + ggml/src/ggml-cpu/ggml-cpu.c | 5 + ggml/src/ggml-cpu/ops.cpp | 13 + ggml/src/ggml-cpu/ops.h | 1 + ggml/src/ggml-cuda/ggml-cuda.cu | 10 + ggml/src/ggml-cuda/sleep.cu | 32 + ggml/src/ggml-cuda/sleep.cuh | 3 + ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp | 2 + .../ggml-vulkan/ggml-vulkan-push-constants.h | 4 + ggml/src/ggml-vulkan/ggml-vulkan-types.h | 3 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 50 + .../src/ggml-vulkan/vulkan-shaders/sleep.comp | 37 + .../vulkan-shaders/vulkan-shaders-gen.cpp | 1 + ggml/src/ggml.c | 29 +- tests/CMakeLists.txt | 2 + tests/test-backend-ops.cpp | 31 + tests/test-backend-sched.cpp | 1084 +++++++++++++++++ tests/test-sleep.cpp | 154 +++ 19 files changed, 1469 insertions(+), 4 deletions(-) create mode 100644 ggml/src/ggml-cuda/sleep.cu create mode 100644 ggml/src/ggml-cuda/sleep.cuh create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp create mode 100644 tests/test-backend-sched.cpp create mode 100644 tests/test-sleep.cpp diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index da1d4e1f167b..168ee774e488 100644 --- a/ggml/include/ggml-rpc.h +++ b/ggml/include/ggml-rpc.h @@ -8,10 +8,10 @@ extern "C" { #define RPC_PROTO_MAJOR_VERSION 10 #define RPC_PROTO_MINOR_VERSION 0 -#define RPC_PROTO_PATCH_VERSION 0 +#define RPC_PROTO_PATCH_VERSION 1 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); #endif #define GGML_RPC_MAX_SERVERS 16 diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 2341fa6c107e..284825ca6caf 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -429,6 +429,8 @@ extern "C" { GGML_OP_GLU, + GGML_OP_SLEEP, + GGML_OP_COUNT, }; @@ -2599,6 +2601,12 @@ extern "C" { int n_tasks, void * userdata); + // Busy-wait operator for scheduling and backend testing. + GGML_API struct ggml_tensor * ggml_sleep( + struct ggml_context * ctx, + struct ggml_tensor * a, // wait after this tensor has executed, return value is simply a full view of this tensor + int32_t us); // amount of time to wait in microseconds + // loss function GGML_API struct ggml_tensor * ggml_cross_entropy_loss( diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 30edcdbac0c8..8b4c7a4ef06c 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -2034,6 +2034,10 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_fill(params, tensor); } break; + case GGML_OP_SLEEP: + { + ggml_compute_forward_sleep(params, tensor); + } break; case GGML_OP_FLASH_ATTN_EXT: { ggml_compute_forward_flash_attn_ext(params, tensor); @@ -2306,6 +2310,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_OP_REPEAT: case GGML_OP_REPEAT_BACK: case GGML_OP_LEAKY_RELU: + case GGML_OP_SLEEP: { n_tasks = 1; } break; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 72efbc6e9fa9..0b540c5a7cff 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -2238,6 +2238,19 @@ void ggml_compute_forward_fill(const ggml_compute_params * params, ggml_tensor * } } +// ggml_compute_forward_sleep + +void ggml_compute_forward_sleep(const ggml_compute_params * params, ggml_tensor * dst) { + if (params->ith != 0) { + return; + } + + // same clock as ggml_time_us() callers; on macOS steady_clock is CLOCK_MONOTONIC_RAW, which can run faster + const int64_t t_end = ggml_time_us() + ggml_get_op_params_i32(dst, 0); + + while (ggml_time_us() < t_end) {} +} + // ggml_compute_tri template diff --git a/ggml/src/ggml-cpu/ops.h b/ggml/src/ggml-cpu/ops.h index aac527a64c54..3a4fa0707e49 100644 --- a/ggml/src/ggml-cpu/ops.h +++ b/ggml/src/ggml-cpu/ops.h @@ -84,6 +84,7 @@ void ggml_compute_forward_top_k(const struct ggml_compute_params * params, struc void ggml_compute_forward_leaky_relu(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_tri(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_fill(const struct ggml_compute_params * params, struct ggml_tensor * dst); +void ggml_compute_forward_sleep(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_flash_attn_ext(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_flash_attn_back( const struct ggml_compute_params * params, diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 40e83750efba..c6622d1b38bb 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -48,6 +48,7 @@ #include "ggml-cuda/rope.cuh" #include "ggml-cuda/roll.cuh" #include "ggml-cuda/scale.cuh" +#include "ggml-cuda/sleep.cuh" #include "ggml-cuda/snake.cuh" #include "ggml-cuda/softcap.cuh" #include "ggml-cuda/softmax.cuh" @@ -3145,6 +3146,9 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg case GGML_OP_FILL: ggml_cuda_op_fill(ctx, dst); break; + case GGML_OP_SLEEP: + ggml_cuda_op_sleep(ctx, dst); + break; case GGML_OP_LIGHTNING_INDEXER: ggml_cuda_lightning_indexer(ctx, dst); break; @@ -6809,6 +6813,12 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g return ggml_cuda_lightning_indexer_supported(dev_ctx->device, op); case GGML_OP_TOP_K_MASK: return op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32; + case GGML_OP_SLEEP: +#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) + return false; +#else + return true; +#endif // defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) default: return false; diff --git a/ggml/src/ggml-cuda/sleep.cu b/ggml/src/ggml-cuda/sleep.cu new file mode 100644 index 000000000000..e6a40e5f213a --- /dev/null +++ b/ggml/src/ggml-cuda/sleep.cu @@ -0,0 +1,32 @@ +#include "sleep.cuh" + +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + +// %globaltimer is a nanosecond wall clock, unlike clock64() it is unaffected by the SM clock and by frequency scaling +static __device__ __forceinline__ uint64_t globaltimer_ns() { + uint64_t t; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); + return t; +} + +// a single thread is enough, the next kernel on the same stream cannot start before this one retires +static __global__ void sleep_ns(const uint64_t ns) { + const uint64_t t0 = globaltimer_ns(); + + while (globaltimer_ns() - t0 < ns) {} +} + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + sleep_ns<<<1, 1, 0, ctx.stream()>>>(1000*(uint64_t) ggml_get_op_params_i32(dst, 0)); + CUDA_CHECK(cudaGetLastError()); +} + +#else + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + GGML_UNUSED(ctx); + GGML_UNUSED(dst); + GGML_ABORT("GGML_OP_SLEEP requires the %%globaltimer register, which is only available on CUDA"); +} + +#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) diff --git a/ggml/src/ggml-cuda/sleep.cuh b/ggml/src/ggml-cuda/sleep.cuh new file mode 100644 index 000000000000..d62c3178565c --- /dev/null +++ b/ggml/src/ggml-cuda/sleep.cuh @@ -0,0 +1,3 @@ +#include "common.cuh" + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp index 56fa6ada34ae..79258b871145 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp @@ -1043,6 +1043,8 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } else if (tensor->op == GGML_OP_FILL) { const float value = ggml_get_op_params_f32(tensor, 0); tensor_clone = ggml_fill(ggml_ctx, src_clone[0], value); + } else if (tensor->op == GGML_OP_SLEEP) { + tensor_clone = ggml_sleep(ggml_ctx, src_clone[0], ggml_get_op_params_i32(tensor, 0)); } else if (tensor->op == GGML_OP_SQR) { tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]); } else if (tensor->op == GGML_OP_SQRT) { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 176dbb72ad21..859cca181cd2 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -189,6 +189,10 @@ struct vk_op_push_constants { float param4; }; +struct vk_op_sleep_push_constants { + uint32_t ticks; +}; + struct vk_op_fwht_push_constants { uint32_t n_rows; uint32_t src_offset; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 6cc76b32307c..b4fec2da44a9 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -739,6 +739,7 @@ struct vk_device_struct { bool shader_int64; bool buffer_device_address; bool vulkan_memory_model; + bool shader_clock; bool add_rms_fusion; uint32_t partials_binding_alignment; @@ -923,6 +924,8 @@ struct vk_device_struct { vk_pipeline pipeline_fill_f32; vk_pipeline pipeline_fill_f16; + vk_pipeline pipeline_sleep; + // [src/dst 0=fp32,1=fp16,2=bf16] vk_pipeline pipeline_glu[GGML_GLU_OP_COUNT][3]; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 3674579cc4ed..6955bb406be0 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -3892,6 +3892,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_fill_f16, "fill_f16", fill_f16_len, fill_f16_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); + if (device->shader_clock) { + ggml_vk_create_pipeline(device, device->pipeline_sleep, "sleep", sleep_len, sleep_data, "main", 1, sizeof(vk_op_sleep_push_constants), {1, 1, 1}, {}, 1); + } + #define CREATE_GLU(name, op) \ ggml_vk_create_pipeline(device, device->pipeline_glu[GGML_GLU_OP_ ## op][0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \ ggml_vk_create_pipeline(device, device->pipeline_glu[GGML_GLU_OP_ ## op][1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \ @@ -4521,6 +4525,7 @@ vk_device ggml_vk_get_device(size_t idx) { bool ocp_microscaling_extension = false; bool shader_float8_extension = false; bool workgroup_memory_explicit_layout_support = false; + bool shader_clock_support = false; for (const auto& properties : ext_props) { if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) { @@ -4571,6 +4576,9 @@ vk_device ggml_vk_get_device(size_t idx) { } else if (strcmp(VK_EXT_SHADER_FLOAT8_EXTENSION_NAME, properties.extensionName) == 0) { shader_float8_extension = true; #endif + } else if (strcmp("VK_KHR_shader_clock", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_SHADER_CLOCK")) { + shader_clock_support = true; } else if (strcmp("VK_VALVE_shader_mixed_float_dot_product", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_DOT2")) { dot2_f16_support = true; @@ -4919,6 +4927,14 @@ vk_device ggml_vk_get_device(size_t idx) { device_extensions.push_back("VK_KHR_shader_integer_dot_product"); } + VkPhysicalDeviceShaderClockFeaturesKHR shader_clock_features {}; + shader_clock_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR; + if (shader_clock_support) { + last_struct->pNext = (VkBaseOutStructure *)&shader_clock_features; + last_struct = (VkBaseOutStructure *)&shader_clock_features; + device_extensions.push_back("VK_KHR_shader_clock"); + } + VkPhysicalDeviceShaderMixedFloatDotProductFeaturesVALVE dot2_features {}; dot2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MIXED_FLOAT_DOT_PRODUCT_FEATURES_VALVE; if (dot2_f16_support) { @@ -5025,6 +5041,7 @@ vk_device ggml_vk_get_device(size_t idx) { device->shader_int64 = device_features2.features.shaderInt64; device->buffer_device_address = vk12_features.bufferDeviceAddress; device->vulkan_memory_model = vk12_features.vulkanMemoryModel; + device->shader_clock = shader_clock_support && shader_clock_features.shaderDeviceClock; if (device->subgroup_size_control) { device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize; @@ -10235,6 +10252,8 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const return ctx->device->pipeline_arange_f32; } return nullptr; + case GGML_OP_SLEEP: + return ctx->device->pipeline_sleep; case GGML_OP_FILL: if (dst->type == GGML_TYPE_F32) { return ctx->device->pipeline_fill_f32; @@ -11471,6 +11490,31 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); } +static void ggml_vk_sleep(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { + VK_LOG_DEBUG("ggml_vk_sleep(dst=" << dst << ", us=" << ggml_get_op_params_i32(dst, 0) << ")"); + + // Vulkan does not specify the period of the shader realtime clock this assumes it matches the timestamp counter. + // A driver where this does not hold could sleep too short or too long by that ratio + const float ns_per_tick = ctx->device->properties.limits.timestampPeriod; + const uint64_t ns = 1000 * (uint64_t) ggml_get_op_params_i32(dst, 0); + const uint64_t ticks = std::min(ns_per_tick > 0.0f ? (uint64_t)(ns / ns_per_tick) : ns, std::numeric_limits::max()); + + vk_op_sleep_push_constants pc = { + (uint32_t) ticks, + }; + + vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_SLEEP); + GGML_ASSERT(pipeline != nullptr); + + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); + + // a single invocation spins, the buffer is bound only to keep the spin from being optimized out + std::array elements = { 1, 1, 1 }; + + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); +} + void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst)); } @@ -13317,6 +13361,10 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in case GGML_OP_FILL: ggml_vk_fill(ctx, compute_ctx, node); + break; + case GGML_OP_SLEEP: + ggml_vk_sleep(ctx, compute_ctx, node); + break; case GGML_OP_SCALE: if (ctx->fused_hc_post_gate) { @@ -16768,6 +16816,8 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm return op->type == GGML_TYPE_F32; case GGML_OP_FILL: return op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16; + case GGML_OP_SLEEP: + return device->shader_clock; case GGML_OP_SCALE: return ggml_is_contiguous(op->src[0]) && ggml_vk_is_float_elementwise(op); case GGML_OP_PAD: diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp b/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp new file mode 100644 index 000000000000..07f6cafc9715 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp @@ -0,0 +1,37 @@ +#version 450 + +#extension GL_EXT_shader_realtime_clock : require + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +// never written, it only anchors the spin below so the compiler cannot drop it +layout (binding = 0) writeonly buffer D {uint data_d[];}; + +layout (push_constant) uniform parameter { + uint ticks; +} p; + +// bounds the spin in case the clock does not advance, turning a hang into a too-short sleep +const uint MAX_ITER = 1u << 27; + +void main() { + const uvec2 t0 = clockRealtime2x32EXT(); + + uvec2 t = t0; + + for (uint iter = 0; iter < MAX_ITER; ++iter) { + t = clockRealtime2x32EXT(); + + const uint lo = t.x - t0.x; + const uint hi = t.y - t0.y - (t.x < t0.x ? 1u : 0u); + + if (hi != 0u || lo >= p.ticks) { + break; + } + } + + // the store never runs, but the compiler cannot prove it and has to keep the spin + if (t.x == 0xFFFFFFFFu && t.y == 0xFFFFFFFFu) { + data_d[0] = t.x; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index 2a07746960af..e988600e3d44 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -1028,6 +1028,7 @@ void process_shaders() { string_to_spv("arange_f32", "arange.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}}); string_to_spv("fill_f32", "fill.comp", {{"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}}); string_to_spv("fill_f16", "fill.comp", {{"D_TYPE", "float16_t"}, {"FLOAT_TYPE", "float"}}); + string_to_spv("sleep", "sleep.comp", {}); string_to_spv("silu_back_f32", "silu_back.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}); diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 7132abc51f3b..68e3a011aed4 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -1112,9 +1112,11 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "OPT_STEP_SGD", "GLU", + + "SLEEP", }; -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); +static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1225,9 +1227,11 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "sgd(x)", "glu(x)", + + "sleep(x)", }; -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); +static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); @@ -6176,6 +6180,27 @@ struct ggml_tensor * ggml_custom_inplace( return result; } + +// ggml_sleep + +// the result aliases a, the op only delays and never touches the data +struct ggml_tensor * ggml_sleep( + struct ggml_context * ctx, + struct ggml_tensor * a, + int32_t us) { + GGML_ASSERT(us >= 0); + + struct ggml_tensor * result = ggml_view_tensor(ctx, a); + ggml_format_name(result, "%s (sleep)", a->name); + + ggml_set_op_params_i32(result, 0, us); + + result->op = GGML_OP_SLEEP; + result->src[0] = a; + + return result; +} + // ggml_cross_entropy_loss struct ggml_tensor * ggml_cross_entropy_loss( diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0b7e8e4a9b35..5b997e91bbcf 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -367,6 +367,8 @@ endif() llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) llama_build_and_test(test-backend-tensor.cpp LINK ggml) +llama_build_and_test(test-sleep.cpp LINK ggml) +llama_build_and_test(test-backend-sched.cpp LINK ggml) if (BUILD_SHARED_LIBS) llama_build_and_test(test-llama-mmap.cpp ${PROJECT_SOURCE_DIR}/src/llama-impl.cpp ${PROJECT_SOURCE_DIR}/src/llama-mmap.cpp LABEL behavior) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index be577b36c2dc..01ea4c115e8b 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9657,6 +9657,33 @@ struct test_fill : public test_case { } }; +// GGML_OP_SLEEP (for scheduler testing only) +struct test_sleep : public test_case { + const ggml_type type; + const std::array ne; + const int32_t us; + + std::string vars() override { return VARS_TO_STR3(type, ne, us); } + + // the op only delays, the output aliases the input and must match it exactly + double max_nmse_err() override { return 0.0; } + + test_sleep(int32_t us = 100, ggml_type type = GGML_TYPE_F32, + std::array ne = { 10, 10, 4, 3 }) + : type(type), ne(ne), us(us) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]); + ggml_set_name(a, "a"); + + ggml_tensor * out = ggml_sleep(ctx, a, us); + + ggml_set_name(out, "out"); + + return out; + } +}; + // GGML_OP_SOLVE_TRI struct test_solve_tri : public test_case { const ggml_type type; @@ -12996,6 +13023,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_fill(-152.0f, GGML_TYPE_F16, { 800, 600, 4, 4 })); test_cases.emplace_back(new test_fill(3.5f, GGML_TYPE_F16, { 2048, 512, 2, 2 })); + test_cases.emplace_back(new test_sleep(0)); + test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F16, { 128, 4, 2, 2 })); + test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F32, { 128, 4, 2, 2 })); + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { test_cases.emplace_back(new test_diag(type)); test_cases.emplace_back(new test_diag(type, { 79, 1, 19, 13 })); diff --git a/tests/test-backend-sched.cpp b/tests/test-backend-sched.cpp new file mode 100644 index 000000000000..8afdcc7caadd --- /dev/null +++ b/tests/test-backend-sched.cpp @@ -0,0 +1,1084 @@ +// Test suite for scheduler and backend behavior + +// Towards formalized scheduling behavior: +// - a single inference pass can run on several backends. The subset of nodes running on a single backend is a split +// - synchronous backends: +// - explicit synchronization (ggml_backend_synchronize()) is required between each operation +// - asynchronous backends: +// - Activations from one split can be copied asynchronously to the next (output of split N -> input of split N+1) +// - Several scheduling patterns must be supported by async backends. The scheduler may: +// - not explicitly synchronize between CPU->backend memcpy and graph execution on backend +// - dispatch several parallel memcpys to the same backend at once +// - schedule splits without inputs at any point in the graph + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include +#include +#include + + + +enum test_result { + TEST_FAIL = 0, + TEST_OK = 1, + TEST_SKIP = 2, // in case a backend does not support a required OP (e.g. OP_SLEEP) +}; + +// global counters for pass/fail/skip +static int n_ok = 0; +static int n_skip = 0; +static int n_test = 0; + +// default silent on success; --verbose / -v prints progress +static bool print_log = false; + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void log_maybe(const char * fmt, ...) { + if (!print_log) { + return; + } + + va_list args; + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); +} + +// pretty-print helpers start +static constexpr int status_column = 82; // for ok/fail column alignment +static int case_len = 0; +static char case_label[256]; // max length of a case label + +static void case_end(test_result res) { + n_ok += res == TEST_OK; + n_skip += res == TEST_SKIP; + n_test++; + + if (res != TEST_FAIL && !print_log) { + case_len = 0; + return; + } + + if (case_len == 0) { + case_len = printf(" %s", case_label); + } + + const char * status = "FAIL"; + if (res == TEST_OK) { + status = "OK"; + } else if (res == TEST_SKIP) { + status = "SKIP"; + } + + printf("%*s%s\n", std::max(1, status_column - case_len), "", status); + case_len = 0; +} + +static void vnote(const char * fmt, va_list args) { + if (case_len != 0) { + printf("\n"); + } + printf(" "); + vprintf(fmt, args); + printf("\n"); + + case_len = 0; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void note(const char * fmt, ...) { + if (!print_log) { + return; + } + + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static test_result fail(const char * fmt, ...) { + if (case_len == 0) { + case_len = printf(" %s", case_label); + } + + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); + + return TEST_FAIL; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static test_result skip(const char * fmt, ...) { + if (print_log) { + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); + } + + return TEST_SKIP; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void case_begin(const char * fmt, ...) { + va_list args; + va_start(args, fmt); + vsnprintf(case_label, sizeof(case_label), fmt, args); + va_end(args); + + if (print_log) { + case_len = printf(" %s", case_label); + fflush(stdout); + } else { + case_len = 0; + } +} +// pretty-print helpers end + + +// NB: the last backend passed has to be the CPU backend (cf. ggml_backend_sched_new) +static ggml_backend_sched_ptr create_test_scheduler(std::vector backends, size_t graph_size, + bool use_device_host_buft, bool parallel = false) { + + std::vector bufts(backends.size()); + for (size_t b = 0; b < backends.size(); b++) { + bufts[b] = ggml_backend_get_default_buffer_type(backends[b]); + } + + // pinned memory for the CPU backend (always required to be the last backend) enables async copies to other devices + // the host buffer type comes from the first backend, (cf. llama_context::llama_context()) + if (use_device_host_buft) { + ggml_backend_buffer_type_t host = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backends[0])); + if (host != nullptr) { + bufts.back() = host; + } + } + + return ggml_backend_sched_ptr(ggml_backend_sched_new(backends.data(), bufts.data(), (int) backends.size(), + graph_size, parallel, /*op_offload =*/ false)); +} + +// the nodes of the graph together with the backend each of them is assigned to +struct helper_graph { + ggml_cgraph * gf; + std::vector nodes; + std::vector backend_id; + + helper_graph(ggml_context * ctx, size_t graph_size) : gf(ggml_new_graph_custom(ctx, graph_size, /*grads =*/ false)) {} + + ggml_tensor * add(ggml_tensor * node, int backend) { + nodes.push_back(node); + backend_id.push_back(backend); + ggml_build_forward_expand(gf, node); + + return node; + } +}; + +struct helper_check { + ggml_tensor * tensor; // Tensor for which to check the data. + float expected; // The expected value that the tensor data should have after graph execution. +}; + +// asks whether the backend implements the op, independent of where the sources of this node currently live. +static bool backend_supports_op(ggml_backend_t backend, const ggml_tensor * node) { + ggml_init_params params = { + /*.mem_size =*/ GGML_MAX_SRC*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx(ggml_init(params)); + + ggml_tensor probe = *node; + probe.buffer = nullptr; + probe.view_src = nullptr; + probe.data = nullptr; + + for (ggml_tensor *& src : probe.src) { + if (src != nullptr) { + src = ggml_dup_tensor(ctx.get(), src); + } + } + + return ggml_backend_supports_op(backend, &probe); +} + +// executes the graph, then checks the number of splits and the results +static test_result run_and_check(ggml_backend_sched_t sched, const helper_graph & g, + const std::vector & backends, const std::vector & checks, int64_t ne) { + + // ggml_backend_sched_set_tensor_backend does not validate the op, an unsupported one would abort inside the backend + for (size_t i = 0; i < g.nodes.size(); i++) { + ggml_backend_t backend = backends[g.backend_id[i]]; + if (!backend_supports_op(backend, g.nodes[i])) { + return skip("%s does not support %s", ggml_backend_name(backend), ggml_op_name(g.nodes[i]->op)); + } + } + + // to later check if any further graph logic alters the number of splits + int n_splits_expected = g.nodes.empty() ? 0 : 1; + for (size_t i = 1; i < g.backend_id.size(); i++) { + n_splits_expected += g.backend_id[i] != g.backend_id[i - 1]; + } + + ggml_backend_sched_reset(sched); + for (size_t i = 0; i < g.nodes.size(); i++) { + ggml_backend_sched_set_tensor_backend(sched, g.nodes[i], backends[g.backend_id[i]]); + } + + if (!ggml_backend_sched_alloc_graph(sched, g.gf)) { + return fail("failed to allocate the graph"); + } + + if (ggml_backend_sched_graph_compute(sched, g.gf) != GGML_STATUS_SUCCESS) { + return fail("failed to compute the graph"); + } + + const int n_splits = ggml_backend_sched_get_n_splits(sched); + if (n_splits != n_splits_expected) { + return fail("n_splits = %d, expected %d, each split consisting of just a single node", n_splits, n_splits_expected); + } + + std::vector data(ne); + for (const helper_check & c : checks) { + ggml_backend_tensor_get(c.tensor, data.data(), 0, ggml_nbytes(c.tensor)); + for (int64_t i = 0; i < ne; i++) { + if (data[i] != c.expected) { + return fail("%s[%" PRId64 "] = %f, expected %f", ggml_get_name(c.tensor), i, data[i], c.expected); + } + } + } + + return TEST_OK; +} + +// helper struct for inputless splits, and constants like 0 and 1 +struct backend_consts { + // the buffers are declared after the contexts, so that they are released first + std::vector ctxs; + std::vector bufs; + std::vector zero; + std::vector one; + + backend_consts(const std::vector & backends, int64_t ne) { + std::vector data(ne); + + for (size_t b = 0; b < backends.size(); b++) { + ggml_init_params params = { + /*.mem_size =*/ 2*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context * ctx = ggml_init(params); + + ggml_tensor * z = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne); + ggml_format_name(z, "zero_%s", ggml_backend_name(backends[b])); + + ggml_tensor * o = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne); + ggml_format_name(o, "one_%s", ggml_backend_name(backends[b])); + + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backends[b]); + GGML_ASSERT(buf != nullptr); + + std::fill(data.begin(), data.end(), 0.0f); + ggml_backend_tensor_set(z, data.data(), 0, ggml_nbytes(z)); + + std::fill(data.begin(), data.end(), 1.0f); + ggml_backend_tensor_set(o, data.data(), 0, ggml_nbytes(o)); + + ctxs.emplace_back(ctx); + bufs.emplace_back(buf); + zero.push_back(z); + one.push_back(o); + } + } +}; + +// TODO add tests for the auto-assign logic of nodes to backends of the scheduler. Possible tests: +// - test of CPU backend with any other backend. Expectation is that GEMM-nodes (usually the first accelerated components) are assigned to the non-CPU backend +// - test of the property that tensor location influences backend assignment. +// - test of neighbor propagation logic? 3 nodes, with the middle one initially on CPU, moved to the other backend? + + +// stress test: a tensor is incremented and sent back and forth between the backends in a ping-pong pattern. +// One pass pairs every backend a with every other backend b via nested loops. +// The counter is brought to a, then bounced to b and back for every partner in turn. +// So one pass copies an activation across every ordered pair of backends. +// Every lap runs two passes: one where the nodes add the constant 1, one where they add a user input +// from the CPU backend, so that every transition is tested with and without an input next to the activation. +// The input values come from a fixed seed. +static test_result stress_test_linked_list(const std::vector & backends, int n_laps, + int64_t tensor_len, bool use_device_host_buft) { + const int n_backends = (int) backends.size(); + + // per pass and backend a: one node to bring the counter to a, then two per partner for the ping-pong + const int n_nodes_pass = n_backends*(2*n_backends - 1); + const int n_nodes = 2*n_laps*n_nodes_pass; + const int n_inputs = n_laps*n_nodes_pass; // one per node of the pass that takes user inputs + + // initial pseudo-random value draw so that the expected result is known before graph execution + std::mt19937 rng(42); + std::uniform_int_distribution draw_value(1, 10000); + + std::vector input_value(n_inputs); // random values store + int64_t sum_inputs = 0; + + for (int i = 0; i < n_inputs; i++) { + input_value[i] = draw_value(rng); + sum_inputs += input_value[i]; + } + + // see sched->hash_set FIXME, the set has to hold the nodes and the leafs: two constants per backend + // plus the user inputs + const size_t graph_size = n_nodes + 2*n_backends + n_inputs; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + // the user inputs all live on the CPU backend, with the same buffer type the scheduler uses for it + ggml_init_params params_input = { + /*.mem_size =*/ n_inputs*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_input(ggml_init(params_input)); + ggml_backend_buffer_ptr buf_input; + + std::vector input(n_inputs); + for (int i = 0; i < n_inputs; i++) { + input[i] = ggml_new_tensor_1d(ctx_input.get(), GGML_TYPE_F32, tensor_len); + ggml_format_name(input[i], "input%d", i); + ggml_set_input(input[i]); + } + + // the inputs follow the buffer type the scheduler uses for the CPU backend (cf. create_test_scheduler) + ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(backends.back()); + if (use_device_host_buft) { + ggml_backend_buffer_type_t host = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backends[0])); + if (host != nullptr) { + buft = host; + } + } + + buf_input.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_input.get(), buft)); + GGML_ASSERT(buf_input != nullptr); + + // write inputs before graph execution + std::vector data(tensor_len); + for (int i = 0; i < n_inputs; i++) { + std::fill(data.begin(), data.end(), float(input_value[i])); + ggml_backend_tensor_set(input[i], data.data(), 0, ggml_nbytes(input[i])); + } + + ggml_init_params params_compute = { + /*.mem_size =*/ (n_nodes + 2)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + int64_t sum = 0; + ggml_tensor * out = nullptr; + + int i = 0; // next user input to consume + + // increments the counter on backend b, which makes the scheduler copy it there from the previous backend + auto step = [&](int b, bool with_input) { + ggml_tensor * src = out == nullptr ? consts.zero[b] : out; + + if (with_input) { + out = g.add(ggml_add(ctx_compute.get(), src, input[i]), b); + i++; + } else { + out = g.add(ggml_add(ctx_compute.get(), src, consts.one[b]), b); + sum += 1; + } + }; + + for (int lap = 0; lap < n_laps; lap++) { + for (bool with_input : { false, true }) { // test each transition with and without input + for (int a = 0; a < n_backends; a++) { + step(a, with_input); + + for (int b = 0; b < n_backends; b++) { + if (b == a) { + continue; + } + + step(b, with_input); + step(a, with_input); + } + } + } + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + // every node adds either the constant 1 or its drawn user input + const int64_t expected = sum + sum_inputs; + + note("%d of %d nodes take a user input, they contribute %" PRId64 " of %" PRId64, n_inputs, n_nodes, sum_inputs, expected); + + test_result ok; + if (expected >= (1 << 24)) { // the counter has to stay exact in f32 + ok = fail("expected result %" PRId64 " does not fit into the f32 mantissa, lower n_laps", expected); + } else { + ok = run_and_check(sched.get(), g, backends, {{ out, float(expected) }}, tensor_len); + } + + return ok; +} + +// Same idea as stress_test_linked_list, but with the compute graph being a directed acyclic graph (DAG). +// n_lanes independent counters run through rounds of four shapes, so that one graph covers: +// - lanes with different histories, so a misrouted copy shows up as a wrong count in a single lane +// - one split producing two values followed by two splits that each consume one of them and do not depend on each other +// - splits with no inputs at all, from lanes re-seeded out of constants that already live on the split's backend +// - splits taking one activation per lane from the previous split, one of them from an older split instead +static test_result stress_test_dag(const std::vector & backends, int n_lanes, int n_rounds, + int64_t tensor_len, bool use_device_host_buft) { + + const int n_backends = (int) backends.size(); + + GGML_ASSERT(n_lanes % 2 == 0); + + // sized for the worst case + const size_t graph_size = n_lanes*(2*n_rounds + 1) + 2*n_backends; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + std::vector lane(n_lanes); + std::vector value(n_lanes); + std::vector checks; + + // every lane starts at a different value, so that a misrouted copy changes a sum instead of going unnoticed + auto seed = [&](int b, const char * prefix) { + for (int l = 0; l < n_lanes; l++) { + lane[l] = g.add(ggml_add(ctx_compute.get(), l == 0 ? consts.zero[b] : lane[l - 1], consts.one[b]), b); + value[l] = l + 1; + ggml_format_name(lane[l], "%s%d", prefix, l); + } + }; + + auto check_lanes = [&]() { + for (int l = 0; l < n_lanes; l++) { + ggml_set_output(lane[l]); + checks.push_back({ lane[l], float(value[l]) }); + } + }; + + seed(0, "seed"); + + std::vector older = lane; + std::vector value_older = value; + + for (int round = 0; round < n_rounds; round++) { + // a backend the previous node did not use, so that the round is not absorbed into the split before it + const int b = (g.backend_id.back() + 1) % n_backends; + + const std::vector prev = lane; + const std::vector value_prev = value; + + switch (round % 5) { + case 0: + for (int p = 0; p < n_lanes/2; p++) { + const int la = 2*p; + const int lb = 2*p + 1; + const int prod = (b + p) % n_backends; + const int cons = (prod + 1) % n_backends; + + // one split producing two values ... + for (int l : { la, lb }) { + lane[l] = g.add(ggml_add(ctx_compute.get(), lane[l], consts.one[prod]), prod); + value[l]++; + ggml_format_name(lane[l], "r%d_prod%d", round, l); + } + + // ... and two splits that each consume one of them, with no dependency on each other + lane[la] = g.add(ggml_add(ctx_compute.get(), lane[la], consts.one[cons]), cons); + value[la]++; + ggml_format_name(lane[la], "r%d_cons%d", round, la); + + lane[lb] = g.add(ggml_add(ctx_compute.get(), lane[lb], consts.one[prod]), prod); + value[lb]++; + ggml_format_name(lane[lb], "r%d_cons%d", round, lb); + } + break; + case 1: + check_lanes(); + seed(b, "restart"); + break; + case 2: + case 3: + for (int l = 0; l < n_lanes; l++) { + const int partner = (l + 1 + round) % n_lanes; + const bool reach_back = round >= 2 && l == round % n_lanes; + + ggml_tensor * a = reach_back ? older[l] : prev[l]; + const int64_t va = reach_back ? value_older[l] : value_prev[l]; + + lane[l] = g.add(ggml_add(ctx_compute.get(), a, prev[partner]), b); + value[l] = va + value_prev[partner]; + ggml_format_name(lane[l], "r%d_lane%d", round, l); + } + break; + case 4: + lane[0] = g.add(ggml_add(ctx_compute.get(), prev[0], consts.one[b]), b); + value[0] = value_prev[0] + 1; + ggml_format_name(lane[0], "r%d_single", round); + break; + default: + GGML_ABORT("unexpected round %d", round); + } + + older = prev; + value_older = value_prev; + } + + check_lanes(); + + test_result ok = TEST_OK; + for (const helper_check & c : checks) { + if (c.expected >= float(1 << 24)) { // the counts have to stay exact in f32 + ok = fail("expected result %.0f does not fit into the f32 mantissa, lower n_rounds", c.expected); + break; + } + } + + if (ok == TEST_OK) { + ok = run_and_check(sched.get(), g, backends, checks, tensor_len); + } + + return ok; +} + +// Created in response to https://github.com/ggml-org/llama.cpp/issues/23321 +// Currently, input copies to splits synchronize split execution. +// CPU split N+1 could overwrite output of split N if this was not copied to backend in time. +// Mechanism to test: GPU split with long sleep to clog CUDA stream / vk command queue, +// followed by CPU splits without input, provoking a race condition in the current setup. +// GPU: 100ms sleep to clog stream/queue +// CPU: produce {55} +// GPU: request copy of {55} in CUDA stream, ADD {44}; Output should be {99} +// CPU: produce {66} +// GPU: increment both {99} and {66} -> {100} and {67} +// Correct result is thus {100}, incorrect output is {111} when {55} was overwritten by {66} before the copy started. +// Note: currently only reproducible on async H2D copy (=pinned memory). +static test_result test_inputless_splits_scheduling(ggml_backend_t gpu, ggml_backend_t cpu, int64_t tensor_len, int32_t sleep_us, bool use_device_host_buft) { + + const int GPU = 0; + const int CPU = 1; + + const std::vector backends = { gpu, cpu }; + + const size_t graph_size = 64; + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_static = { + /*.mem_size =*/ 4*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + + ggml_context_ptr ctx_cpu(ggml_init(params_static)); + + ggml_tensor * zero_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(zero_cpu, "zero_cpu"); + + ggml_tensor * val55_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val55_cpu, "val55_cpu"); + + ggml_tensor * val66_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val66_cpu, "val66_cpu"); + + ggml_backend_buffer_ptr buf_cpu(ggml_backend_alloc_ctx_tensors(ctx_cpu.get(), cpu)); + GGML_ASSERT(buf_cpu != nullptr); + + ggml_context_ptr ctx_gpu(ggml_init(params_static)); + + ggml_tensor * zero_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(zero_gpu, "zero_gpu"); + + ggml_tensor * one_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(one_gpu, "one_gpu"); + + ggml_tensor * val44_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val44_gpu, "val44_gpu"); + + ggml_backend_buffer_ptr buf_gpu(ggml_backend_alloc_ctx_tensors(ctx_gpu.get(), gpu)); + GGML_ASSERT(buf_gpu != nullptr); + + std::vector data(tensor_len); + + std::fill(data.begin(), data.end(), 0.0f); + ggml_backend_tensor_set(zero_cpu, data.data(), 0, ggml_nbytes(zero_cpu)); + ggml_backend_tensor_set(zero_gpu, data.data(), 0, ggml_nbytes(zero_gpu)); + + std::fill(data.begin(), data.end(), 1.0f); + ggml_backend_tensor_set(one_gpu, data.data(), 0, ggml_nbytes(one_gpu)); + + std::fill(data.begin(), data.end(), 44.0f); + ggml_backend_tensor_set(val44_gpu, data.data(), 0, ggml_nbytes(val44_gpu)); + + std::fill(data.begin(), data.end(), 55.0f); + ggml_backend_tensor_set(val55_cpu, data.data(), 0, ggml_nbytes(val55_cpu)); + + std::fill(data.begin(), data.end(), 66.0f); + ggml_backend_tensor_set(val66_cpu, data.data(), 0, ggml_nbytes(val66_cpu)); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + // GPU: add then sleep - occupies the GPU while later splits run + ggml_tensor * delayed = g.add(ggml_add(ctx_compute.get(), zero_gpu, one_gpu), GPU); + ggml_set_name(delayed, "to_delay"); + delayed = g.add(ggml_sleep(ctx_compute.get(), delayed, sleep_us), GPU); + ggml_set_name(delayed, "delayed"); + + // CPU: 0 + 55 -> 55 + ggml_tensor * v55 = g.add(ggml_add(ctx_compute.get(), zero_cpu, val55_cpu), CPU); + ggml_set_name(v55, "v55"); + + // GPU: 55 + 44 -> 99 + ggml_tensor * v99 = g.add(ggml_add(ctx_compute.get(), v55, val44_gpu), GPU); + ggml_set_name(v99, "v99"); + + // CPU: 0 + 66 -> 66 + ggml_tensor * v66 = g.add(ggml_add(ctx_compute.get(), zero_cpu, val66_cpu), CPU); + ggml_set_name(v66, "v66"); + + // GPU: increment both of the previous split outputs + ggml_tensor * out99 = g.add(ggml_add(ctx_compute.get(), v99, one_gpu), GPU); + ggml_set_name(out99, "out99"); + + ggml_tensor * out66 = g.add(ggml_add(ctx_compute.get(), v66, one_gpu), GPU); + ggml_set_name(out66, "out66"); + + ggml_set_output(delayed); + ggml_set_output(out99); + ggml_set_output(out66); + + const test_result ok = run_and_check(sched.get(), g, backends, { + { delayed, 1.0f }, + { out99, 100.0f }, + { out66, 67.0f }, + }, tensor_len); + + // the race needs the allocator to reuse the memory of the first CPU split for the second one + note("v55 and v66 %s (v55=%p v66=%p)", v55->data == v66->data ? "alias" : "do not alias", v55->data, v66->data); + + return ok; +} + +// Test that all async backends transmit their activations to the following async backend correctly. No user inputs tested. +static test_result test_chain_all_backends(const std::vector & backends, int64_t tensor_len, int32_t sleep_us, + bool use_device_host_buft) { + + const int n_backends = (int) backends.size(); + + std::vector seq; + + auto push = [&](int b) { + if (seq.empty() || seq.back() != b) { + seq.push_back(b); + } + }; + + for (int i = 0; i < n_backends; i++) { + for (int j = 0; j < n_backends; j++) { + if (i != j) { + push(i); + push(j); + } + } + } + + const size_t n_nodes = seq.size(); + const size_t n_sleeps = sleep_us > 0 ? n_nodes : 0; // one sleep per split + const size_t graph_size = n_nodes + n_sleeps + n_backends + 1; // see sched->hash_set FIXME, one "one" per backend plus the "zero" that starts the chain + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * out = nullptr; + for (size_t k = 0; k < n_nodes; k++) { + const int b = seq[k]; + + out = g.add(ggml_add(ctx_compute.get(), k == 0 ? consts.zero[b] : out, consts.one[b]), b); + + // the sleep keeps the backend busy, so that the next one has to wait for this split + if (sleep_us > 0) { + out = g.add(ggml_sleep(ctx_compute.get(), out, sleep_us), b); + } + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + const test_result ok = run_and_check(sched.get(), g, backends, {{ out, float(n_nodes) }}, tensor_len); + + return ok; +} + +// Tests data transfer between all combinations of backend pairs +// The receiving split takes one activation from the sender plus n_inputs user inputs +static test_result test_pair_user_inputs(const std::vector & backends, int b_send, int b_recv, int64_t tensor_len, + int n_inputs, bool inputs_on_sender, bool parallel, bool use_device_host_buft) { + + const size_t graph_size = 64; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft, parallel); + + // placing the inputs on the sender makes the receiving split copy all of them, placing them on the + // receiver leaves the activation as its only input + const int b_inputs = inputs_on_sender ? b_send : b_recv; + + ggml_init_params params_inputs = { + /*.mem_size =*/ n_inputs*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_inputs(ggml_init(params_inputs)); + + std::vector inputs; + for (int k = 0; k < n_inputs; k++) { + ggml_tensor * in = ggml_new_tensor_1d(ctx_inputs.get(), GGML_TYPE_F32, tensor_len); + ggml_format_name(in, "in%d", k); + ggml_set_input(in); + inputs.push_back(in); + } + + ggml_backend_buffer_ptr buf_inputs(ggml_backend_alloc_ctx_tensors(ctx_inputs.get(), backends[b_inputs])); + GGML_ASSERT(buf_inputs != nullptr); + + std::vector data(tensor_len); + std::fill(data.begin(), data.end(), 1.0f); + for (ggml_tensor * in : inputs) { + ggml_backend_tensor_set(in, data.data(), 0, ggml_nbytes(in)); + } + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * out = g.add(ggml_add(ctx_compute.get(), consts.zero[b_send], consts.one[b_send]), b_send); + + for (ggml_tensor * in : inputs) { + out = g.add(ggml_add(ctx_compute.get(), out, in), b_recv); + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + test_result ok = run_and_check(sched.get(), g, backends, {{ out, float(1 + n_inputs) }}, tensor_len); + + for (ggml_tensor * in : inputs) { + if (ok != TEST_OK) { + break; + } + ggml_backend_tensor_get(in, data.data(), 0, ggml_nbytes(in)); + for (int64_t i = 0; i < tensor_len; i++) { + if (data[i] != 1.0f) { + ok = fail("%s[%" PRId64 "] = %f after compute, expected 1.000000 - the input was modified", ggml_get_name(in), i, data[i]); + break; + } + } + } + + return ok; +} + +// Tests Y-shaped scheduling: two parallel lanes merging into 1. Lane A and B, merging into a single split. +// The lanes join in a final split on backend_a that receives one activation from each of the two backend_b splits. +static test_result test_y_shaped_graph(const std::vector & backends, int backend_a, int backend_b, int64_t tensor_len, + int32_t sleep_us, bool use_device_host_buft) { + + const size_t graph_size = 64; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * seed_a = g.add(ggml_add(ctx_compute.get(), consts.zero[backend_a], consts.one[backend_a]), backend_a); + ggml_set_name(seed_a, "seed_a"); + + // only lane a sleeps, so that lane b is scheduled while it is still running + if (sleep_us > 0) { + seed_a = g.add(ggml_sleep(ctx_compute.get(), seed_a, sleep_us), backend_a); + ggml_set_name(seed_a, "seed_a_delayed"); + } + + ggml_tensor * lane_a = g.add(ggml_add(ctx_compute.get(), seed_a, consts.one[backend_b]), backend_b); + ggml_set_name(lane_a, "lane_a"); + + if (sleep_us > 0) { + lane_a = g.add(ggml_sleep(ctx_compute.get(), lane_a, sleep_us), backend_b); + ggml_set_name(lane_a, "lane_a_delayed"); + } + + ggml_tensor * seed_b = g.add(ggml_add(ctx_compute.get(), consts.zero[backend_a], consts.one[backend_a]), backend_a); + ggml_set_name(seed_b, "seed_b"); + + ggml_tensor * lane_b = g.add(ggml_add(ctx_compute.get(), seed_b, consts.one[backend_b]), backend_b); + ggml_set_name(lane_b, "lane_b"); + + // neither lane ends on backend_a, so both activations are inputs of the last split + ggml_tensor * out = g.add(ggml_add(ctx_compute.get(), lane_a, lane_b), backend_a); + ggml_set_name(out, "out"); + ggml_set_output(out); + + const test_result ok = run_and_check(sched.get(), g, backends, {{ out, 4.0f }}, tensor_len); + + return ok; +} + +static const char * dev_type_name(enum ggml_backend_dev_type type) { + switch (type) { + case GGML_BACKEND_DEVICE_TYPE_CPU: return "CPU"; + case GGML_BACKEND_DEVICE_TYPE_GPU: return "GPU"; + case GGML_BACKEND_DEVICE_TYPE_IGPU: return "IGPU"; + case GGML_BACKEND_DEVICE_TYPE_ACCEL: return "ACCEL"; + case GGML_BACKEND_DEVICE_TYPE_META: return "META"; + } + return "UNKNOWN"; +} + +static bool initialize_backends(std::vector & backends) { + + // cf. GGML_SCHED_MAX_BACKENDS + const size_t max_backends = 16; + + for (size_t i = 0; i < ggml_backend_dev_count() && backends.size() + 1 < max_backends; i++) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + log_maybe("device %2zu: %-10s %-5s (%s)\n", i, ggml_backend_dev_name(dev), + dev_type_name(ggml_backend_dev_type(dev)), ggml_backend_dev_description(dev)); + + const enum ggml_backend_dev_type type = ggml_backend_dev_type(dev); + // Exclude ACCEL devices as they run in tandem with the CPU backend and only implement matmul, the tests here require ADD + if (type == GGML_BACKEND_DEVICE_TYPE_CPU || type == GGML_BACKEND_DEVICE_TYPE_ACCEL) { + continue; + } + + ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr); + if (backend == nullptr) { + printf("failed to initialize %s, skipping it\n", ggml_backend_dev_name(dev)); + continue; + } + + backends.emplace_back(backend); + } + + if (backends.empty()) { + printf("no non-CPU backend found, skipping\n"); + return false; + } + + // ggml_backend_sched_new requires the CPU backend to be the last one + backends.emplace_back(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr)); + GGML_ASSERT(backends.back() != nullptr); + + for (const ggml_backend_ptr & backend : backends) { + ggml_backend_dev_t dev = ggml_backend_get_device(backend.get()); + + log_maybe("backend: %-10s host_buft = %d (%s)\n", ggml_backend_name(backend.get()), + ggml_backend_dev_host_buffer_type(dev) != nullptr, ggml_backend_dev_description(dev)); + } + log_maybe("\n"); + return true; +} + + +int main(int argc, char ** argv) { + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) { + print_log = true; + } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { + printf("Usage: %s [-v|--verbose]\n", argv[0]); + return 0; + } else { + fprintf(stderr, "unknown argument: %s\n", argv[i]); + fprintf(stderr, "Usage: %s [-v|--verbose]\n", argv[0]); + return 1; + } + } + + ggml_backend_load_all(); + + std::vector backends; + + // nothing to test with synchronous CPU backend only + if (!initialize_backends(backends)) { + return 0; + } + + // the tests only borrow the backends, the ownership stays with this vector + std::vector backend_ptrs; + for (const ggml_backend_ptr & backend : backends) { + backend_ptrs.push_back(backend.get()); + } + + ggml_backend_t cpu = backend_ptrs.back(); + const size_t n_non_cpu_backends = backend_ptrs.size() - 1; + + // Test cases for single backends against CPU backend + for (size_t b_id = 0; b_id < n_non_cpu_backends; b_id++) { + ggml_backend_t backend = backend_ptrs[b_id]; + const char * name_backend = ggml_backend_name(backend); + + for (bool use_device_host_buft : { false, true }) { + // without a host buffer type this case is a duplicate of the pageable one + if (use_device_host_buft && ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend)) == nullptr) { + continue; + } + + log_maybe("=== Backend: %s, CPU sched buft: %s ===\n\n", name_backend, use_device_host_buft ? "device_host" : "pageable"); + + for (int32_t sleep_us : {50, 60, 70, 80, 400, 500, 600, 700, 1000, 10000}) { + for (int tensor_len : { 2, 2048, 4096, 8192, 1600}) { + case_begin("test_inputless_splits_scheduling %-8s sleep_us = %6d, tensor_len = %4d", name_backend, sleep_us, tensor_len); + case_end(test_inputless_splits_scheduling(backend, cpu, tensor_len, sleep_us, use_device_host_buft)); + } + } + + log_maybe("\n"); + } + } + + // Test cases for all present backend subsets + for (bool use_device_host_buft : { false, true }) { + // create_test_scheduler takes the host buffer type from the first backend + if (use_device_host_buft && ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend_ptrs[0])) == nullptr) { + continue; + } + + log_maybe("=== all backends, CPU sched buft: %s ===\n\n", use_device_host_buft ? "device_host" : "pageable"); + + for (int n_lanes : { 8, 16 }) { + for (int n_rounds : { 5, 13, 64 }) { + for (int tensor_len : { 2, 4096 }) { + case_begin("stress_test_dag n_lanes = %2d, n_rounds = %2d, tensor_len = %4d", n_lanes, n_rounds, tensor_len); + case_end(stress_test_dag(backend_ptrs, n_lanes, n_rounds, tensor_len, use_device_host_buft)); + } + } + } + + log_maybe("\n"); + + for (int tensor_len : { 2, 4096 }) { + for (int32_t sleep_us : { 0, 80 }) { + case_begin("test_chain_all_backends sleep_us = %4d, tensor_len = %4d", sleep_us, tensor_len); + case_end(test_chain_all_backends(backend_ptrs, tensor_len, sleep_us, use_device_host_buft)); + } + } + + log_maybe("\n"); + + for (int n_laps : { 1, 4, 64 }) { + for (int tensor_len : { 2, 4096 }) { + case_begin("stress_test_linked_list n_laps = %3d, tensor_len = %4d", n_laps, tensor_len); + case_end(stress_test_linked_list(backend_ptrs, n_laps, tensor_len, use_device_host_buft)); + } + } + + log_maybe("\n"); + + // every ordered pair of backends is the sender and the receiver of a copy + for (size_t backend_a = 0; backend_a < backend_ptrs.size(); backend_a++) { + for (size_t backend_b = 0; backend_b < backend_ptrs.size(); backend_b++) { + if (backend_a == backend_b) { + continue; + } + + const char * name_a = ggml_backend_name(backend_ptrs[backend_a]); + const char * name_b = ggml_backend_name(backend_ptrs[backend_b]); + + for (bool inputs_on_sender : { false, true }) { + for (bool parallel : { false, true }) { + for (int tensor_len : { 1, 4096 }) { + case_begin("test_pair_user_inputs %-8s -> %-8s inputs on %-8s parallel = %d, tensor_len = %4d", + name_a, name_b, inputs_on_sender ? "sender" : "receiver", parallel, tensor_len); + case_end(test_pair_user_inputs(backend_ptrs, (int) backend_a, (int) backend_b, tensor_len, + /*n_inputs =*/ 4, inputs_on_sender, parallel, use_device_host_buft)); + } + } + } + + for (int tensor_len : { 1, 4096 }) { + for (int32_t sleep_us : { 0, 80 }) { + case_begin("test_y_shaped %-8s -> %-8s sleep_us = %4d, tensor_len = %4d", name_a, name_b, sleep_us, tensor_len); + case_end(test_y_shaped_graph(backend_ptrs, (int) backend_a, (int) backend_b, tensor_len, sleep_us, use_device_host_buft)); + } + } + } + } + + log_maybe("\n"); + } + + if (print_log || n_ok + n_skip != n_test) { + printf("%d/%d tests passed", n_ok, n_test); + if (n_skip > 0) { + printf(", %d skipped", n_skip); + } + printf("\n"); + } + + return n_ok + n_skip == n_test ? 0 : 1; +} diff --git a/tests/test-sleep.cpp b/tests/test-sleep.cpp new file mode 100644 index 000000000000..bd836c33870a --- /dev/null +++ b/tests/test-sleep.cpp @@ -0,0 +1,154 @@ +// Tests for GGML_OP_SLEEP, on every backend that supports it. Three properties are checked: +// - the op only delays: input = output +// - the op does not return early: a chain of n sleeps must take at least n*us +// Only a lower bound is asserted for the duration. A busy-wait cannot finish early, so that bound is +// deterministic, whereas an upper bound would be flaky on a loaded machine. +// Known limitation: Vulkan does not specify the tick rate of the shader clock, see ggml_vk_sleep. A driver +// whose clock runs slower than assumed could undershoot the request and fail this bound. + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include + +enum test_result { + TEST_OK, + TEST_FAIL, + TEST_SKIP, +}; + +static test_result test_sleep(ggml_backend_t backend, ggml_type type, int64_t ne, int32_t us, int n_nodes) { + const size_t graph_size = n_nodes + 16; + + ggml_init_params params_static = { + /*.mem_size =*/ ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_static(ggml_init(params_static)); + + ggml_tensor * x = ggml_new_tensor_1d(ctx_static.get(), type, ne); + ggml_set_name(x, "x"); + ggml_set_input(x); + + ggml_init_params params_compute = { + /*.mem_size =*/ n_nodes*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + ggml_cgraph * gf = ggml_new_graph_custom(ctx_compute.get(), graph_size, false); + + ggml_tensor * out = x; + for (int i = 0; i < n_nodes; i++) { + out = ggml_sleep(ctx_compute.get(), out, us); + } + ggml_set_name(out, "out"); + ggml_build_forward_expand(gf, out); + + // the backends log to stdout while computing, so the result line is only printed once it is complete + char desc[128]; + snprintf(desc, sizeof(desc), " %-6s %-4s ne=%-9" PRId64 " us=%-7d n_nodes=%d ", + ggml_backend_name(backend), ggml_type_name(type), ne, us, n_nodes); + + test_result result = TEST_OK; + + if (!ggml_backend_supports_op(backend, out)) { + printf("%snot supported\n", desc); + result = TEST_SKIP; + } else { + ggml_backend_buffer_ptr buf_static(ggml_backend_alloc_ctx_tensors(ctx_static.get(), backend)); + + // random bytes rather than random floats, so that bit patterns a value-wise copy could + // mangle, such as NaNs and denormals, are covered as well + std::vector data_in(ggml_nbytes(x)); + std::mt19937 rng(1234); + for (size_t i = 0; i < data_in.size(); i++) { + data_in[i] = rng() & 0xFF; + } + ggml_backend_tensor_set(x, data_in.data(), 0, data_in.size()); + + ggml_gallocr_ptr galloc(ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend))); + ggml_gallocr_alloc_graph(galloc.get(), gf); + + // warm up, so that one-time costs such as lazy CUDA module loading are not timed + ggml_backend_graph_compute(backend, gf); + + const int64_t t_start_us = ggml_time_us(); + const ggml_status status = ggml_backend_graph_compute(backend, gf); + const int64_t t_us = ggml_time_us() - t_start_us; + + std::vector data_out(ggml_nbytes(out)); + ggml_backend_tensor_get(out, data_out.data(), 0, data_out.size()); + + const int64_t t_min_us = (int64_t) n_nodes * us; + + const bool ok_status = status == GGML_STATUS_SUCCESS; + const bool ok_alias = out->data == x->data; + const bool ok_data = memcmp(data_in.data(), data_out.data(), data_in.size()) == 0; + const bool ok_time = t_us >= t_min_us; + + printf("%selapsed=%7" PRId64 " us (>= %6" PRId64 ") alias: %-4s data: %-4s time: %s\n", + desc, t_us, t_min_us, ok_alias ? "OK" : "FAIL", ok_data ? "OK" : "FAIL", ok_time ? "OK" : "FAIL"); + + if (!ok_status) { + printf(" compute failed: %s\n", ggml_status_to_string(status)); + } + + result = ok_status && ok_alias && ok_data && ok_time ? TEST_OK : TEST_FAIL; + } + + return result; +} + +int main() { + ggml_time_init(); + ggml_backend_load_all(); + + int n_ok = 0; + int n_fail = 0; + int n_skip = 0; + + for (size_t i = 0; i < ggml_backend_dev_count(); i++) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + + ggml_backend_ptr backend(ggml_backend_dev_init(dev, nullptr)); + if (backend == nullptr) { + printf(" failed to initialize %s\n", ggml_backend_dev_name(dev)); + n_fail++; + continue; + } + + // a zero duration must still be a valid no-op, longer ones are checked against the clock, + // and the last case verifies that a chain of sleeps accumulates instead of collapsing into one + const struct { + ggml_type type; + int64_t ne; + int32_t us; + int n_nodes; + } cases[] = { + { GGML_TYPE_F32, 1, 0, 1 }, + { GGML_TYPE_F32, 4096, 10000, 1 }, + { GGML_TYPE_F16, 1024, 10000, 1 }, + { GGML_TYPE_F32, 1 << 20, 5000, 4 }, + }; + + for (const auto & c : cases) { + switch (test_sleep(backend.get(), c.type, c.ne, c.us, c.n_nodes)) { + case TEST_OK: n_ok++; break; + case TEST_FAIL: n_fail++; break; + case TEST_SKIP: n_skip++; break; + } + } + } + + printf("%d passed, %d failed, %d skipped\n", n_ok, n_fail, n_skip); + + return n_fail > 0; +} From c7468107efba061fe83d32b17c91e2b5295677d4 Mon Sep 17 00:00:00 2001 From: Bhargav Krish Date: Thu, 19 Nov 2026 06:44:47 -0800 Subject: [PATCH 03/88] cuda: Scatter kernel for set_n (#32489) * cuda: add scatter for batched tensor writes * update test case to mirror get_n test case * save restore timing logs * refactor code into batch-copy.cu file --- .../ggml-cuda/{batch-get.cu => batch-copy.cu} | 109 +++++++++++------- .../{batch-get.cuh => batch-copy.cuh} | 4 + ggml/src/ggml-cuda/ggml-cuda.cu | 7 +- tests/test-backend-tensor.cpp | 34 ++++++ tools/server/server-context.cpp | 4 + tools/server/server-slot-sched.cpp | 4 + 6 files changed, 117 insertions(+), 45 deletions(-) rename ggml/src/ggml-cuda/{batch-get.cu => batch-copy.cu} (58%) rename ggml/src/ggml-cuda/{batch-get.cuh => batch-copy.cuh} (55%) diff --git a/ggml/src/ggml-cuda/batch-get.cu b/ggml/src/ggml-cuda/batch-copy.cu similarity index 58% rename from ggml/src/ggml-cuda/batch-get.cu rename to ggml/src/ggml-cuda/batch-copy.cu index 60c4747b967c..920b2b15d355 100644 --- a/ggml/src/ggml-cuda/batch-get.cu +++ b/ggml/src/ggml-cuda/batch-copy.cu @@ -1,17 +1,17 @@ -#include "batch-get.cuh" +#include "batch-copy.cuh" #include "common.cuh" #include "ggml-cpp.h" #include #if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) -struct ggml_cuda_batch_get_descriptor { +struct ggml_cuda_batch_copy_descriptor { const unsigned char * src; unsigned char * dst; size_t size; }; -static __global__ void ggml_cuda_batch_get_kernel(const ggml_cuda_batch_get_descriptor * copies, size_t count) { +static __global__ void ggml_cuda_batch_copy_kernel(const ggml_cuda_batch_copy_descriptor * copies, size_t count) { // Blocks along y cooperate on each descriptor. const size_t index = blockIdx.x; if (index >= count) { @@ -50,11 +50,11 @@ static __global__ void ggml_cuda_batch_get_kernel(const ggml_cuda_batch_get_desc } } -struct ggml_cuda_batch_get_mapping { +struct ggml_cuda_batch_copy_mapping { void * host = nullptr; unsigned char * device = nullptr; - ggml_cuda_batch_get_mapping(void * host, size_t size) { + ggml_cuda_batch_copy_mapping(void * host, size_t size) { const cudaError_t err = cudaHostRegister(host, size, cudaHostRegisterMapped | cudaHostRegisterPortable); if (err != cudaSuccess) { (void) cudaGetLastError(); @@ -70,10 +70,10 @@ struct ggml_cuda_batch_get_mapping { } } - ggml_cuda_batch_get_mapping(const ggml_cuda_batch_get_mapping &) = delete; - ggml_cuda_batch_get_mapping & operator=(const ggml_cuda_batch_get_mapping &) = delete; + ggml_cuda_batch_copy_mapping(const ggml_cuda_batch_copy_mapping &) = delete; + ggml_cuda_batch_copy_mapping & operator=(const ggml_cuda_batch_copy_mapping &) = delete; - ~ggml_cuda_batch_get_mapping() { + ~ggml_cuda_batch_copy_mapping() { if (host) { // Release only the registration acquired by this object. CUDA_CHECK(cudaHostUnregister(host)); @@ -82,11 +82,12 @@ struct ggml_cuda_batch_get_mapping { }; #endif -bool ggml_cuda_get_tensor_n(int device, - const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, +static bool ggml_cuda_copy_tensor_n(int device, cudaMemcpyKind direction, + const ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors) { #if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) GGML_UNUSED(device); + GGML_UNUSED(direction); GGML_UNUSED(tensors); GGML_UNUSED(data); GGML_UNUSED(offsets); @@ -94,14 +95,17 @@ bool ggml_cuda_get_tensor_n(int device, GGML_UNUSED(n_tensors); return false; #else + const bool to_host = direction == cudaMemcpyDeviceToHost; // Provisional dispatch values based on experiments. constexpr size_t min_batch_reads = 128; - constexpr size_t max_gather_read_bytes = 128 * 1024; - // Collect non-empty CPU destination ranges. + constexpr size_t max_kernel_read_bytes = 128 * 1024; + // Collect destination ranges; repeated sources are allowed. std::vector> ranges; ranges.reserve(n_tensors); size_t payload_bytes = 0; - // Number of non-empty reads whose size is at most max_gather_read_bytes. + uintptr_t begin = UINTPTR_MAX; + uintptr_t end = 0; + // Number of non-empty reads whose size is at most max_kernel_read_bytes. size_t n_reads_small = 0; for (size_t i = 0; i < n_tensors; ++i) { if (sizes[i] == 0) { @@ -111,15 +115,19 @@ bool ggml_cuda_get_tensor_n(int device, GGML_ASSERT(address <= UINTPTR_MAX - sizes[i]); GGML_ASSERT(payload_bytes <= SIZE_MAX - sizes[i]); payload_bytes += sizes[i]; - n_reads_small += sizes[i] <= max_gather_read_bytes; - ranges.emplace_back(address, address + sizes[i]); + n_reads_small += sizes[i] <= max_kernel_read_bytes; + begin = std::min(begin, address); + end = std::max(end, address + sizes[i]); + const uintptr_t destination = to_host ? address : (uintptr_t) tensors[i]->data + offsets[i]; + GGML_ASSERT(destination <= UINTPTR_MAX - sizes[i]); + ranges.emplace_back(destination, destination + sizes[i]); } if (ranges.empty()) { return true; } // Total number of non-empty reads. const size_t n_reads = ranges.size(); - if (n_reads > SIZE_MAX / sizeof(ggml_cuda_batch_get_descriptor) || n_reads > INT_MAX) { + if (n_reads > SIZE_MAX / sizeof(ggml_cuda_batch_copy_descriptor) || n_reads > INT_MAX) { return false; } if (n_reads < 2 || (n_reads < min_batch_reads && n_reads_small == n_reads)) { @@ -127,72 +135,85 @@ bool ggml_cuda_get_tensor_n(int device, } std::sort(ranges.begin(), ranges.end()); for (size_t i = 1; i < ranges.size(); ++i) { - // Preserve the ordered copy path when CPU destinations overlap. + // Preserve the ordered copy path when destinations overlap. if (ranges[i].first < ranges[i - 1].second) { return false; } } - // Find the CPU span to register, including gaps between destinations. - const uintptr_t begin = ranges.front().first; - const uintptr_t end = ranges.back().second; - if (end - begin - payload_bytes > payload_bytes) { + // Limit gaps in the CPU span without underflow when sources overlap. + if (end - begin > payload_bytes && end - begin - payload_bytes > payload_bytes) { return false; } - // Register and map the existing CPU destination so the kernel can write to it directly. - ggml_cuda_batch_get_mapping mapping((void *) begin, end - begin); + // Register and map the CPU span for direct kernel access. + ggml_cuda_batch_copy_mapping mapping((void *) begin, end - begin); if (!mapping.host) { return false; } - // Reads selected for gather; zero means all reads use DMA. - size_t n_reads_gather = mapping.device && n_reads_small >= min_batch_reads ? n_reads_small : 0; + // Reads selected for the kernel; zero means all reads use DMA. + size_t n_reads_kernel = mapping.device && n_reads_small >= min_batch_reads ? n_reads_small : 0; // Keep descriptor storage alive until the final stream synchronization. constexpr size_t max_batch_descriptors = 128 * 1024; - const size_t bytes = std::min(n_reads_gather, max_batch_descriptors) * sizeof(ggml_cuda_batch_get_descriptor); - ggml_backend_buffer_ptr descriptors(n_reads_gather ? ggml_backend_buft_alloc_buffer(ggml_backend_cuda_buffer_type(device), bytes) : nullptr); + const size_t bytes = std::min(n_reads_kernel, max_batch_descriptors) * sizeof(ggml_cuda_batch_copy_descriptor); + ggml_backend_buffer_ptr descriptors(n_reads_kernel ? ggml_backend_buft_alloc_buffer(ggml_backend_cuda_buffer_type(device), bytes) : nullptr); if (!descriptors) { - n_reads_gather = 0; + n_reads_kernel = 0; } const auto host_type = ggml_backend_cuda_host_buffer_type(); - ggml_backend_buffer_ptr host_descriptors(n_reads_gather ? ggml_backend_buft_alloc_buffer(host_type, bytes) : nullptr); + ggml_backend_buffer_ptr host_descriptors(n_reads_kernel ? ggml_backend_buft_alloc_buffer(host_type, bytes) : nullptr); if (!host_descriptors || ggml_backend_buffer_get_type(host_descriptors.get()) != host_type) { - n_reads_gather = 0; + n_reads_kernel = 0; } - if (n_reads_gather) { - auto * copies = static_cast(ggml_backend_buffer_get_base(host_descriptors.get())); - auto * device_copies = static_cast(ggml_backend_buffer_get_base(descriptors.get())); + if (n_reads_kernel) { + auto * copies = static_cast(ggml_backend_buffer_get_base(host_descriptors.get())); + auto * device_copies = static_cast(ggml_backend_buffer_get_base(descriptors.get())); const int threads = 256; const size_t nsm = ggml_cuda_info().devices[device].nsm; size_t i = 0; - for (size_t first = 0; first < n_reads_gather; first += max_batch_descriptors) { - const size_t n_batch = std::min(n_reads_gather - first, max_batch_descriptors); + for (size_t first = 0; first < n_reads_kernel; first += max_batch_descriptors) { + const size_t n_batch = std::min(n_reads_kernel - first, max_batch_descriptors); size_t count = 0; for (; i < n_tensors && count < n_batch; ++i) { - if (sizes[i] == 0 || sizes[i] > max_gather_read_bytes) { + if (sizes[i] == 0 || sizes[i] > max_kernel_read_bytes) { continue; } - copies[count++] = {(const unsigned char *) tensors[i]->data + offsets[i], - mapping.device + ((uintptr_t) data[i] - begin), sizes[i]}; + auto * host = mapping.device + ((uintptr_t) data[i] - begin); + auto * tensor = (unsigned char *) tensors[i]->data + offsets[i]; + copies[count++] = {to_host ? tensor : host, to_host ? host : tensor, sizes[i]}; } const size_t blocks_per_copy = std::min(UINT16_MAX, std::max(1, (nsm + n_batch - 1) / n_batch)); const dim3 blocks((unsigned int) n_batch, (unsigned int) blocks_per_copy); // Stream ordering keeps each kernel ahead of the next descriptor overwrite. CUDA_CHECK(cudaMemcpyAsync(device_copies, copies, n_batch * sizeof(copies[0]), cudaMemcpyHostToDevice, cudaStreamPerThread)); - ggml_cuda_batch_get_kernel<<>>(device_copies, n_batch); + ggml_cuda_batch_copy_kernel<<>>(device_copies, n_batch); CUDA_CHECK(cudaGetLastError()); - if (first + n_batch < n_reads_gather) { + if (first + n_batch < n_reads_kernel) { // Wait before refilling the pinned host descriptor buffer. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); } } } - // Keep the destination pinned for DMA too; overlapping destinations already declined above. + // Keep the CPU span pinned for DMA too; overlapping destinations already declined above. for (size_t i = 0; i < n_tensors; ++i) { - if (sizes[i] && (!n_reads_gather || sizes[i] > max_gather_read_bytes)) { - CUDA_CHECK(cudaMemcpyAsync(data[i], (const char *) tensors[i]->data + offsets[i], sizes[i], cudaMemcpyDeviceToHost, cudaStreamPerThread)); + if (sizes[i] && (!n_reads_kernel || sizes[i] > max_kernel_read_bytes)) { + void * host = const_cast(data[i]); + void * tensor = (char *) tensors[i]->data + offsets[i]; + CUDA_CHECK(cudaMemcpyAsync(to_host ? host : tensor, to_host ? tensor : host, sizes[i], direction, cudaStreamPerThread)); } } - // Wait for GPU writes before releasing the CPU mapping and descriptor buffers. + // Wait for transfers before releasing the CPU mapping and descriptor buffers. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); return true; #endif } + +bool ggml_cuda_get_tensor_n(int device, + const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, + const size_t * sizes, size_t n_tensors) { + return ggml_cuda_copy_tensor_n(device, cudaMemcpyDeviceToHost, tensors, data, offsets, sizes, n_tensors); +} + +bool ggml_cuda_set_tensor_n(int device, + ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, + const size_t * sizes, size_t n_tensors) { + return ggml_cuda_copy_tensor_n(device, cudaMemcpyHostToDevice, tensors, data, offsets, sizes, n_tensors); +} diff --git a/ggml/src/ggml-cuda/batch-get.cuh b/ggml/src/ggml-cuda/batch-copy.cuh similarity index 55% rename from ggml/src/ggml-cuda/batch-get.cuh rename to ggml/src/ggml-cuda/batch-copy.cuh index eb9bf0cc81bd..bb7fca4c02dd 100644 --- a/ggml/src/ggml-cuda/batch-get.cuh +++ b/ggml/src/ggml-cuda/batch-copy.cuh @@ -5,3 +5,7 @@ bool ggml_cuda_get_tensor_n(int device, const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors); + +bool ggml_cuda_set_tensor_n(int device, + ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, + const size_t * sizes, size_t n_tensors); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index c6622d1b38bb..2ce3d0b809c6 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -10,7 +10,7 @@ #include "ggml-cuda/arange.cuh" #include "ggml-cuda/argmax.cuh" #include "ggml-cuda/argsort.cuh" -#include "ggml-cuda/batch-get.cuh" +#include "ggml-cuda/batch-copy.cuh" #include "ggml-cuda/binbcast.cuh" #include "ggml-cuda/clamp.cuh" #include "ggml-cuda/col2im-1d.cuh" @@ -1117,6 +1117,11 @@ static void ggml_backend_cuda_buffer_set_tensor_n(ggml_backend_buffer_t buffer, ggml_cuda_set_device(ctx->device); + if (!ggml_cuda_pinned_memory_disabled() && + ggml_cuda_set_tensor_n(ctx->device, tensors, data, offsets, sizes, n_tensors)) { + return; + } + for (size_t i = 0; i < n_tensors; i++) { if (sizes[i] == 0) { continue; diff --git a/tests/test-backend-tensor.cpp b/tests/test-backend-tensor.cpp index 9685bc277789..ed617939d2ea 100644 --- a/tests/test-backend-tensor.cpp +++ b/tests/test-backend-tensor.cpp @@ -170,6 +170,40 @@ static bool test_tensor_n(ggml_backend_buffer_type_t buft) { } } + { + std::vector batch; + ggml_backend_buffer_ptr scatter_buf = alloc_tensors(ctx.get(), buft, { 64 }, batch); + if (!scatter_buf) { + return false; + } + batch.resize(128, batch[0]); + uint8_t input[32], expected[256], out[256]; + for (size_t i = 0; i < sizeof(input); i++) { + input[i] = (uint8_t) (i + 1); + } + std::vector offsets(batch.size()), sizes(batch.size(), 1), data_offsets(batch.size()); + for (bool overlap : { false, true }) { + memset(expected, 0, sizeof(expected)); + ggml_backend_tensor_set(batch[0], expected, 0, sizeof(expected)); + for (size_t i = 0; i < batch.size(); i++) { + offsets[i] = 2*((i*5) % batch.size()) + 1; + data_offsets[i] = i % sizeof(input); + } + // Repeated sources are valid; overlapping destinations must retain copy order. + if (overlap) { + offsets.back() = offsets.front(); + } + for (size_t i = 0; i < batch.size(); i++) { + expected[offsets[i]] = input[data_offsets[i]]; + } + ggml_backend_tensor_set_n(batch.data(), input, offsets.data(), sizes.data(), data_offsets.data(), batch.size()); + ggml_backend_tensor_get(batch[0], out, 0, sizeof(out)); + if (memcmp(out, expected, sizeof(out)) != 0) { + return false; + } + } + } + return true; } diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 36082df89d7a..f821ac6cb2a3 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -353,6 +353,8 @@ struct server_slot { return false; } + const int64_t t_start = ggml_time_us(); + const size_t cur_size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); const size_t cur_size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; @@ -374,6 +376,8 @@ struct server_slot { return false; } + SLT_TRC(*this, "prompt cache save took %.2f ms\n", (ggml_time_us() - t_start) / 1000.0); + return true; } diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp index 5f8aa5c33e2c..9f977934828f 100644 --- a/tools/server/server-slot-sched.cpp +++ b/tools/server/server-slot-sched.cpp @@ -208,6 +208,8 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok if (it_best != states.end()) { SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + const int64_t t_start = ggml_time_us(); + { auto & data = it_best->data.main; @@ -252,6 +254,8 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok prompt = std::move(it_best->prompt); states.erase(it_best); + + SRV_TRC("slot %d: prompt cache restore took %.2f ms\n", id_slot, (ggml_time_us() - t_start) / 1000.0); } return true; From 9a080f44b503c64f66c84a6274b9d9ee5d5b09d5 Mon Sep 17 00:00:00 2001 From: Ravi Panchumarthy Date: Thu, 19 Nov 2026 07:22:26 -0800 Subject: [PATCH 04/88] ggml-openvino: fix OpenVINO CI, minor fixes and optimizations (#32590) * ggml-openvino: round the GPU KV length up to a power of two Review notes (follow-ups, not blocking): - convert_ggml_input_to_ov pads the KQ mask into a std::vector and then copies it into the ov::Tensor. Writing the padded rows straight into padded.data() avoids the second allocation and copy (up to 16 MB per call at a 16K context). - The padding is skipped when the mask is not contiguous, and the KV inputs are then sliced to more rows than the mask has columns. Masks are always contiguous today; a GGML_ASSERT would make that explicit. - compute_llm_params reads GGML_OPENVINO_STATEFUL_EXECUTION directly; is_stateful_enabled() is local to ggml-openvino.cpp. * ggml-openvino: Optimize model recompiles of prefill stage Optimize the model recompiles of prefill stage when attended size changed between prompts. This can save model recompile time for llama-bench and llama-server. * ggml-openvino: Optimize model recompiles of prefill stage Optimize the model recompiles of prefill stage when attended size changed between prompts. This can save model recompile time for llama-bench and llama-server. * ggml-openvino: Remove solution C and keep A as default * ggml-openvino: match the output count before reusing a compiled NPU prefill The static prefill model has a fixed inp_out_ids shape [1,1,1,output_len]. The new reuse check compared only the attention sizes, so llama-perplexity, which alternates 1 and 512 outputs per ubatch, reused the model compiled for 512 outputs on a 1-output ubatch and failed with "got [1,1,1,1] expecting [1,1,1,512]". Store the output count of the cached prefill model and require it to match. * ggml-openvino: Fix LFM2 context create on GPU and DSpark speculative decoding * ggml-openvino: remove leftovers from merging dev into the LFM2/DSpark fix - compute_model_outputs exported OUTPUT-flagged nodes twice: dev's block ran before the new one and still exported result_norm, so the result_norm exclusion had no effect. Keep only the new block. - compute_node_dynamic_dims checked is_activation_input twice in a row. Remove the second copy. - process_view_input_new created the dynamic Split on split_dim. With stateful execution the input drops the leading size-1 axis, so use split_axis, which already accounts for the rank difference. * ggml-openvino: hash the output flags into the model-cache fingerprint The fingerprint hashed the ops, names and weights but not the outputs, so a blob compiled with another output set was imported. With the result_norm change, an NPU blob written before it gave wrong output, and enabling llama_set_embeddings_layer_inp() reused a blob without the layer-input outputs. Hash each node's output flag and bump the cache version to 8. * ggml-openvino: support f16 SCALE and f16/bf16 TRI test-backend-ops now runs SCALE on f16 and TRI on f16 and bf16. Both translators built their constants as f32, and Multiply, Add and Select need all inputs in one element type, so building the graph threw for these cases. SCALE now converts a non-f32 input to f32, applies the scale and bias, and converts back once, as the CPU backend computes it. TRI creates its zero constant in the input's element type. f32 graphs are unchanged. * ggml-openvino: [Qwen3.6 A3B]fix static-shape ids view of the last MoE layer The same-stride single-dim Slice in process_view_input_new was followed by a Reshape whose target baked the static chunk size into the token axis. After the output-ids GET_ROWS the last layer runs on n_outputs tokens (1 in the prefill graph), so the Reshape failed shape validation for qwen35moe with FORCE_STATIC or on the NPU. Skip the Reshape in static graphs when the slice already keeps the rank; the dynamic graphs are unchanged. * enable mamba based models on OV CPU-GPU * revert changes in tests * docs : add Falcon-H1 to the OpenVINO validated models Falcon-H1 runs on CPU and GPU since Mamba SSM support was added. Add its row and the known limitations: multi-sequence batches fail, GPU accuracy is slightly lower than CPU, and the NPU fails with an element type mismatch. * ggml-openvino: simplify the SSM_SCAN build check and clean up - Drop the SelectiveSSM configure check and its guards: OpenVINO 2026.4.1 always provides the op. Drop the no-op LANGUAGE CXX source property. - Drop the semicolon after OPENVINO_OP("SelectiveSSM"). GCC 15 reports it with -Wextra-semi, which fails builds with fatal warnings. - Add ggml_openvino_is_static() for the repeated NPU or GGML_OPENVINO_FORCE_STATIC check. - Share the f16 and f32 KQ mask padding code. - Drop the redundant inline on in-class static functions. --------- Co-authored-by: Suhas Somashekar Co-authored-by: yzhou51 Co-authored-by: Ananth, Swathi Co-authored-by: Beheshti --- docs/backend/OPENVINO.md | 3 + ggml/src/ggml-openvino/ggml-decoder.cpp | 79 ++++++++++-- ggml/src/ggml-openvino/ggml-decoder.h | 66 +++++++++- .../src/ggml-openvino/ggml-openvino-extra.cpp | 4 + ggml/src/ggml-openvino/ggml-openvino-extra.h | 3 + ggml/src/ggml-openvino/ggml-openvino.cpp | 55 ++++++++- ggml/src/ggml-openvino/model-cache.cpp | 8 +- ggml/src/ggml-openvino/openvino/op/cpy.cpp | 22 ++++ ggml/src/ggml-openvino/openvino/op/scale.cpp | 18 ++- .../openvino/op/selective_ssm.hpp | 42 +++++++ .../ggml-openvino/openvino/op/set_rows.cpp | 59 +++++++++ .../ggml-openvino/openvino/op/ssm_scan.cpp | 63 ++++++++++ ggml/src/ggml-openvino/openvino/op/tri.cpp | 3 +- ggml/src/ggml-openvino/openvino/op_table.cpp | 1 + ggml/src/ggml-openvino/openvino/op_table.h | 1 + ggml/src/ggml-openvino/openvino/utils.cpp | 113 ++++++++++++++++-- ggml/src/ggml-openvino/openvino/utils.h | 3 + ggml/src/ggml-openvino/utils.cpp | 49 +++++++- ggml/src/ggml-openvino/utils.h | 9 +- 19 files changed, 558 insertions(+), 43 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp create mode 100644 ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 0b5615ca2460..a3a94aa16fb6 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -195,6 +195,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C | [bartowski/prism-ml_Bonsai-8B-unpacked-Q4_K_M](https://huggingface.co/bartowski/prism-ml_Bonsai-8B-unpacked-GGUF) | ✓ | ✓ | ✓ | | [LiquidAI/LFM2.5-2.6B-Q4_K_M](https://huggingface.co/LiquidAI/LFM2.5-2.6B-GGUF) | ✓ | ✓ | ✗ | | [bartowski/inclusionAI_Ling-mini-2.0-Q4_K_M](https://huggingface.co/bartowski/inclusionAI_Ling-mini-2.0-GGUF) | ✓ | ✓ | ✗ | +| [tiiuae/Falcon-H1-0.5B-Instruct-Q4_K_M](https://huggingface.co/tiiuae/Falcon-H1-0.5B-Instruct-GGUF) | ✓ | ✓ | ✗ | | | | | | | [Qwen/Qwen3-Embedding-0.6B-Q8_0](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF) | ✓ | ✓ | ✗ | | [ggml-org/bge-m3-Q8_0](https://huggingface.co/ggml-org/bge-m3-Q8_0-GGUF) | ✓ | ✓ | ✗ | @@ -990,6 +991,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - Multimodal features (audio/image/video) are a work in progress. - Embedding models: reranking models are not validated. - Llama.cpp tool coverage across CPU/GPU/NPU is not uniform. +- Mamba-based models (e.g. Falcon-H1): `llama-perplexity` with several sequences per batch fails; set `-b` to the same value as `-c`. GPU accuracy is slightly lower than CPU. **GPU-specific** @@ -1012,6 +1014,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - `llama-perplexity`: requires `-b 512` or smaller. - Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU. - `llama-embedding` fails on the NPU. +- Mamba-based models (e.g. Falcon-H1) fail on the NPU with `Failed to set tensor` (element type mismatch). - Lunar Lake NPU: decode slows down sharply when the context is large. The context size at which this starts depends on the model. - **Workaround:** Pass the smallest context that fits the use, e.g. `-c 512`, or `-c 256` for larger models. - Panther Lake NPU: the load of a Qwen3.5 model can end with a segmentation fault in the NPU compiler of OpenVINO 2026.4.1. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 38db895c532f..519c35bc21a1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -107,7 +107,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, std::mapn_nodes; ++i) { if ((cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET && cgraph->nodes[i]->op_params[0] > 1) || - is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i])) { + is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i]) || + is_ssm_state_writeback(cgraph->nodes[i])) { std::tie(m_model_params, m_compute_params) = compute_llm_params(cgraph, false); add_extra_inputs(); break; @@ -494,6 +495,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } } else if (node->ne[0] == 1 && src->ne[0] * src->ne[1] * src->ne[2] == node->ne[1]) { op_case = 3; + } else if (node->ne[0] * node->ne[1] == src->ne[0] * src->ne[1] && node->ne[2] == src->ne[2] && + node->ne[3] == src->ne[3]) { + // head regroup, e.g. mamba2's [head_dim, n_head, n_tokens, n_seqs] -> [d_inner/n_group, n_group, n_tokens, n_seqs] + op_case = 1; } else if (name.find("linear_attn_qkv_mixed") == 0 || name.find("alpha") == 0) { op_case = 6; } else if (name.find("linear_attn_out") == 0) { @@ -597,6 +602,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { op_case = 3; break; } + if (is_column_set_rows(node)) { + op_case = 4; + break; + } // `-fa off` writes the V cache transposed, through a [1, n] reshape of the cache: one element per row if (node->src[2] != nullptr && node->src[2]->op == GGML_OP_RESHAPE && node->src[2]->ne[0] == 1 && is_kvcache(node->src[2]->src[0], nullptr)) { @@ -797,6 +806,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } else { op_case = 1; } + } else if (is_ssm_state_writeback(node)) { + op_case = 13; + break; } else if (GgmlOvDecoder::is_conv_state_writeback(node)) { op_case = 2; break; @@ -1296,6 +1308,11 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr writeback.snapshot_stride = destination->nb[2] / destination->nb[1]; compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; } + if (is_ssm_state_writeback(node)) { + ComputeParams::RsWriteback writeback; + writeback.slot_begin = (int64_t) (node->src[1]->view_offs / node->src[1]->nb[1]); + compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; + } if (is_conv_state_snapshot_writeback(node)) { const auto source = node->src[0]; const auto dest = node->src[2]; @@ -1406,6 +1423,14 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr compute_params.attention_size = ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq); } + // The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of + // 256. Round it up to a power of two the same way, so that a long context uses a few lengths and not one per + // step. The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov). + if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && + !compute_params.mask_name.empty() && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) { + compute_params.attention_size = + ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq); + } model_params.ctx = model_params.ctx_per_seq * model_params.n_seq; return {model_params, compute_params}; } @@ -1416,6 +1441,15 @@ void GgmlOvDecoder::validate_cgraph() const { } } +bool GgmlOvDecoder::has_inp_embd_leaf_use(const ggml_tensor * tensor) const { + for (int i = 0; i < m_cgraph->n_nodes; i++) { + if (is_inp_embd_leaf(tensor, m_cgraph->nodes[i])) { + return true; + } + } + return false; +} + ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, const ggml_tensor * input, int dynamic_dim_index) const { @@ -1530,7 +1564,7 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, // index list has a static length; on CPU/GPU it may change across compiles (defrag). input_shape = m_is_static ? ov::PartialShape{get_shape(input)} : ov::PartialShape{1, 1, 1, -1}; - } else if (input != nullptr && op != nullptr && is_inp_emb(input, op)) { + } else if (input != nullptr && op != nullptr && (is_inp_emb(input, op) || has_inp_embd_leaf_use(input))) { input_shape = ov::PartialShape{get_shape(input)}; if (!m_is_static) { input_shape[2] = -1; @@ -1914,7 +1948,11 @@ void GgmlOvDecoder::compute_model_outputs() { continue; } const bool inactive_top_k = is_sampling_top_k(cur_node) && !(cur_node->flags & GGML_TENSOR_FLAG_COMPUTE); - if ((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) || inactive_top_k) { + auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; + // llama flags result_norm in every graph but reads it only with embeddings on, when it has no consumer + // and is kept by the rule below. + const bool unread_embd = strcmp(cur_node->name, "result_norm") == 0 && cur_node_use_count > 0; + if (((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) && !unread_embd) || inactive_top_k) { const auto name = get_tensor_ov_name(m_cgraph, cur_node); m_model_outputs[name] = cur_node; m_model_output_names.insert(name); @@ -1925,7 +1963,12 @@ void GgmlOvDecoder::compute_model_outputs() { m_model_outputs[name] = cache; m_model_output_names.insert(name); } - auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; + if (is_ssm_state_writeback(cur_node)) { + auto * cache = cur_node->view_src; + const auto name = get_tensor_ov_name(m_cgraph, cache); + m_model_outputs[name] = cache; + m_model_output_names.insert(name); + } if (cur_node_use_count == 0) { // The output of in-place ops is the view_src tensor, which is updated in place. We should use the view_src name as the output name to make sure it can be correctly matched with the later ops that use the view_src. if (cur_node != nullptr && ::is_inplace_op(cur_node) && @@ -2641,6 +2684,10 @@ bool GgmlOvDecoder::is_direct_gdn_view(const ggml_tensor * node) const { std::vector GgmlOvDecoder::get_output_names(int node_idx) const { auto * node = m_node_info_list[node_idx].node; + if (is_ssm_state_writeback(node)) { + // the written state block plus the full updated cache (see translate_cpy op_case 13) + return {m_node_info_list[node_idx].node_name, get_tensor_ov_name(m_cgraph, node->view_src)}; + } if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) { std::string attn_name; std::string state_name; @@ -2669,6 +2716,10 @@ std::vector GgmlOvDecoder::get_output_names(int node_idx) const { std::string GgmlOvDecoder::get_inplace_op_src(int node_idx) const { auto * node = m_node_info_list[node_idx].node; + if (is_ssm_state_writeback(node)) { + // translate_cpy publishes the updated cache as a second named output + return ""; + } // Reset lengths (also in static mode) and dynamic remainder views can become nonempty // after compilation. Keep their alias updates in the translated cache chain. const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(node->view_src) && @@ -2786,7 +2837,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[src] = 0; continue; } - if (is_inp_scale_rows(src, node)) { + if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) { m_node_dynamic_dims[src] = 1; continue; } @@ -2865,6 +2916,11 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[node] = 2; break; } + if (node->src[0]->op == GGML_OP_SSM_SCAN) { + // y part [head_dim, n_head, n_tokens, n_seqs] at offset 0; the state part is token-independent + m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1; + break; + } // Use stride-based matching: the stride of a VIEW dimension directly // encodes which source dimension it indexes into, so it uniquely // identifies the dynamic dim even when two dims share the same size. @@ -3030,6 +3086,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_GATED_DELTA_NET: m_node_dynamic_dims[node] = 1; break; + case GGML_OP_SSM_SCAN: + // packed 1-D [y | state]; the y part grows with tokens + m_node_dynamic_dims[node] = 0; + break; case GGML_OP_RMS_NORM: case GGML_OP_L2_NORM: case GGML_OP_NORM: @@ -3080,12 +3140,15 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_CPY: case GGML_OP_SUM: case GGML_OP_MEAN: + case GGML_OP_ARANGE: m_node_dynamic_dims[node] = -1; break; case GGML_OP_SET_ROWS: - // a cache write returns the cache; other rows writes keep the shape of their destination - m_node_dynamic_dims[node] = (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node)) ? - -1 : m_node_dynamic_dims[node->src[2]]; + // a cache or column write returns its whole buffer; other rows writes keep the shape of their destination + m_node_dynamic_dims[node] = + (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node) || is_column_set_rows(node)) ? + -1 : + m_node_dynamic_dims[node->src[2]]; break; case GGML_OP_IM2COL: { m_node_dynamic_dims[node] = -1; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index b7ff4b715f06..12b08cebce4b 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -477,6 +477,21 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { return tensor->op == GGML_OP_GET_ROWS && op->op == GGML_OP_RMS_NORM; } + // Raw float input [n_embd, n_tokens]: DFlash/DSpark/EAGLE3 features into fc, or raw embd batch / EAGLE3 g-embd into RMS_NORM + // MUL_MAT needs a weight leaf as src[0], so inp_mean (src[0] is computed) does not match + static bool is_inp_embd_leaf(const ggml_tensor * tensor, const ggml_tensor * op) { + if (tensor->op != GGML_OP_NONE || !(tensor->flags & GGML_TENSOR_FLAG_INPUT) || tensor->type != GGML_TYPE_F32) { + return false; + } + if (op->op == GGML_OP_MUL_MAT) { + return op->src[1] == tensor && op->src[0] != nullptr && op->src[0]->op == GGML_OP_NONE; + } + return op->op == GGML_OP_RMS_NORM && op->src[0] == tensor; + } + + // true if any node of the current graph uses tensor as a raw embd input (see is_inp_embd_leaf) + bool has_inp_embd_leaf_use(const ggml_tensor * tensor) const; + static bool is_activation_input(const ggml_tensor * tensor, const ggml_tensor * op) { if (tensor == nullptr || op == nullptr || tensor->type != GGML_TYPE_F32 || tensor->ne[2] != 1 || tensor->ne[3] != 1 || (tensor->buffer != nullptr && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { @@ -578,11 +593,11 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { bool is_direct_gdn_view(const ggml_tensor * node) const; - inline static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { + static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { return is_recurrent_cache(tensor) || is_kvcache(tensor, op); } - inline static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) { + static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) { if (tensor == nullptr || is_recurrent_cache(tensor)) { return false; } @@ -590,27 +605,68 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { (op != nullptr && op->op == GGML_OP_SET_ROWS && op->src[2] == tensor); } - inline static bool is_conv_state_writeback(const ggml_tensor * node) { + static bool is_conv_state_writeback(const ggml_tensor * node) { return node->op == GGML_OP_CPY && node->view_src != nullptr && is_recurrent_cache(node->view_src) && node->src[0] != nullptr && node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr && node->src[0]->src[0]->op == GGML_OP_CONCAT && node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src; } + // The final-state writeback of SSM_SCAN (K == 1): the state tail of the packed [y | state] + // output copied into a slot block of the recurrent cache. + static bool is_ssm_state_writeback(const ggml_tensor * node) { + if (!(node != nullptr && node->op == GGML_OP_CPY && node->view_src != nullptr && node->src[0] != nullptr && + node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr && + node->src[0]->src[0]->op == GGML_OP_SSM_SCAN && node->src[0]->src[0]->op_params[0] == 1 && + node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && + node->src[1]->view_src == node->view_src)) { + return false; + } + const auto * scan = node->src[0]->src[0]; + const auto * src = node->src[0]; + const auto * dst = node->src[1]; + if (node->type != GGML_TYPE_F32 || src->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || + src->ne[2] != 1 || src->ne[3] != 1) { + return false; + } + for (int i = 0; i < GGML_MAX_DIMS; ++i) { + if (src->ne[i] != dst->ne[i]) { + return false; + } + } + return dst->nb[1] > 0 && dst->view_offs % dst->nb[1] == 0 && + src->view_offs == (size_t) ggml_nelements(scan->src[1]) * ggml_type_size(scan->type); + } + // build_conv_state_store writes overlapping [history, window, channel, seq] windows into newest-first rollback planes. // Match this layout separately from general SET_ROWS. static bool is_conv_state_snapshot_writeback(const ggml_tensor * node); + // SET_ROWS into a column range of each row of a plain 2-D buffer, e.g. build_layer_inp_dev(): every enabled layer + // input goes to view_2d(layer_inp_dev, n_embd, n_batch, nb1, col * n_embd * elem) at the batch rows of the ubatch. + // The buffer sits in a regular device buffer, so is_kvcache() matches it: check this first + static bool is_column_set_rows(const ggml_tensor * node) { + if (node == nullptr || node->op != GGML_OP_SET_ROWS || node->src[2] == nullptr || + node->src[2]->op != GGML_OP_VIEW) { + return false; + } + const ggml_tensor * dst = node->src[2]; + const ggml_tensor * buf = dst->view_src; + return buf != nullptr && buf->op == GGML_OP_NONE && !is_recurrent_cache(buf) && buf->ne[2] == 1 && + buf->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && dst->ne[0] < buf->ne[0] && + dst->nb[0] == buf->nb[0] && dst->nb[1] == buf->nb[1] && dst->ne[1] == buf->ne[1]; + } + // SET_ROWS into a KV cache, directly or through the [1, n] reshape of the transposed V cache with `-fa off`. // Other SET_ROWS write rows of a compute tensor, e.g. the MoE expert-group mask - inline static bool is_kvcache_write(const ggml_tensor * node) { + static bool is_kvcache_write(const ggml_tensor * node) { const ggml_tensor * dst = node->src[2]; return dst != nullptr && is_kvcache(dst->view_src != nullptr ? dst->view_src : dst, nullptr); } // GET_ROWS batched over ggml dims 2 and 3, e.g. the MoE expert-group scores // ggml_get_rows(ggml_reshape_4d(groups, 1, n_exp_per_group, n_groups, n_tokens), top_groups) - inline static bool is_get_rows_batched_4d(const ggml_tensor * node) { + static bool is_get_rows_batched_4d(const ggml_tensor * node) { return node->op == GGML_OP_GET_ROWS && !ggml_is_quantized(node->src[0]->type) && node->src[1]->ne[1] == node->src[0]->ne[2] && node->src[1]->ne[2] == node->src[0]->ne[3] && node->src[1]->ne[3] == 1; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index c76b423983f3..2537f8af3a31 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -616,6 +616,10 @@ bool ggml_openvino_is_npu() { return ggml_openvino_get_device_config().is_npu; } +bool ggml_openvino_is_static() { + return ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"); +} + bool ggml_openvino_is_gpu() { return has_prefix(ggml_openvino_get_device_name(), "GPU"); } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 5a64c67ef9c5..406ac6d4cb5a 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -134,6 +134,9 @@ bool ggml_openvino_release_weights_enabled(); // Check if running on NPU bool ggml_openvino_is_npu(); +// Static graphs: NPU, or any device with GGML_OPENVINO_FORCE_STATIC +bool ggml_openvino_is_static(); + // KV-cache slicing: bind the KV cache, and size the KQ masks, at the attended length instead of the full context. // One mechanism, two modes: // dynamic graphs (CPU/GPU): the KV input is a view over the cache; the graph is not recompiled. diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index a7f5d177f527..98f22cfd7a51 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1504,6 +1504,38 @@ static bool has_strides_on_element_grid(const ggml_tensor * t) { return true; } +// A VIEW that regroups one contiguous span of every row of its contiguous source, e.g. the z/x/B/C +// splits of the fused mamba projections. The strides do not nest on an element grid, but +// process_view_input_new resolves it as a Slice of the source's innermost axis plus a Reshape. +// Keep in sync with the matching branch there; dynamic execution only. +static bool is_row_span_view(const ggml_tensor * t) { + if (ggml_openvino_is_static() || is_stateful_enabled()) { + return false; + } + const ggml_tensor * src = t->op == GGML_OP_VIEW ? t->src[0] : nullptr; + // a RESHAPE source is fine (the translation reads its value); a chained VIEW is not, because + // the view metadata then describes the intermediate view instead of the resolved input + if (src == nullptr || src->op == GGML_OP_VIEW || !ggml_is_contiguous(src) || t->type != src->type) { + return false; + } + const size_t es = ggml_type_size(t->type); + int d = 0; + size_t span = 1; + while (d < GGML_MAX_DIMS && t->nb[d] == span * es) { + span *= t->ne[d]; + d++; + } + if (d < 2) { + return false; + } + for (int s = 1; d < GGML_MAX_DIMS; ++d, ++s) { + if (t->ne[d] != src->ne[s] || t->nb[d] != src->nb[s]) { + return false; + } + } + return t->view_offs % es == 0 && t->view_offs / es + span <= (size_t) src->ne[0]; +} + static bool has_non_contiguous_view_input(const ggml_tensor * op) { for (int i = 0; i < GGML_MAX_SRC; i++) { if (op->src[i] == nullptr) { @@ -1624,7 +1656,7 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) { } return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op) || - GgmlOvDecoder::is_gdn_snapshot_writeback(op); + GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op); } static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) { @@ -1727,8 +1759,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } case GGML_OP_GET_ROWS: case GGML_OP_SET_ROWS: { - if (GgmlOvDecoder::is_conv_state_snapshot_writeback(op) && - (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"))) { + if (GgmlOvDecoder::is_conv_state_snapshot_writeback(op) && ggml_openvino_is_static()) { return {false, "convolution snapshots require dynamic execution"}; } if (op->ne[3] != 1 && !GgmlOvDecoder::is_get_rows_batched_4d(op) && @@ -2034,7 +2065,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported"; } else if (op->op_params[0] > 1) { - if (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC")) { + if (ggml_openvino_is_static()) { reason = "GATED_DELTA_NET snapshots require dynamic execution"; } } @@ -2053,6 +2084,19 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { // return true; break; } + case GGML_OP_SSM_SCAN: { + // SelectiveSSM implements the Mamba-2 recurrence: scalar decay per head, one final state + if (op->src[3]->ne[0] != 1) { + return {false, "SSM_SCAN with Mamba-1 state-wise decay is not supported"}; + } + if (op->op_params[0] > 1) { + return {false, "SSM_SCAN with rollback snapshots (K > 1) is not supported"}; + } + if (ggml_openvino_is_static()) { + return {false, "SSM_SCAN requires dynamic execution"}; + } + break; + } case GGML_OP_VIEW: { // Skip TOPK_MOE fused tests until it is fully supported. // The argsort_top_k VIEW wrapping ARGSORT is named "selected_experts" in test_topk_moe. @@ -2274,7 +2318,8 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg if (supported_types.find(src->type) == supported_types.end()) { return {false, "src[" + std::to_string(i) + "] type " + std::string(ggml_type_name(src->type)) + " is not supported"}; } - if (!has_strides_on_element_grid(src) && !(i == 1 && GgmlOvDecoder::is_gdn_snapshot_writeback(op)) && + if (!has_strides_on_element_grid(src) && !is_row_span_view(src) && + !(i == 1 && GgmlOvDecoder::is_gdn_snapshot_writeback(op)) && !(i == 2 && GgmlOvDecoder::is_conv_state_snapshot_writeback(op))) { return {false, "src[" + std::to_string(i) + "] strides are not multiples of each other"}; } diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 597233d7e6d9..7bfa7ad08b11 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -197,8 +197,7 @@ void ggml_openvino_model_cache_init() { } return; } - if (cache_only && (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC") || - ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE") || + if (cache_only && (ggml_openvino_is_static() || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE") || ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_FALLBACK"))) { GGML_ABORT("ggml-openvino: cache-only mode requires dynamic CPU/GPU execution with caching and without fallback"); } @@ -368,7 +367,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 5 requantizes K-quant MoE experts to Q4_1_64 on GPU by default. // Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive. // Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter. - h = fnv1a_u64(h, 7); + // Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags. + h = fnv1a_u64(h, 8); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); @@ -391,6 +391,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, const ggml_tensor * node = cgraph->nodes[i]; h = fnv1a_u64(h, static_cast(node->op)); h = fnv1a(h, node->name, strlen(node->name)); + // Each output is a Result of the model; llama_set_embeddings_layer_inp() changes only the flags. + h = fnv1a_u64(h, (node->flags & GGML_TENSOR_FLAG_OUTPUT) ? 1u : 0u); has_gdn = has_gdn || node->op == GGML_OP_GATED_DELTA_NET; } if (has_gdn && ggml_openvino_is_npu()) { diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp index 0bb6bd054d15..e0d63ac95179 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -75,6 +75,28 @@ OutputVector translate_cpy(const NodeContext & context) { return rename_outputs_with_suffix({result}, context.get_name()); } + if (op_case == 13) { + // SSM_SCAN final-state writeback: output the written state block and the full updated cache + auto src = process_view_input_new(context, 0); + auto base = context.get_input(1); + if (src.get_element_type() != context.get_output_type()) { + src = std::make_shared(src, context.get_output_type()); + } + auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0}); + auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1}); + auto int_max = ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX}); + auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {2}); + auto begin = context.get_input("rs_slot_begin_" + context.get_name()); + auto src_len = std::make_shared( + std::make_shared(src, ov::element::i64), axis, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto end = std::make_shared(begin, src_len); + auto head_part = std::make_shared(base, zero, begin, one, axis); + auto tail_part = std::make_shared(base, end, int_max, one, axis); + auto updated = std::make_shared(ov::OutputVector{head_part, src, tail_part}, 2); + return rename_outputs_with_suffix({src, updated}, context.get_name()); + } + if (op_case == 4) { auto src = process_view_input_new(context, 0); auto base = context.get_input(1); diff --git a/ggml/src/ggml-openvino/openvino/op/scale.cpp b/ggml/src/ggml-openvino/openvino/op/scale.cpp index f77d8ce58a6e..e0d0ea182c19 100644 --- a/ggml/src/ggml-openvino/openvino/op/scale.cpp +++ b/ggml/src/ggml-openvino/openvino/op/scale.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -26,15 +27,20 @@ OutputVector translate_scale(const NodeContext & context) { return translate_recurrent_cache_reset(context); } - auto scaled = std::make_shared(process_view_input_new(context, 0), scale_node); - - std::shared_ptr res; + // Multiply and Add need matching types; compute f16 input in f32 and round once, as the CPU backend does. + auto input = process_view_input_new(context, 0); + const auto input_type = input.get_element_type(); + if (input_type != ov::element::f32) { + input = std::make_shared(input, ov::element::f32); + } + ov::Output res = std::make_shared(input, scale_node); if (bias != 0.0f) { auto bias_node = std::make_shared(ov::element::f32, ov::Shape{}, std::vector{bias}); - res = std::make_shared(scaled, bias_node); - } else { - res = scaled; + res = std::make_shared(res, bias_node); + } + if (input_type != ov::element::f32) { + res = std::make_shared(res, input_type); } return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp b/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp new file mode 100644 index 000000000000..509b43e0005f --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp @@ -0,0 +1,42 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +// Local mirror of OpenVINO's ov::op::internal::SelectiveSSM declaration +// (src/core/dev_api/openvino/op/selective_ssm.hpp). The implementation comes from the linked +// OpenVINO runtime; the class layout must stay in sync with the runtime's declaration. +#pragma once + +#include "openvino/op/op.hpp" + +namespace ov::op::internal { +/// Mamba2 selective state-space recurrence (arXiv:2405.21060). +/// dA = exp(A * dt), dtB = dt * B; per token t: +/// dBx_t = x_t (x) dtB_t, state_t = state_{t-1} * dA_t + dBx_t, y_t = sum(state_t * C_t). +/// B and C are grouped and shared across heads: head h reads group h / (num_heads / num_groups). +class OPENVINO_API SelectiveSSM : public ov::op::Op { +public: + OPENVINO_OP("SelectiveSSM") + + SelectiveSSM() = default; + /// \param A (Negative) log-decay rates per head [num_heads]. + /// \param dt Per-token, per-head time steps [batch_size, seq_len, num_heads]. + /// \param B Grouped input projection [batch_size, seq_len, num_groups, state_size]. + /// \param x Input hidden states [batch_size, seq_len, num_heads, head_dim]. + /// \param C Grouped output projection [batch_size, seq_len, num_groups, state_size]. + /// \param recurrent_state Initial state [batch_size, num_heads, head_dim, state_size]. + SelectiveSSM(const Output & A, + const Output & dt, + const Output & B, + const Output & x, + const Output & C, + const Output & recurrent_state); + + /// \param args Input tensor vector in order: A, dt, B, x, C, recurrent_state. + explicit SelectiveSSM(const ov::OutputVector & args); + + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor & visitor) override; + std::shared_ptr clone_with_new_inputs(const ov::OutputVector & new_args) const override; +}; + +} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp index 1eae9408b83e..476890911c04 100644 --- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp @@ -90,12 +90,71 @@ static OutputVector translate_conv_snapshots(const NodeContext & context) { return rename_outputs_with_suffix({result}, name); } +// SET_ROWS into a column range of a plain 2-D buffer (see GgmlOvDecoder::is_column_set_rows). The result is the +// whole buffer: the indexed rows get the new columns, the other columns and rows keep their values, so the next +// write into another column range of the same buffer reads this one. +static OutputVector translate_column_set_rows(const NodeContext & context) { + using namespace ov::op; + auto i64_const = [](const std::vector & values) { + return v0::Constant::create(ov::element::i64, {values.size()}, values); + }; + + const auto view_shape = context.get_view_input_ggml_shape(2, 0); // [1, 1, rows, width] + FRONT_END_OP_CONVERSION_CHECK(view_shape.size() == 4, "SET_ROWS column write needs a 4-D destination view"); + const int64_t width = (int64_t) view_shape[3]; + + auto base = context.get_input(2); + const auto base_shape = base.get_partial_shape(); + FRONT_END_OP_CONVERSION_CHECK(base_shape.rank().is_static() && base_shape[base_shape.size() - 1].is_static(), + "SET_ROWS column write needs a static buffer row size"); + const int64_t row_size = base_shape[base_shape.size() - 1].get_length(); + const size_t elem_size = context.get_output_type().size(); + const int64_t col_begin = (int64_t) (context.get_view_input_offset(2, 0) / elem_size) % row_size; + const int64_t col_end = col_begin + width; + FRONT_END_OP_CONVERSION_CHECK(col_end <= row_size, "SET_ROWS column range is out of bounds"); + + Output data = std::make_shared(process_view_input_new(context, 0), i64_const({1, 1, -1, width}), + false); + if (data.get_element_type() != context.get_output_type()) { + data = std::make_shared(data, context.get_output_type()); + } + Output rows = std::make_shared(process_view_input_new(context, 1), i64_const({-1}), false); + if (rows.get_element_type() != ov::element::i64) { + rows = std::make_shared(rows, ov::element::i64); + } + + auto axis = v0::Constant::create(ov::element::i64, {}, {2}); + auto buffer = std::make_shared(base, i64_const({1, 1, -1, row_size}), false); + Output updates = data; + if (width < row_size) { + auto existing = std::make_shared(buffer, rows, axis); + auto col_axis = i64_const({3}); + OutputVector parts; + if (col_begin > 0) { + parts.push_back(std::make_shared(existing, i64_const({0}), i64_const({col_begin}), + i64_const({1}), col_axis)); + } + parts.push_back(data); + if (col_end < row_size) { + parts.push_back(std::make_shared(existing, i64_const({col_end}), i64_const({row_size}), + i64_const({1}), col_axis)); + } + updates = std::make_shared(parts, 3); + } + auto updated = std::make_shared(buffer, rows, updates, axis); + auto res = std::make_shared(updated, std::make_shared(base, ov::element::i64), false); + return rename_outputs_with_suffix({res}, context.get_name()); +} + OutputVector translate_set_rows(const NodeContext & context) { num_inputs_check(context, 3, 3); if (context.get_op_case() == 3) { return translate_conv_snapshots(context); } + if (context.get_op_case() == 4) { + return translate_column_set_rows(context); + } auto data = process_view_input_new(context, 0); auto indices = process_view_input_new(context, 1); diff --git a/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp b/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp new file mode 100644 index 000000000000..fce8e111ed42 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp @@ -0,0 +1,63 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +// Adapted from OpenVINO's GGUF frontend (src/frontends/gguf/src/op/ssm_scan.cpp). + +#include "../node_context.h" +#include "../op_table.h" +#include "../utils.h" +#include "selective_ssm.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace op { + +OutputVector translate_ssm_scan(const NodeContext & context) { + num_inputs_check(context, 7, 7); + using namespace ov::op; + + // ggml: s [slots,H,D,S], x [B,T,H,D], dt [1,B,T,H], A [1,1,H,1], + // B/C [B,T,G,S], ids [1,1,1,B]. Only Mamba2 has scalar decay per head. + const auto a_shape = context.get_input_shape(3); + FRONT_END_OP_CONVERSION_CHECK(a_shape.rank() == 4 && a_shape[0] == 1 && a_shape[1] == 1 && a_shape[3] == 1, + "SSM_SCAN: SelectiveSSM requires Mamba2 scalar decay per head; " + "Mamba1 state-wise decay is not supported"); + const auto x = process_view_input_new(context, 1); + const auto flat = v0::Constant::create(element::i64, {1}, {-1}); + const auto axis0 = v0::Constant::create(element::i64, {}, {0}); + const auto ids = std::make_shared(process_view_input_new(context, 6), flat, false); + const auto state = std::make_shared(process_view_input_new(context, 0), ids, axis0); + const auto a = std::make_shared(process_view_input_new(context, 3), flat, false); + const auto dt_shape = std::make_shared(std::make_shared(x), + v0::Constant::create(element::i64, {3}, {0, 1, 2}), + axis0); + const auto dt = + std::make_shared(std::make_shared(process_view_input_new(context, 2), dt_shape, false)); + const auto ssm = std::make_shared(a, + dt, + process_view_input_new(context, 4), + x, + process_view_input_new(context, 5), + state); + // Pack directly in GGML layout so whole-part views can select either Concat input. + const auto packed_shape = v0::Constant::create(element::i64, {4}, {1, 1, 1, -1}); + const auto y = std::make_shared(ssm->output(0), packed_shape, false); + const auto s = std::make_shared(ssm->output(1), packed_shape, false); + const auto result = std::make_shared(OutputVector{y, s}, 3); + result->get_rt_info()[GGML_OV_SSM_SCAN_PACKED] = true; + return rename_outputs_with_suffix({result}, context.get_name()); +} + +} // namespace op +} // namespace ggml +} // namespace frontend +} // namespace ov + diff --git a/ggml/src/ggml-openvino/openvino/op/tri.cpp b/ggml/src/ggml-openvino/openvino/op/tri.cpp index 9b7774a383ec..ba2efdc0bf1f 100644 --- a/ggml/src/ggml-openvino/openvino/op/tri.cpp +++ b/ggml/src/ggml-openvino/openvino/op/tri.cpp @@ -70,7 +70,8 @@ OutputVector translate_tri(const NodeContext & context) { throw std::runtime_error("translate_tri: invalid tri_type " + std::to_string(tri_type)); } - auto zero = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f}); + // Select needs the zero in the input's type (f32, f16 or bf16). + auto zero = ov::op::v0::Constant::create(x.get_element_type(), {}, {0.0f}); auto res = std::make_shared(mask, x, zero); return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index 399c17ac0162..defc428d1d4c 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -98,6 +98,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_PAD", op::translate_pad }, {"GGML_OP_TOP_K", op::translate_top_k }, {"GGML_OP_SSM_CONV", op::translate_ssm_conv }, + {"GGML_OP_SSM_SCAN", op::translate_ssm_scan }, {"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net }, {"GGML_OP_REPEAT", op::translate_repeat }, {"GGML_OP_CUMSUM", op::translate_cumsum }, diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 206966a935ff..54c60c634bf6 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -49,6 +49,7 @@ GGML_OP_CONVERTER(translate_flash_attn_ext); GGML_OP_CONVERTER(translate_clamp); GGML_OP_CONVERTER(translate_pad); GGML_OP_CONVERTER(translate_ssm_conv); +GGML_OP_CONVERTER(translate_ssm_scan); GGML_OP_CONVERTER(translate_gated_delta_net); #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index ec7513951c01..e82a6c92fc47 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -465,6 +465,25 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return input; } + // A VIEW over the packed SSM_SCAN output selects one whole Concat part: y at offset 0, the + // final state after it. The y length is token-dependent, so a static Slice of the flat + // tensor would bake in the captured token count; return the native part instead. + if (view_input_size == 1 && input.get_node_shared_ptr()->get_rt_info().count(GGML_OV_SSM_SCAN_PACKED)) { + const bool is_y = context.get_view_input_offset(input_index, 0) == 0; + auto part = input.get_node_shared_ptr()->input_value(is_y ? 0 : 1).get_node_shared_ptr()->input_value(0); + if (is_y) { + // y keeps its native [n_seqs, n_tokens, n_head, head_dim] layout + return part; + } + // state [n_seqs, n_head, head_dim, d_state] -> view layout [1, 1, n_seqs, d_state * d_inner] + auto n_seqs = get_dimensions(std::make_shared(part, ov::element::i64), {0}); + auto target = std::make_shared( + ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 1}), n_seqs, + ov::op::v0::Constant::create(ov::element::i64, {1}, {-1})}, + 0); + return std::make_shared(part, target, false); + } + // Integer router views can share these strides when their row count is zero. // Packed projections can store query and gate in separate halves of each head. if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { @@ -534,6 +553,70 @@ ov::Output process_view_input_new(const NodeContext & context, int inp } } + // A VIEW that regroups one contiguous span of every source row, e.g. the z/x/B/C splits of the + // fused mamba projections: [head_dim, n_head, nt, ns] over [d_in_proj, nt, ns] rows. The span + // dims are packed and the remaining dims carry the source's outer strides, so the view is a + // Slice of the source's innermost axis plus a Reshape. + if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { + const auto source = context.get_view_input_src_ggml_shape(input_index, 0); + const auto view = context.get_view_input_ggml_shape(input_index, 0); + const auto source_stride = context.get_view_input_src_stride(input_index, 0); + const auto view_stride = context.get_view_input_stride(input_index, 0); + const auto in_rank = input.get_partial_shape().rank(); + const size_t nd = view.size(); + if (nd == 4 && source.size() == nd && view_stride.size() == nd && source_stride.size() == nd && + in_rank.is_static() && in_rank.get_length() == static_cast(nd) && + view_stride[nd - 1] == source_stride[nd - 1] && source_stride[nd - 1] > 0) { + const size_t es = source_stride[nd - 1]; + int j = static_cast(nd) - 1; + size_t span = 1; + while (j >= 0 && view_stride[j] == span * es) { + span *= view[j]; + --j; + } + // at least two packed dims replace the source's innermost dim; a one-dim span keeps the + // source rank and is handled by the generic paths below + const int shift = static_cast(nd) - 2 - j; + bool matches = j >= 0 && shift >= 1; + for (int t = 0; matches && t <= j; ++t) { + matches = view[t] == source[t + shift] && view_stride[t] == source_stride[t + shift]; + } + for (int t = 0; matches && t < shift; ++t) { + matches = source[t] == 1; + } + const size_t offset = context.get_view_input_offset(input_index, 0); + const size_t src_offset = context.get_view_input_src_offset(input_index, 0); + if (matches && offset >= src_offset && (offset - src_offset) % es == 0) { + const int64_t begin = static_cast((offset - src_offset) / es); + if (begin + static_cast(span) <= static_cast(source[nd - 1])) { + auto sliced = std::make_shared( + input, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + static_cast(span)}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {static_cast(nd) - 1})); + const auto view_ov_shape = context.get_view_input_ov_shape(input_index, 0); + std::vector pattern(nd); + size_t dynamic_dims = 0; + for (size_t i = 0; i < nd; ++i) { + if (view_ov_shape.rank().is_static() && view_ov_shape[i].is_static()) { + pattern[i] = view_ov_shape[i].get_length(); + } else { + pattern[i] = -1; + ++dynamic_dims; + } + } + if (dynamic_dims > 1) { + for (size_t i = 0; i < nd; ++i) { + pattern[i] = static_cast(view[i]); + } + } + return std::make_shared( + sliced, ov::op::v0::Constant::create(ov::element::i64, {nd}, pattern), false); + } + } + } + } + // A row range of a 2D weight (BERT's token type row): slice the rows of the [rows, row_size] Constant if (view_input_size == 1 && input.get_partial_shape().rank().is_static() && input.get_partial_shape().rank().get_length() == 2 && @@ -671,14 +754,17 @@ ov::Output process_view_input_new(const NodeContext & context, int inp exact_chunk = i == static_cast(split_dim) || view_ggml_shape[i] == 1 || view_stride_v[i] == view_src_stride_v[i]; } - // stateful execution drops the leading size-1 axis, so the input can be one rank lower than the - // ggml metadata - const auto input_rank = input.get_partial_shape().rank(); - const int64_t rank_shift = input_rank.is_static() ? - static_cast(ndims) - input_rank.get_length() : - static_cast(ndims); + // num_splits is the captured source size: on a dynamic axis (e.g. the token axis of DSpark's + // result_norm, read one block position at a time) the graph is reused with other sizes, and + // each Split output would then hold several rows or the wrong one + const auto input_shape = input.get_partial_shape(); + const int64_t split_axis = input_shape.rank().is_static() ? + split_dim - (int64_t) ndims + input_shape.rank().get_length() : + -1; + const bool split_axis_static = split_axis >= 0 && input_shape[split_axis].is_static() && + input_shape[split_axis].get_length() == num_splits; if (split_index >= 0 && split_index < num_splits && dynamic_split && exact_chunk && - split_dim >= rank_shift) { + split_axis_static) { // the Split keeps its input alive, so only keep a weak reference to it on the input auto src_node = input.get_node_shared_ptr(); std::string rt_key = @@ -689,8 +775,7 @@ ov::Output process_view_input_new(const NodeContext & context, int inp split_node = rt_info[rt_key].as>().lock(); } if (split_node == nullptr) { - auto axis_const = ov::op::v0::Constant::create( - ov::element::i64, {}, {static_cast(split_dim) - rank_shift}); + auto axis_const = ov::op::v0::Constant::create(ov::element::i64, {}, {split_axis}); split_node = std::make_shared(input, axis_const, static_cast(num_splits)); split_node->set_friendly_name(src_node->get_friendly_name() + "_split"); @@ -722,7 +807,8 @@ ov::Output process_view_input_new(const NodeContext & context, int inp // Lambda function to process a single view operation auto process_single_view = - [](ov::Output current, size_t view_offset, const std::vector & view_stride, + [is_static = context.is_static()]( + ov::Output current, size_t view_offset, const std::vector & view_stride, const ov::Shape & view_ggml_shape, const ov::PartialShape & view_ov_shape, const std::string & view_name, size_t view_src_offset, const std::vector & view_src_stride, const ov::Shape & view_src_ggml_shape, const ov::PartialShape & view_src_ov_shape, const std::string & view_src_name) -> ov::Output { @@ -847,7 +933,12 @@ ov::Output process_view_input_new(const NodeContext & context, int inp ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_dim - axis_shift})); - if (view_ov_shape.is_static()) { + // In a static graph a rank-preserving slice (diff_dims has one entry) already has the view + // shape. Skip the Reshape: its target bakes the static chunk size into the token axis, which + // is wrong after the output-ids GET_ROWS of the last layer (1 token in the prefill graph). + const bool rank_kept = is_static && current_rank.is_static() && + static_cast(current_rank.get_length()) == ndims; + if (view_ov_shape.is_static() && !rank_kept) { auto reshaped = std::make_shared( sliced, ov::op::v0::Constant::create(ov::element::i64, {ndims}, view_ov_shape.to_shape()), diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index 10344675b21e..aaee05116445 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -97,6 +97,9 @@ constexpr const char * GGML_OV_GROUPED_ROWS = "ggml_ov_grouped_rows"; // rt_info key on the stateful V cache read with `-fa off` (permute): V is [.., kv, head_size], not transposed constexpr const char * GGML_OV_V_TOKEN_MAJOR = "ggml_ov_v_token_major"; +// rt_info key on the packed SSM_SCAN output Concat [1, 1, 1, y | state]; whole-part VIEWs select one Concat input +constexpr const char * GGML_OV_SSM_SCAN_PACKED = "ggml_ov_ssm_scan_packed"; + namespace op { template OutputVector translate_1to1_match_2_inputs(const NodeContext & context) { num_inputs_check(context, 2, 2); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 7c5f6b7567b3..c959ce0d9203 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -657,6 +657,30 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_ return *sliced; } + // KQ mask with fewer columns than the rounded KV length (see compute_llm_params): pad it with -inf + const auto & compute_params = ggml_decoder->get_compute_params(); + if (!ggml_decoder->is_static() && name == compute_params.mask_name && + compute_params.attention_size > ggml_tensor->ne[0] && ggml_is_contiguous(ggml_tensor)) { + const size_t rows = ggml_nrows(ggml_tensor); + const size_t cols = ggml_tensor->ne[0]; + const size_t padded_cols = compute_params.attention_size; + ov::Shape shape = GgmlOvDecoder::get_shape(ggml_tensor); + shape.back() = padded_cols; + ov::Tensor padded(GgmlOvDecoder::get_ov_type(ggml_tensor), shape); + auto pad = [&](auto fill) { + using T = decltype(fill); + auto data = pad_input((const T *) ggml_tensor->data, rows, cols, rows, padded_cols, fill); + std::memcpy(padded.data(), data.data(), padded.get_byte_size()); + }; + if (ggml_tensor->type == GGML_TYPE_F16) { + pad(GGML_FP32_TO_FP16(-INFINITY)); + } else { + GGML_ASSERT(ggml_tensor->type == GGML_TYPE_F32); + pad(-INFINITY); + } + return padded; + } + if (ggml_decoder->is_static() && GgmlOvDecoder::is_kvcache(ggml_tensor, ggml_decoder->get_tensor_used_op(ggml_tensor))) { const auto type = ggml_decoder->get_ov_type(ggml_tensor); @@ -2192,8 +2216,21 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared old_m_params = ggml_decoder->get_model_params(); cache_hit = old_m_params.can_reuse_statically(m_params); if (cache_hit && is_prefill && ggml_openvino_kv_slice_enabled()) { - cache_hit = entry->prefill_attention_size == c_params.attention_size && - entry->prefill_attention_size_swa == c_params.attention_size_swa; + // A larger compiled prefill also serves a smaller attended length: the extra KV rows are masked, as with + // the power-of-two rounding. Without this, a new prompt walks up the sizes again, and since only one + // prefill model is kept, every prompt longer than one chunk recompiles. Head-major KV is bound at the + // storage size, so it keeps the exact match. + // The output count is part of the static prefill shape (more than 1 only for llama-perplexity). + const bool reuse_larger = !ggml_openvino_npu_kv_head_major_enabled(); + cache_hit = entry->prefill_output_len == c_params.output_len && + (reuse_larger ? entry->prefill_attention_size >= c_params.attention_size && + entry->prefill_attention_size_swa >= c_params.attention_size_swa : + entry->prefill_attention_size == c_params.attention_size && + entry->prefill_attention_size_swa == c_params.attention_size_swa); + if (cache_hit) { + c_params.attention_size = entry->prefill_attention_size; + c_params.attention_size_swa = entry->prefill_attention_size_swa; + } prefill_size_changed = !cache_hit; } } @@ -2260,6 +2297,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared entry->ptr = ggml_decoder; entry->prefill_attention_size = c_params.attention_size; entry->prefill_attention_size_swa = c_params.attention_size_swa; + entry->prefill_output_len = c_params.output_len; entry->decode_attention_size = compiled.decode_attention_size; entry->shared_key = shared_key; entry->decode_window_requests.clear(); @@ -2274,6 +2312,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared r_ctx->ov_output_names_cache_prefill[key] = compiled.prefill_output_names; decoder_end_time = conversion_end_time = compile_end_time = ggml_time_us(); GGML_LOG_DEBUG("ggml-openvino: shared compiled model HIT (static)\n"); + if (prefill_size_changed) { + GGML_LOG_INFO("ggml-openvino: reuse the compiled prefill model of attention size %d\n", + c_params.attention_size); + } } else { auto decode_c_params = c_params; if (ggml_openvino_kv_slice_enabled()) { @@ -2600,6 +2642,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared entry->ptr = ggml_decoder; entry->prefill_attention_size = c_params.attention_size; entry->prefill_attention_size_swa = c_params.attention_size_swa; + entry->prefill_output_len = c_params.output_len; entry->decode_attention_size = decode_c_params.attention_size; entry->shared_key = shared_key; entry->decode_window_requests.clear(); @@ -3180,7 +3223,7 @@ enum ggml_status ov_graph_compute(ggml_cgraph * cgraph, ggml_backend_t backend) GgmlOvDecoder::dump_cgraph(cgraph, filename); } - const auto is_static = ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"); + const auto is_static = ggml_openvino_is_static(); GGML_ASSERT(ctx->runtime_context != nullptr); std::shared_ptr r_ctx = std::static_pointer_cast(ctx->runtime_context); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 31fa7abc2435..c4450a387748 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -42,6 +42,11 @@ struct graph_key { if (GgmlOvDecoder::is_sampling_view(node)) { input_srcs.push_back("sampling_row_" + std::string(node->name) + "#n" + std::to_string(i)); } + // The output set is part of the model (one Result per output). Enabling outputs on an existing graph, + // e.g. llama_set_embeddings_layer_inp() for a DFlash/DSpark drafter, changes only the flags. + if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { + input_srcs.push_back("output_" + std::string(node->name) + "#n" + std::to_string(i)); + } } static const bool full_key = ggml_openvino_getenv_int("GGML_OPENVINO_FULL_GRAPH_KEY") != 0; @@ -95,9 +100,11 @@ struct decoder_runtime_ctx { std::shared_ptr mutex; std::shared_ptr ptr; - // Attention sizes the cached prefill model was built with; decode calls overwrite the decoder's. + // Attention sizes and output count the cached prefill model was built with; decode calls overwrite the + // decoder's. int prefill_attention_size = -1; int prefill_attention_size_swa = -1; + int prefill_output_len = -1; // KV window of the decode model in the compiled pair (GGML_OPENVINO_NPU_BLOB_PREBUILD). int decode_attention_size = -1; std::string shared_key; From 53ecea05a0728e133478b06b3d543b6fcfaa418e Mon Sep 17 00:00:00 2001 From: JamePeng Date: Fri, 20 Nov 2026 02:11:11 +0800 Subject: [PATCH 05/88] mtmd : fix YuE2 projector loading (#32606) - Allow cls.output.weight to be absent from the mmproj. It is an optional Qwen3 reranking head that the YuE2 NAR decoder never uses. - Without this fix, mtmd_init_from_file() fails with "tensor cls.output.weight is missing from the mmproj", preventing audio generation from starting. --- tools/mtmd/mtmd.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index 1101d267ad01..511e01f93223 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -644,6 +644,7 @@ static void mtmd_owned_llama_set_tensor_data(ggml_tensor * t, void * user_data) return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0; }; const bool optional = ends_with("scale") || ends_with(".bias") || name == "dense_2.weight" || + name == "cls.output.weight" || // Qwen3 reranking head, unused by YuE2 NAR name == "rope_freqs.weight" || // granite, voxcpm2 residual LM name == "token_embd.weight" || name == "output.weight"; // inputs are embedding rows, outputs are hidden states if (!optional || t->type != GGML_TYPE_F32) { From 7fce5439fe451cd48340b112ec37d2befe02c776 Mon Sep 17 00:00:00 2001 From: anujj Date: Thu, 19 Nov 2026 23:43:55 +0530 Subject: [PATCH 06/88] ggml : add BF16 support to ROPE and SET_ROWS (CPU, CUDA) (#32387) * ggml : add BF16 support to ROPE and SET_ROWS (CPU, CUDA) * cuda : SET_ROWS from BF16 into quantized types and F8_E4M3 * cuda : fuse BF16 rope into a BF16 cache * tests : trim the BF16 rope cases to one per code path --- ggml/src/ggml-cann/ggml-cann.cpp | 6 +++ ggml/src/ggml-cpu/ggml-cpu.c | 3 +- ggml/src/ggml-cpu/ops.cpp | 38 ++++++++++++-- ggml/src/ggml-cuda/ggml-cuda.cu | 13 +++-- ggml/src/ggml-cuda/rope.cu | 63 +++++++++++++++++++----- ggml/src/ggml-cuda/set-rows.cu | 53 +++++++++++++------- ggml/src/ggml-metal/ggml-metal-device.m | 2 +- ggml/src/ggml-opencl/ggml-opencl.cpp | 2 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 6 +++ ggml/src/ggml-sycl/ggml-sycl.cpp | 4 +- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 3 +- ggml/src/ggml.c | 2 +- tests/test-backend-ops.cpp | 60 +++++++++++++++++++--- 13 files changed, 204 insertions(+), 51 deletions(-) diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 7e692f1b545f..0adc8680f5a4 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2501,6 +2501,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten break; case GGML_OP_SET_ROWS: { + if (op->src[0]->type == GGML_TYPE_BF16) { + return false; + } switch (op->type) { case GGML_TYPE_F32: case GGML_TYPE_F16: @@ -2553,6 +2556,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten if (((const int32_t *) op->op_params)[15] != 0) { return false; // FIXME: support ggml_rope_set_offset } + if (op->src[0]->type != GGML_TYPE_F32 && op->src[0]->type != GGML_TYPE_F16) { + return false; + } if (op->src[0]->ne[0] > 896) { return false; } diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 8b4c7a4ef06c..4d9760bad5b1 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -2933,7 +2933,8 @@ struct ggml_cplan ggml_graph_plan( } break; case GGML_OP_SET_ROWS: { - if (node->src[0]->type == GGML_TYPE_F16 && node->type != GGML_TYPE_F16) { + if ((node->src[0]->type == GGML_TYPE_F16 && node->type != GGML_TYPE_F16) || + (node->src[0]->type == GGML_TYPE_BF16 && node->type != GGML_TYPE_BF16)) { cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks; } } break; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 0b540c5a7cff..cd8134740e19 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -5531,7 +5531,7 @@ static void ggml_compute_forward_set_rows_impl( assert(ne0 == nc); assert(ne2 == ne02); assert(ne3 == ne03); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); assert(ne02 % ne11 == 0); assert(ne03 % ne12 == 0); @@ -5578,6 +5578,20 @@ static void ggml_compute_forward_set_rows_impl( from_float(wdata, ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), nc); } + } else if constexpr (std::is_same_v) { + if (dst->type == GGML_TYPE_BF16) { + memcpy( + ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), + ((char *) src0->data + i*nb01 + i02*nb02 + i03*nb03), + rs); + } else { + float * wdata = (float *) params->wdata + (nc + CACHE_LINE_SIZE_F32) * ith; + ggml_bf16_to_fp32_row( + (const ggml_bf16_t *) ((char *) src0->data + i*nb01 + i02*nb02 + i03*nb03), + wdata, nc); + from_float(wdata, + ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), nc); + } } else { GGML_ABORT("src0->type = %d (%s) not supported", src0->type, ggml_type_name(src0->type)); } @@ -5614,6 +5628,16 @@ void ggml_compute_forward_set_rows( GGML_ABORT("src1->type = %d (%s) not supported", src1->type, ggml_type_name(src1->type)); } } break; + case GGML_TYPE_BF16: + { + if (src1->type == GGML_TYPE_I64) { + ggml_compute_forward_set_rows_impl(params, dst); + } else if (src1->type == GGML_TYPE_I32) { + ggml_compute_forward_set_rows_impl(params, dst); + } else { + GGML_ABORT("src1->type = %d (%s) not supported", src1->type, ggml_type_name(src1->type)); + } + } break; default: { GGML_ABORT("src0->type = %d (%s) not supported", src0->type, ggml_type_name(src0->type)); @@ -6302,7 +6326,7 @@ static void rotate_pairs(const int64_t n, const int64_t n_offset, const float * } } -template //float or ggml_fp16_t +template //float, ggml_fp16_t or ggml_bf16_t static void ggml_compute_forward_rope_flt( const ggml_compute_params * params, ggml_tensor * dst, @@ -6312,7 +6336,7 @@ static void ggml_compute_forward_rope_flt( const ggml_tensor * src1 = dst->src[1]; const ggml_tensor * src2 = dst->src[2]; - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); GGML_ASSERT(src1->type == GGML_TYPE_I32); float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow; @@ -6472,6 +6496,10 @@ void ggml_compute_forward_rope( { ggml_compute_forward_rope_flt(params, dst, true); } break; + case GGML_TYPE_BF16: + { + ggml_compute_forward_rope_flt(params, dst, true); + } break; case GGML_TYPE_F32: { ggml_compute_forward_rope_flt(params, dst, true); @@ -6496,6 +6524,10 @@ void ggml_compute_forward_rope_back( { ggml_compute_forward_rope_flt(params, dst, false); } break; + case GGML_TYPE_BF16: + { + ggml_compute_forward_rope_flt(params, dst, false); + } break; case GGML_TYPE_F32: { ggml_compute_forward_rope_flt(params, dst, false); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 2ce3d0b809c6..a58f020c29df 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -3504,7 +3504,12 @@ static bool ggml_cuda_should_fuse_rope_set_rows(const ggml_tensor * rope, return false; } - if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) { + if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16 && set_rows->type != GGML_TYPE_BF16) { + return false; + } + + // BF16 rope fuses into an F16 or BF16 cache, other ropes not into a BF16 cache + if (rope->type == GGML_TYPE_BF16 ? set_rows->type == GGML_TYPE_F32 : set_rows->type == GGML_TYPE_BF16) { return false; } @@ -6510,7 +6515,7 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_BF16 || op->type == GGML_TYPE_F8_E4M3 || op->type == GGML_TYPE_Q4_0 || op->type == GGML_TYPE_Q4_1 || op->type == GGML_TYPE_Q5_0 || op->type == GGML_TYPE_Q5_1 || op->type == GGML_TYPE_Q8_0 || op->type == GGML_TYPE_IQ4_NL) && - op->src[0]->type == GGML_TYPE_F32 + (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_BF16) ) || ( op->type == GGML_TYPE_F16 && op->src[0]->type == GGML_TYPE_F16 ) @@ -6731,7 +6736,9 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g return false; case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: { - return op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && ggml_is_contiguous_2(op->src[0]); + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) && + op->type == op->src[0]->type && + op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && ggml_is_contiguous_2(op->src[0]); } case GGML_OP_IM2COL: case GGML_OP_IM2COL_3D: diff --git a/ggml/src/ggml-cuda/rope.cu b/ggml/src/ggml-cuda/rope.cu index 2604d014f854..657b58a4d05c 100644 --- a/ggml/src/ggml-cuda/rope.cu +++ b/ggml/src/ggml-cuda/rope.cu @@ -92,13 +92,16 @@ static __global__ void rope_norm(const T * x, } else if constexpr (std::is_same_v) { half2 v = make_half2(x0, x1); ggml_cuda_memcpy_1<4>(dst + idst, &v); + } else if constexpr (std::is_same_v) { + const __align__(4) nv_bfloat16 v[2] = { ggml_cuda_cast(x0), ggml_cuda_cast(x1) }; + ggml_cuda_memcpy_1(dst + idst, v); } }; if (i0 < n_offs || i0 >= n_offs + n_dims) { if (inplace) { return; } - store_coaelsced(x[ix + 0], x[ix + 1]); + store_coaelsced(ggml_cuda_cast(x[ix + 0]), ggml_cuda_cast(x[ix + 1])); return; } @@ -113,8 +116,8 @@ static __global__ void rope_norm(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); - const float x0 = x[ix + 0]; - const float x1 = x[ix + 1]; + const float x0 = ggml_cuda_cast(x[ix + 0]); + const float x1 = ggml_cuda_cast(x[ix + 1]); store_coaelsced(x0 * cos_theta - x1 * sin_theta, x0 * sin_theta + x1 * cos_theta); } @@ -189,8 +192,8 @@ static __global__ void rope_neox(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); // idst/ix point at channel i0/2; the first channel of the rotated pair is n_offs + iw/2 = i0/2 + n_offs/2 - const float x0 = x[ix + n_offs/2 + 0]; - const float x1 = x[ix + n_offs/2 + n_dims/2]; + const float x0 = ggml_cuda_cast(x[ix + n_offs/2 + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_offs/2 + n_dims/2]); dst[idst + n_offs/2 + 0] = ggml_cuda_cast(x0 * cos_theta - x1 * sin_theta); dst[idst + n_offs/2 + n_dims / 2] = ggml_cuda_cast(x0 * sin_theta + x1 * cos_theta); @@ -293,8 +296,8 @@ static __global__ void rope_multi(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); // idst/ix point at channel i0/2; the first channel of the rotated pair is n_offs + iw/2 = i0/2 + n_offs/2 - const float x0 = x[ix + n_offs/2 + 0]; - const float x1 = x[ix + n_offs/2 + n_dims/2]; + const float x0 = ggml_cuda_cast(x[ix + n_offs/2 + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_offs/2 + n_dims/2]); dst[idst + n_offs/2 + 0] = ggml_cuda_cast(x0*cos_theta - x1*sin_theta); dst[idst + n_offs/2 + n_dims/2] = ggml_cuda_cast(x0*sin_theta + x1*cos_theta); @@ -357,11 +360,11 @@ static __global__ void rope_vision(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, cos_theta, sin_theta); - const float x0 = x[ix + 0]; - const float x1 = x[ix + n_dims]; + const float x0 = ggml_cuda_cast(x[ix + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_dims]); - dst[idst + 0] = x0*cos_theta - x1*sin_theta; - dst[idst + n_dims] = x0*sin_theta + x1*cos_theta; + dst[idst + 0] = ggml_cuda_cast(x0*cos_theta - x1*sin_theta); + dst[idst + n_dims] = ggml_cuda_cast(x0*sin_theta + x1*cos_theta); } template @@ -569,8 +572,8 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, } cudaStream_t stream = ctx.stream(); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); - GGML_ASSERT( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); + GGML_ASSERT( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_BF16); // When not fused, src0 and dst types must match // When fused (ROPE+VIEW+SET_ROWS), src0 may be F32 and dst may be F16 GGML_ASSERT(src0->type == dst->type || (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16)); @@ -655,6 +658,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_neox_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_neox_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } @@ -674,6 +687,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_multi_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, + row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_multi_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, + row_indices, set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } @@ -686,6 +709,10 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, rope_vision_cuda((const half *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, s03, s1, s2, s3, n_dims, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, sections, stream); + } else if (src0->type == GGML_TYPE_BF16) { + rope_vision_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, s03, s1, + s2, s3, n_dims, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, + corr_dims, freq_factors, sections, stream); } else { GGML_ABORT("fatal error"); } @@ -705,6 +732,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_norm_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_norm_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } diff --git a/ggml/src/ggml-cuda/set-rows.cu b/ggml/src/ggml-cuda/set-rows.cu index 4be3e649b73b..e4fb51619e66 100644 --- a/ggml/src/ggml-cuda/set-rows.cu +++ b/ggml/src/ggml-cuda/set-rows.cu @@ -4,8 +4,8 @@ typedef void (*set_rows_kernel_t)(const char * src, char * dst); // Generic quantized set_rows kernel template -template -static __global__ void k_set_rows_quant(const float * __restrict__ src0, +template +static __global__ void k_set_rows_quant(const src_t * __restrict__ src0, const idx_t * __restrict__ src1, block_type * __restrict__ dst, const int64_t ne_total, @@ -56,13 +56,23 @@ static __global__ void k_set_rows_quant(const float * __restrict__ src0, ggml_cuda_pdl_sync(); const int64_t dst_row = *(src1 + i10*s10 + i11*s11 + i12*s12); - const float * src0_row = src0 + i01*s01 + i02*s02 + i03*s03; + const src_t * src0_row = src0 + i01*s01 + i02*s02 + i03*s03; block_type * dst_row_ptr = dst + (dst_row*s1 + i02*s2 + i03*s3) / sizeof(block_type); - const float * src_block = src0_row + i00; + const src_t * src_block = src0_row + i00; block_type * dst_block = dst_row_ptr + i00 / qk; - quantize_func(src_block, dst_block); + if constexpr (std::is_same_v) { + quantize_func(src_block, dst_block); + } else { + // the quantize functions take F32 input: widen the block first + float src_block_f32[qk]; +#pragma unroll + for (int j = 0; j < qk; ++j) { + src_block_f32[j] = ggml_cuda_cast(src_block[j]); + } + quantize_func(src_block_f32, dst_block); + } GGML_UNUSED(ne10); GGML_UNUSED(ne11); @@ -71,9 +81,9 @@ static __global__ void k_set_rows_quant(const float * __restrict__ src0, } // Template dispatch function for quantized set_rows -template +template static void set_rows_cuda_quant( - const float * src0_d, const idx_t * src1_d, block_type * dst_d, + const src_t * src0_d, const idx_t * src1_d, block_type * dst_d, const int64_t ne00, const int64_t ne01, const int64_t ne02, const int64_t ne03, const int64_t ne10, const int64_t ne11, const int64_t ne12, const int64_t ne13, const size_t nb01, const size_t nb02, const size_t nb03, @@ -87,9 +97,9 @@ static void set_rows_cuda_quant( const dim3 block_size(CUDA_SET_ROWS_BLOCK_SIZE); const dim3 grid_size(num_blocks); - const int64_t s01 = nb01/sizeof(float); - const int64_t s02 = nb02/sizeof(float); - const int64_t s03 = nb03/sizeof(float); + const int64_t s01 = nb01/sizeof(src_t); + const int64_t s02 = nb02/sizeof(src_t); + const int64_t s03 = nb03/sizeof(src_t); const int64_t s10 = nb10/sizeof(idx_t); const int64_t s11 = nb11/sizeof(idx_t); const int64_t s12 = nb12/sizeof(idx_t); @@ -104,7 +114,7 @@ static void set_rows_cuda_quant( const uint3 ne11_fd = init_fastdiv_values((uint32_t) ne11); const uint3 ne12_fd = init_fastdiv_values((uint32_t) ne12); - k_set_rows_quant<<>>( + k_set_rows_quant<<>>( src0_d, src1_d, dst_d, ne_total, ne10, ne11, ne12, ne13, s01, s02, s03, s10, s11, s12, s1, s2, s3, ne00_fd, ne01_fd, ne02_fd, ne11_fd, ne12_fd); } @@ -268,7 +278,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q4_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q4_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -278,7 +288,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q4_1) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q4_1*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -288,7 +298,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q5_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q5_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -298,7 +308,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q5_1) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q5_1*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -308,7 +318,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q8_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q8_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -318,7 +328,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_IQ4_NL) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_iq4_nl*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -382,12 +392,11 @@ void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_te } } - void ggml_cuda_op_set_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * src0 = dst->src[0]; const ggml_tensor * src1 = dst->src[1]; - GGML_ASSERT(src0->type == GGML_TYPE_F32 || (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16)); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16 || (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16)); GGML_ASSERT(src1->type == GGML_TYPE_I64 || src1->type == GGML_TYPE_I32); if (src0->type == GGML_TYPE_F32) { @@ -402,6 +411,12 @@ void ggml_cuda_op_set_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { } else { set_rows_cuda(ctx, src0, src1, dst); } + } else if (src0->type == GGML_TYPE_BF16) { + if (src1->type == GGML_TYPE_I64) { + set_rows_cuda(ctx, src0, src1, dst); + } else { + set_rows_cuda(ctx, src0, src1, dst); + } } else { GGML_ABORT("unsupported type %s", ggml_type_name(src0->type)); } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 26746d0b3065..2e085453adb9 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1713,7 +1713,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32 && (ggml_is_contiguous_rows(op->src[0])); case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: - return ggml_rope_get_truncate(op); + return ggml_rope_get_truncate(op) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); case GGML_OP_IM2COL: return ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 && (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32); case GGML_OP_CONV_2D: diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 0d9212232871..8162ace2ec87 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -12305,7 +12305,7 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te } return false; } - return true; + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; } case GGML_OP_SOLVE_TRI: return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 98f22cfd7a51..bd49560d8e1e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1766,6 +1766,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { !GgmlOvDecoder::is_conv_state_snapshot_writeback(op)) { return {false, "GET_ROWS/SET_ROWS with ne[3] != 1 (ne[3]=" + std::to_string(op->ne[3]) + ") is not supported"}; } + if (op->op == GGML_OP_SET_ROWS && op->src[0]->type == GGML_TYPE_BF16) { + return {false, "SET_ROWS with BF16 src0 is not supported"}; + } if (op->ne[0] == 256 && (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K || op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q5_1)) { // These are all f16-arithmetic dequant rounding errors that intermittently exceed the @@ -2035,6 +2038,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { if (op->view_src != nullptr && !ggml_is_contiguous(op->src[0])) { return {false, "ROPE on VIEW / non-contiguous input is not supported"}; } + if (op->type == GGML_TYPE_BF16) { + return {false, "ROPE with BF16 type is not supported"}; + } break; } case GGML_OP_TRANSPOSE: { diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 4fc90e543166..9da436ced3c1 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7434,8 +7434,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons if (op->type == GGML_TYPE_TQ2_0 || op->type == GGML_TYPE_TQ1_0) { return false; } - auto res = (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || - op->src[0]->type == GGML_TYPE_BF16) && + auto res = (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && (op->src[1]->type == GGML_TYPE_I64 || op->src[1]->type == GGML_TYPE_I32); return res; } @@ -7624,6 +7623,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons } case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; case GGML_OP_IM2COL: case GGML_OP_IM2COL_3D: case GGML_OP_UPSCALE: diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 6955bb406be0..ecd46d8282d2 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -16729,8 +16729,9 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_REPEAT_BACK: return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32; case GGML_OP_ROPE: - return ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0]); + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0]); case GGML_OP_ROPE_BACK: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_VIEW: diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 68e3a011aed4..ecd667753ee3 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -4019,7 +4019,7 @@ struct ggml_tensor * ggml_set_rows( GGML_ASSERT(b->ne[2] % c->ne[1] == 0); GGML_ASSERT(b->ne[3] % c->ne[2] == 0); GGML_ASSERT(c->ne[3] == 1); - GGML_ASSERT(b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16); + GGML_ASSERT(b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16 || b->type == GGML_TYPE_BF16); GGML_ASSERT(c->type == GGML_TYPE_I64 || c->type == GGML_TYPE_I32); GGML_ASSERT(ggml_is_contiguous_rows(a)); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 01ea4c115e8b..d6b849944830 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -2830,6 +2830,12 @@ struct test_set_rows : public test_case { if (type_src == GGML_TYPE_F16) { err_estimate *= 16.0f; } + if (type_src == GGML_TYPE_BF16) { + // BF16 values have 8 significant bits, so many of them land exactly on a rounding tie, + // and backends break ties differently (e.g. the CPU q8_0 rounds half to even, CUDA half away from zero). + // Allow 1 in 32 values to be off by one instead of one value in total. + return err_estimate / (0.25f*32.0f); + } err_estimate /= 0.25f*float(ne[0] * r * ne[2]*nr23[0] * ne[3]*nr23[1]); return err_estimate; } @@ -2860,10 +2866,15 @@ struct test_rope_set_rows : public test_case { const int n_dims; const bool yarn; const bool truncate; + const ggml_type type_a; // type of the rope input const int n_ctx{512}; std::string vars() override { - return VARS_TO_STR7(type, type_idx, ne_a, mode, n_dims, yarn, truncate); + std::string s = VARS_TO_STR7(type, type_idx, ne_a, mode, n_dims, yarn, truncate); + if (type_a != GGML_TYPE_F32) { + s += "," + VAR_TO_STR(type_a); + } + return s; } std::string op_desc(ggml_tensor * t) override { @@ -2871,17 +2882,27 @@ struct test_rope_set_rows : public test_case { return "ROPE_SET_ROWS"; } + double max_nmse_err() override { + if (type_a != GGML_TYPE_BF16) { + return 1e-7; + } + // into F16 the reference rounds the BF16 rope result to BF16 first, the fused rope + set_rows does not + // otherwise the limit of a BF16 test_rope: the angle error n_ctx*FLT_EPSILON can flip a BF16 rounding + return type == GGML_TYPE_F16 ? 1e-5 : n_ctx * FLT_EPSILON / 128.0; + } + bool run_whole_graph() override { return true; } test_rope_set_rows(ggml_type type, ggml_type type_idx, std::array ne_a, int mode, - int n_dims = 128, bool yarn = false, bool truncate = true) - : type(type), type_idx(type_idx), ne_a(ne_a), mode(mode), n_dims(n_dims), yarn(yarn), truncate(truncate) {} + int n_dims = 128, bool yarn = false, bool truncate = true, + ggml_type type_a = GGML_TYPE_F32) + : type(type), type_idx(type_idx), ne_a(ne_a), mode(mode), n_dims(n_dims), yarn(yarn), truncate(truncate), type_a(type_a) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, ne_a[0], ne_a[1], ne_a[2], 1); + ggml_tensor * a = ggml_new_tensor_4d(ctx, type_a, ne_a[0], ne_a[1], ne_a[2], 1); ggml_set_name(a, "a"); const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; @@ -6793,6 +6814,10 @@ struct test_rope : public test_case { // the f32 rotation angle of a position below n_ctx carries a rounding error of up to n_ctx*FLT_EPSILON radians // backends compute the angle with different rounding sequences, so their agreement is bounded by that error const double eps_theta = n_ctx * FLT_EPSILON; + if (type == GGML_TYPE_BF16) { + // with BF16 output that error can also change the rounding: a step of 2^-7 with a chance of about eps_theta/2^-7 + return std::max(test_case::max_nmse_err(), eps_theta / 128.0); + } return std::max(test_case::max_nmse_err(), eps_theta * eps_theta); } @@ -10895,6 +10920,12 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I32, { 1, 8, 1, 3 }, { 1, 1 }, 2, false)); test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, true)); test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I32, { 1, 8, 1, 3 }, { 1, 1 }, 2, true)); + // BF16 source: one case per type covers batch dims, broadcast indices and gaps between rows + for (ggml_type type : all_types) { + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, type, GGML_TYPE_I64, { 256, 11, 1, 1 }, { 2, 3, }, 7, true)); + } + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_I32, { 256, 5, 1, 3 }, { 1, 1, }, 1, false)); + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, false)); for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) { for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { @@ -10905,11 +10936,19 @@ static std::vector> make_test_cases_eval() { } } test_cases.emplace_back(new test_rope_set_rows(GGML_TYPE_F32, GGML_TYPE_I32, { 128, 32, 8, 1 }, GGML_ROPE_TYPE_IMROPE)); + for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) { + for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_BF16}) { + for (int ne2 : {1, 8, 512}) { + test_cases.emplace_back(new test_rope_set_rows(type, GGML_TYPE_I64, { 128, 32, ne2, 1 }, mode, 128, false, true, GGML_TYPE_BF16)); + } + } + } // partial rotation for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE }) { for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { test_cases.emplace_back(new test_rope_set_rows(type, GGML_TYPE_I64, { 256, 4, 8, 1 }, mode, 64)); } + test_cases.emplace_back(new test_rope_set_rows(GGML_TYPE_F16, GGML_TYPE_I64, { 256, 4, 8, 1 }, mode, 64, false, true, GGML_TYPE_BF16)); } for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX}) { @@ -12716,8 +12755,17 @@ static std::vector> make_test_cases_eval() { } } + // BF16: each mode forward on a strided view and backward on an offset view, with and without freq factors, and one in place + for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE, GGML_ROPE_TYPE_VISION}) { + for (bool ff : {false, true}) { + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, ff, 1, true)); + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, ff, 2, false)); + } + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, false, 0, true, true)); + } + // rotated dims window at an offset (ggml_rope_set_offset), not supported for vision mode - for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { for (bool fw : {true, false}) { // fw == forward for (bool ff : {false, true}) { test_cases.emplace_back(new test_rope(type, {128, 32, 2, 1}, 32, GGML_ROPE_TYPE_NORMAL, 512, 1.4245f, 0.7465f, 1.4245f, ff, 0, fw, false, 32)); @@ -14108,7 +14156,7 @@ static std::vector> make_test_cases_perf() { } for (bool fw : {true, false}) { // fw == forward - for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { for (bool ff : {false, true}) { // freq_factors for (float v : { 0, 1 }) { test_cases.emplace_back(new test_rope(type, {128, 32, 512, 1}, 128, GGML_ROPE_TYPE_NORMAL, 512, 1.0f, 0.0f, 1.0f, ff, v, fw)); // llama 7B From c406f4367e19bea7930e7f74e1984c9acc6d44bf Mon Sep 17 00:00:00 2001 From: shaofeiqi Date: Thu, 19 Nov 2026 11:30:19 -0800 Subject: [PATCH 07/88] opencl: support dp4a for KQ mm in decomposed FA (#32577) * opencl: support int8 KQ for DK = 512 Co-authored-by: Shaofei Qi Co-authored-by: Hongqiang Wang Assisted-by: Codex * opencl: allow query chunk up to 96 for int8 KQ Co-authored-by: Shaofei Qi Co-authored-by: Hongqiang Wang Assisted-by: Codex * opencl: extend `build_program_from_source` to allow non-fatal failure Assisted-by: Codex * opencl: add int8 KQ for decomposed FA with DK <= 256 Co-authored-by: Shaofei Qi Co-authored-by: Hongqiang Wang Assisted-by: Codex --------- Co-authored-by: Li He Co-authored-by: Hongqiang Wang --- ggml/src/ggml-opencl/CMakeLists.txt | 3 + ggml/src/ggml-opencl/ggml-opencl.cpp | 288 ++++++++++++++---- .../ggml-opencl/kernels/flash_attn_q8_rows.cl | 77 +++++ .../ggml-opencl/kernels/mul_mm_q8_kq_p8.cl | 174 +++++++++++ .../kernels/mul_mm_q8_kq_p8_dk512.cl | 170 +++++++++++ 5 files changed, 658 insertions(+), 54 deletions(-) create mode 100644 ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl create mode 100644 ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl create mode 100644 ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index cdf4a5d54455..325f5c4bfc75 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -323,6 +323,9 @@ set(GGML_OPENCL_KERNELS mul_mm_f16_f32_kq_kqv mul_mm_f16_f32_kq_p8 mul_mm_q8_f32_kqv + mul_mm_q8_kq_p8 + mul_mm_q8_kq_p8_dk512 + flash_attn_q8_rows conv2d conv2d_f16_f32 conv2_dw diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 8162ace2ec87..776a8e75776a 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -781,6 +781,10 @@ struct ggml_backend_opencl_context { ggml_cl_buffer prealloc_fa_pd; ggml_cl_buffer prealloc_fa_bmax; ggml_cl_buffer prealloc_fa_bsum; + ggml_cl_buffer prealloc_fa_k8; + ggml_cl_buffer prealloc_fa_k8_scale; + ggml_cl_buffer prealloc_fa_q8; + ggml_cl_buffer prealloc_fa_q8_scale; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_buffer prealloc_adreno_xmem_const; @@ -899,6 +903,10 @@ struct ggml_backend_opencl_context { cl_kernel kernel_fa_kqv_direct_f16 = nullptr; cl_kernel kernel_fa_kqv_direct_reduce = nullptr; cl_kernel kernel_fa_v_transpose_q8 = nullptr; + cl_kernel kernel_fa_q8_rows_f16 = nullptr; + cl_kernel kernel_fa_q8_rows_f32 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8_dk512 = nullptr; ggml_opencl_fa_kernels fa; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_adreno_xmem_attn_state adreno_xmem_attn; @@ -1506,7 +1514,18 @@ struct ggml_backend_opencl_context { #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { - for (cl_kernel kernel : {kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, kernel_fa_p8_fixup, kernel_fa_v_transpose_q8, kernel_fa_kqv_direct_f16, kernel_fa_kqv_direct_reduce}) { + for (cl_kernel kernel : { + kernel_mul_mm_f16_f32_kq_p8, + kernel_mul_mm_q8_f32_kqv, + kernel_fa_p8_fixup, + kernel_fa_v_transpose_q8, + kernel_fa_kqv_direct_f16, + kernel_fa_kqv_direct_reduce, + kernel_fa_q8_rows_f16, + kernel_fa_q8_rows_f32, + kernel_mul_mm_q8_kq_p8, + kernel_mul_mm_q8_kq_p8_dk512 + }) { if (kernel != nullptr) { CL_CHECK(clReleaseKernel(kernel)); } @@ -1648,7 +1667,7 @@ static cl_program build_program_from_source_ex(cl_context ctx, cl_device_id dev, return NULL; } -static cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts) { +static cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts, bool fatal = true) { cl_context ctx = backend_ctx->context; cl_device_id dev = backend_ctx->device; @@ -1660,7 +1679,7 @@ static cl_program build_program_from_source(ggml_backend_opencl_context * backen return p_cached; } - cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, /*fatal=*/true); + cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, fatal); // Best-effort save of the freshly-built binary (no-op if cache disabled). if (p != nullptr) { @@ -3995,6 +4014,52 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string rows_src { + #include "flash_attn_q8_rows.cl.h" + }; + const std::string kq_src { + #include "mul_mm_q8_kq_p8.cl.h" + }; +#else + const std::string rows_src = read_file("flash_attn_q8_rows.cl"); + const std::string kq_src = read_file("mul_mm_q8_kq_p8.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, rows_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_fa_q8_rows_f16 = clCreateKernel(prog, "kernel_fa_q8_rows_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_fa_q8_rows_f32 = clCreateKernel(prog, "kernel_fa_q8_rows_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + prog = build_program_from_source(backend_ctx, kq_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_mul_mm_q8_kq_p8 = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } + + // mul_mm_q8_kq_p8_dk512 + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q8_kq_p8_dk512.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q8_kq_p8_dk512.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + cl_kernel kernel = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8_dk512", &err); + CL_CHECK(clReleaseProgram(prog)); + if (err == CL_SUCCESS) { + backend_ctx->kernel_mul_mm_q8_kq_p8_dk512 = kernel; + } + } + GGML_LOG_CONT("."); + } + // mul_mm_f16_f32_kq_p8 if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { #ifdef GGML_OPENCL_EMBED_KERNELS @@ -22922,12 +22987,58 @@ static void ggml_cl_flash_attn_prefill_bin(ggml_backend_t backend, const ggml_te } #endif // GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_fa_q8_rows( + ggml_backend_t backend, const ggml_tensor * src, const ggml_tensor * dst, + cl_mem values, cl_mem scales, int64_t row0, int nrow +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto * extra = (ggml_tensor_extra_cl *) (src->view_src ? src->view_src->extra : src->extra); + const cl_ulong offset = extra->offset + src->view_offs + row0 * src->nb[1]; + const cl_ulong nb1 = src->nb[1]; + const cl_ulong nb2 = src->nb[2]; + const int dk = src->ne[0]; + const int nhead = src->ne[2]; + cl_kernel kernel; + switch (src->type) { + case GGML_TYPE_F16: kernel = backend_ctx->kernel_fa_q8_rows_f16; break; + case GGML_TYPE_F32: kernel = backend_ctx->kernel_fa_q8_rows_f32; break; + default: GGML_ABORT("unsupported int8 KQ input type"); + } + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &values)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &scales)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nrow)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhead)); + const size_t blocks = (size_t) (dk / 32) * nrow * nhead; + size_t gws[3] = {(blocks + 63) / 64 * 64, 1, 1}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); +} + +static void ggml_cl_fa_kq_int8_prepare(ggml_backend_t backend, const ggml_tensor * dst, int64_t n_q_chunk) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const size_t k_bytes = (size_t) k->ne[0] * k->ne[1] * k->ne[2]; + const size_t q_bytes = (size_t) q->ne[0] * n_q_chunk * q->ne[2]; + backend_ctx->prealloc_fa_k8.allocate(backend_ctx->context, k_bytes); + backend_ctx->prealloc_fa_k8_scale.allocate(backend_ctx->context, k_bytes / 32 * sizeof(cl_half)); + backend_ctx->prealloc_fa_q8.allocate(backend_ctx->context, q_bytes); + backend_ctx->prealloc_fa_q8_scale.allocate(backend_ctx->context, q_bytes / 32 * sizeof(cl_half)); + ggml_cl_fa_q8_rows(backend, k, dst, backend_ctx->prealloc_fa_k8.buffer, backend_ctx->prealloc_fa_k8_scale.buffer, 0, k->ne[1]); +} + static void ggml_cl_fa_kq_p8_dispatch( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * mask, const ggml_tensor * sinks, const ggml_tensor * dst, - int64_t q0, int nqc, float scale, float max_bias, int p_pitch + int64_t q0, int nqc, float scale, float max_bias, int p_pitch, bool kq_int8 ) { auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; auto * extra_k = (ggml_tensor_extra_cl *) (k->view_src ? k->view_src->extra : k->extra); @@ -22940,64 +23051,94 @@ static void ggml_cl_fa_kq_p8_dispatch( const int D_A = k->ne[2]; const int D_B = q->ne[2]; - cl_int err; - - cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; - cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format fmt = {CL_RGBA, CL_FLOAT}; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = region.size / 16; - desc.buffer = k_sub; - cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); - CL_CHECK(err); - - region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; - region.size = (size_t) K * N * D_B * sizeof(float); - cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const cl_ulong off_mask = extra_m->offset + mask->view_offs + q0 * mask->nb[1]; const cl_ulong mask_nb1 = mask->nb[1]; const int n_head_log2 = 1u << (unsigned) floorf(log2f((float) D_B)); const float m0 = powf(2.0f, -max_bias / n_head_log2); const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + cl_kernel kernel; cl_uint a = 0; - cl_kernel kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + if (kq_int8) { + ggml_cl_fa_q8_rows(backend, q, dst, backend_ctx->prealloc_fa_q8.buffer, backend_ctx->prealloc_fa_q8_scale.buffer, q0, nqc); + kernel = K <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + size_t gws[3] = {64 * (((size_t) N + 31) / 32) * (D_B / D_A), ((size_t) M + 511) / 512, (size_t) D_A}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } else { + cl_int err; - const size_t n_tiles = (N + 31) / 32; - size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * D_B}; + cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; + cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); - const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; - size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + cl_image_format fmt = {CL_RGBA, CL_FLOAT}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = region.size / 16; + desc.buffer = k_sub; + cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); + CL_CHECK(err); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - CL_CHECK(clReleaseMemObject(k_img)); - CL_CHECK(clReleaseMemObject(k_sub)); - CL_CHECK(clReleaseMemObject(q_sub)); + region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; + region.size = (size_t) K * N * D_B * sizeof(float); + cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + + const size_t n_tiles = (N + 31) / 32; + size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * D_B}; + + const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; + size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + CL_CHECK(clReleaseMemObject(k_img)); + CL_CHECK(clReleaseMemObject(k_sub)); + CL_CHECK(clReleaseMemObject(q_sub)); + } cl_mem sinks_buf = extra_q->data_device; cl_ulong sinks_off = 0; @@ -23261,7 +23402,7 @@ static void ggml_cl_flash_attn_decompose_kq_p8( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst, - int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct + int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct, bool kq_int8 ) { auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; const ggml_tensor * v = dst->src[2]; @@ -23345,13 +23486,17 @@ static void ggml_cl_flash_attn_decompose_kq_p8( backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); } + if (kq_int8) { + ggml_cl_fa_kq_int8_prepare(backend, dst, n_q_chunk); + } + ggml_tensor_extra_cl extra_kqv; ggml_tensor kqv; for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { const int64_t nqc = MIN(n_q_chunk, n_q - q0); - ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch); + ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch, kq_int8); ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); @@ -23408,6 +23553,7 @@ static void ggml_cl_flash_attn_decompose_kq_p8( // head size. GGML_OPENCL_FA_DECOMPOSE_MB sets the KQ scratch budget (default 256). // GGML_OPENCL_FA_KQ_P8=0 disables U8 probabilities and int8 KQV. // GGML_OPENCL_FA_KQV_DIRECT=0 disables direct PV for small query batches. +// GGML_OPENCL_FA_KQ_INT8=0 keeps F16 KQ; =1 enables int8 KQ for supported shapes. static bool ggml_cl_flash_attn_decompose_dispatch( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst @@ -23537,12 +23683,46 @@ static bool ggml_cl_flash_attn_decompose_dispatch( return false; } + static const int kq_int8_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + static const int dk512_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_DK512_F16"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + const bool dk512 = dk > 256 && dk <= 512 && n_q >= 32 && + (dk512_env == 1 || (dk512_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E)); + const bool kq_int8_possible = kq_p8 && (dk <= 256 || dk512) && dk % 32 == 0 && + backend_ctx->kernel_fa_q8_rows_f16 != nullptr && backend_ctx->kernel_fa_q8_rows_f32 != nullptr && + n_head <= INT_MAX && n_head_kv <= INT_MAX && + n_q <= INT_MAX / n_head / (dk / 32) && n_kv <= INT_MAX / n_head_kv / (dk / 32) && + (dst->src[4] == nullptr || dk > 64) && + (kq_int8_env == 1 || (kq_int8_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && n_kv >= 2048)) && + backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f16) >= 64 && + backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f32) >= 64; + cl_kernel kq_int8_kernel = nullptr; + if (kq_int8_possible) { + kq_int8_kernel = dk <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; + } + const bool kq_int8 = kq_int8_kernel != nullptr && backend_ctx->get_kernel_workgroup_size(kq_int8_kernel) >= 64; + + // Fewer query tiles per KV block reduce cache pressure in the int8 KQ kernel. + static const int64_t kq_int8_max_chunk = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8_MAX_CHUNK"); + const int v = (e && e[0]) ? atoi(e) : 96; + return (int64_t) (v >= 32 ? (v / 32) * 32 : 96); + }(); + if (kq_int8) { + n_q_chunk = MIN(n_q_chunk, kq_int8_max_chunk); + } + // even out the chunks, then align to the 32-wide n-tile const int64_t n_chunks = (n_q + n_q_chunk - 1) / n_q_chunk; n_q_chunk = MIN(n_q_chunk, ((n_q + n_chunks - 1) / n_chunks + 31) & ~(int64_t) 31); if (kq_p8) { - ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct); + ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct, kq_int8); } else { ggml_cl_flash_attn_decompose(backend, q, k, dst, n_q_chunk, scale, max_bias); } diff --git a/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl b/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl new file mode 100644 index 000000000000..f0eda2539bcd --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl @@ -0,0 +1,77 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +// Store 32-element blocks as separate int8 values and half scales. + +kernel void kernel_fa_q8_rows_f16( + global const char * src, ulong off_src, ulong nb1, ulong nb2, + global char * dq, global half * dd, + int ne0, int nrow, int nhead +) { + const int nblk = ne0 / 32; + const int gid = get_global_id(0); + if (gid >= nblk*nrow*nhead) { + return; + } + const int b = gid % nblk; + const int r = (gid / nblk) % nrow; + const int h = gid / (nblk*nrow); + + global const half * p = (global const half *)(src + off_src + (ulong)h*nb2 + (ulong)r*nb1) + b*32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 8; ++i) { + const float4 x = convert_float4(vload4(i, p)); + v[i*4+0] = x.s0; + v[i*4+1] = x.s1; + v[i*4+2] = x.s2; + v[i*4+3] = x.s3; + amax = fmax(amax, fmax(fmax(fabs(x.s0), fabs(x.s1)), fmax(fabs(x.s2), fabs(x.s3)))); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + const size_t row = (size_t)h*nrow + r; + dd[row*nblk + b] = (half)d; + global char * q = dq + row*ne0 + b*32; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (char)clamp((int)rint(v[i]*id), -127, 127); + } +} + +kernel void kernel_fa_q8_rows_f32( + global const char * src, ulong off_src, ulong nb1, ulong nb2, + global char * dq, global half * dd, + int ne0, int nrow, int nhead +) { + const int nblk = ne0 / 32; + const int gid = get_global_id(0); + if (gid >= nblk*nrow*nhead) { + return; + } + const int b = gid % nblk; + const int r = (gid / nblk) % nrow; + const int h = gid / (nblk*nrow); + + global const float * p = (global const float *)(src + off_src + (ulong)h*nb2 + (ulong)r*nb1) + b*32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 8; ++i) { + const float4 x = vload4(i, p); + v[i*4+0] = x.s0; + v[i*4+1] = x.s1; + v[i*4+2] = x.s2; + v[i*4+3] = x.s3; + amax = fmax(amax, fmax(fmax(fabs(x.s0), fabs(x.s1)), fmax(fabs(x.s2), fabs(x.s3)))); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + const size_t row = (size_t)h*nrow + r; + dd[row*nblk + b] = (half)d; + global char * q = dq + row*ne0 + b*32; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (char)clamp((int)rint(v[i]*id), -127, 127); + } +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl new file mode 100644 index 000000000000..8e04ad393b5b --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl @@ -0,0 +1,174 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#define KQ_TN 32 +#define KQ_MB 8 +#define KQ_TM 64 +#define KQ_WG 64 +#define KQ_DK_MAX 256 + +__attribute__((qcom_wave_pair_mode(1))) +kernel void kernel_mul_mm_q8_kq_p8( + global const uint * kq, // K int8, [head_kv][n_kv][dk] as packed uints + global const half * kd, // K scales, [head_kv][n_kv][dk/32] + global const uint * qq, // Q int8, [head][n_q][dk] as packed uints + global const half * qd, // Q scales, [head][n_q][dk/32] + global uchar * qp, // u8 P, [head][n_q][p_pitch] + global float * bmax, // per 32-row block max, [head][n_q][p_pitch/32] + global float * bsum, // per block sum of exp(s - bmax), [head][n_q][p_pitch/32] + global const char * mask, // f16 [>=n_kv][n_q] view, row stride mask_nb1 bytes + ulong offset_mask, + ulong mask_nb1, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2, + int dk, + int n_kv, + int n_q, + int n_head, + int n_head_kv, + int p_pitch // bytes per P row, >= n_kv, multiple of 32 +) { + const int lid = get_local_id(0); + const int gsz = n_head / n_head_kv; + const int g0 = get_group_id(0); + const int head_kv = get_group_id(2); + const int head = head_kv*gsz + (g0 % gsz); + const int qn0 = (g0 / gsz) * KQ_TN; + const int kv0 = get_group_id(1)*KQ_TM*KQ_MB + lid; + + const int nblk = dk / 32; + const int nu = dk / 4; + + __local uint sh_q [KQ_TN][KQ_DK_MAX/4]; + __local half sh_qd[KQ_TN][KQ_DK_MAX/32]; + __local float p8_lds[1024]; + + const size_t qbase = (size_t)head*n_q; + for (int i = lid; i < KQ_TN*(KQ_DK_MAX/16); i += KQ_WG) { + const int t = i / (KQ_DK_MAX/16); + const int u = (i % (KQ_DK_MAX/16)) * 4; + const int qi = qn0 + t; + uint4 v = (uint4)(0u); + if (qi < n_q && u < nu) { + v = vload4(0, &qq[(qbase + qi)*nu + u]); + } + vstore4(v, 0, &sh_q[t][u]); + } + for (int i = lid; i < KQ_TN*(KQ_DK_MAX/32); i += KQ_WG) { + const int t = i / (KQ_DK_MAX/32); + const int b = i % (KQ_DK_MAX/32); + const int qi = qn0 + t; + sh_qd[t][b] = (qi < n_q && b < nblk) ? qd[(qbase + qi)*nblk + b] : (half)0.0f; + } + barrier(CLK_LOCAL_MEM_FENCE); + + float slope = 1.0f; + if (max_bias > 0.0f) { + const float base = head < n_head_log2 ? m0 : m1; + const int ex = head < n_head_log2 ? head + 1 : 2*(head - n_head_log2) + 1; + slope = pow(base, ex); + } + global const half * mrow = (global const half *)(mask + offset_mask); + const uint mstride = (uint)(mask_nb1 / 2); + const int pblk = p_pitch / 32; + + for (int m = 0; m < KQ_MB; ++m) { + const int kv = kv0 + m*KQ_TM; + if (kv - lid >= n_kv) { + break; // uniform across the workgroup + } + + float acc[KQ_TN]; + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + acc[t] = 0.0f; + } + + const int kl = min(kv, n_kv - 1); + const size_t kbase = ((size_t)head_kv*n_kv + kl)*nu; + const size_t kdbas = ((size_t)head_kv*n_kv + kl)*nblk; + + for (int b = 0; b < nblk; ++b) { + const uint4 w0 = vload4(0, &kq[kbase + b*8]); + const uint4 w1 = vload4(0, &kq[kbase + b*8 + 4]); + const float dks = (float)kd[kdbas + b]; + + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + const uint4 a0 = vload4(0, &sh_q[t][b*8]); + const uint4 a1 = vload4(0, &sh_q[t][b*8 + 4]); + int raw = 0; + raw = dot_acc_sat_4x8packed_ss_int(w0.s0, a0.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s1, a0.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s2, a0.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s3, a0.s3, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s0, a1.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s1, a1.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s2, a1.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s3, a1.s3, raw); + acc[t] += dks * (float)sh_qd[t][b] * (float)raw; + } + } + + // Each lane owns one complete 32-row softmax block after the transpose. + const int kvblk0 = kv - lid; + #pragma unroll + for (int half_ = 0; half_ < 2; ++half_) { + barrier(CLK_LOCAL_MEM_FENCE); + #pragma unroll + for (int j = 0; j < 16; ++j) { + p8_lds[j*64 + lid] = acc[half_*16 + j]; + } + barrier(CLK_LOCAL_MEM_FENCE); + if (lid < 32) { + const int j = lid >> 1; + const int b = lid & 1; + const int n = qn0 + half_*16 + j; + if (n < n_q) { + const int kvb = kvblk0 + b*32; + const __local float * src = p8_lds + j*64 + b*32; + float16 s0 = vload16(0, src); + float16 s1 = vload16(1, src); + const global half * mp = mrow + (size_t)n*mstride + kvb; + const float16 m0v = convert_float16(vload16(0, mp)); + const float16 m1v = convert_float16(vload16(1, mp)); + s0 = s0*scale + slope*m0v; + s1 = s1*scale + slope*m1v; + const float16 mx16 = fmax(s0, s1); + const float8 mx8 = fmax(mx16.lo, mx16.hi); + const float4 mx4 = fmax(mx8.lo, mx8.hi); + const float2 mx2 = fmax(mx4.lo, mx4.hi); + const float amax = fmax(mx2.x, mx2.y); + const size_t prow = qbase + n; + const int blk = kvb >> 5; + float sum = 0.0f; + uchar16 q0 = (uchar16)(0); + uchar16 q1 = (uchar16)(0); + // finite sentinel: the program builds with -cl-finite-math-only + if (amax > -1.0e30f) { + const float16 e0 = exp(s0 - amax); + const float16 e1 = exp(s1 - amax); + const float16 a16 = e0 + e1; + const float8 a8 = a16.lo + a16.hi; + const float4 a4 = a8.lo + a8.hi; + const float2 a2 = a4.lo + a4.hi; + sum = a2.x + a2.y; + q0 = convert_uchar16_sat_rte(e0*255.0f); + q1 = convert_uchar16_sat_rte(e1*255.0f); + } + global uchar * qdst = qp + prow*(size_t)p_pitch + (size_t)kvb; + vstore16(q0, 0, qdst); + vstore16(q1, 1, qdst); + bmax[prow*pblk + blk] = amax; + bsum[prow*pblk + blk] = sum; + } + } + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl new file mode 100644 index 000000000000..f6ba2b6c2247 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl @@ -0,0 +1,170 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#define KQ_TN 32 +#define KQ_MB 8 +#define KQ_TM 64 +#define KQ_WG 64 +#define KQ_DKC 256 + +__attribute__((qcom_wave_pair_mode(1))) +kernel void kernel_mul_mm_q8_kq_p8_dk512( + global const uint * kq, // K int8, [head_kv][n_kv][dk] as packed uints + global const half * kd, // K scales, [head_kv][n_kv][dk/32] + global const uint * qq, // Q int8, [head][n_q][dk] as packed uints + global const half * qd, // Q scales, [head][n_q][dk/32] + global uchar * qp, // u8 P, [head][n_q][p_pitch] + global float * bmax, // per 32-row block max, [head][n_q][p_pitch/32] + global float * bsum, // per block sum of exp(s - bmax), [head][n_q][p_pitch/32] + global const char * mask, // f16 [>=n_kv][n_q] view, row stride mask_nb1 bytes + ulong offset_mask, + ulong mask_nb1, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2, + int dk, + int n_kv, + int n_q, + int n_head, + int n_head_kv, + int p_pitch // bytes per P row, >= n_kv, multiple of 32 +) { + const int lid = get_local_id(0); + const int gsz = n_head / n_head_kv; + const int g0 = get_group_id(0); + const int head_kv = get_group_id(2); + const int head = head_kv*gsz + (g0 % gsz); + const int qn0 = (g0 / gsz) * KQ_TN; + const int kv0 = get_group_id(1)*KQ_TM*KQ_MB + lid; + + const int nblk = dk / 32; + const int nu = dk / 4; + + // Reuse the 256-wide Q slice for the F32 softmax scores after the contraction. + __local uint sh_q [KQ_TN*KQ_DKC/4]; + __local half sh_qd[KQ_TN][KQ_DKC/32]; + __local float * p8_lds = (__local float *)sh_q; + + const size_t qbase = (size_t)head*n_q; + + float slope = 1.0f; + if (max_bias > 0.0f) { + const float base = head < n_head_log2 ? m0 : m1; + const int ex = head < n_head_log2 ? head + 1 : 2*(head - n_head_log2) + 1; + slope = pow(base, ex); + } + global const half * mrow = (global const half *)(mask + offset_mask); + const uint mstride = (uint)(mask_nb1 / 2); + const int pblk = p_pitch / 32; + + for (int m = 0; m < KQ_MB; ++m) { + const int kv = kv0 + m*KQ_TM; + if (kv - lid >= n_kv) { + break; // uniform across the workgroup + } + + float acc[KQ_TN]; + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + acc[t] = 0.0f; + } + + const int kl = min(kv, n_kv - 1); + const size_t kbase = ((size_t)head_kv*n_kv + kl)*nu; + const size_t kdbas = ((size_t)head_kv*n_kv + kl)*nblk; + + for (int c0 = 0; c0 < nblk; c0 += KQ_DKC/32) { + const int cb = min(KQ_DKC/32, nblk - c0); + barrier(CLK_LOCAL_MEM_FENCE); + for (int i = lid; i < KQ_TN*(KQ_DKC/16); i += KQ_WG) { + const int t = i / (KQ_DKC/16); + const int u = (i % (KQ_DKC/16)) * 4; + const int qi = qn0 + t; + uint4 v = (uint4)(0u); + if (qi < n_q && u < cb*8) { + v = vload4(0, &qq[(qbase + qi)*nu + c0*8 + u]); + } + vstore4(v, 0, &sh_q[t*(KQ_DKC/4) + u]); + } + for (int i = lid; i < KQ_TN*(KQ_DKC/32); i += KQ_WG) { + const int t = i / (KQ_DKC/32); + const int b = i % (KQ_DKC/32); + const int qi = qn0 + t; + sh_qd[t][b] = (qi < n_q && b < cb) ? qd[(qbase + qi)*nblk + c0 + b] : (half)0.0f; + } + barrier(CLK_LOCAL_MEM_FENCE); + + for (int b = 0; b < cb; ++b) { + const uint4 w0 = vload4(0, &kq[kbase + (c0 + b)*8]); + const uint4 w1 = vload4(0, &kq[kbase + (c0 + b)*8 + 4]); + const float dks = (float)kd[kdbas + c0 + b]; + + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + const uint4 a0 = vload4(0, &sh_q[t*(KQ_DKC/4) + b*8]); + const uint4 a1 = vload4(0, &sh_q[t*(KQ_DKC/4) + b*8 + 4]); + int raw = 0; + raw = dot_acc_sat_4x8packed_ss_int(w0.s0, a0.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s1, a0.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s2, a0.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s3, a0.s3, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s0, a1.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s1, a1.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s2, a1.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s3, a1.s3, raw); + acc[t] += dks * (float)sh_qd[t][b] * (float)raw; + } + } + } + + // Finish reading the Q slice before writing scores to the same local memory. + const int kvblk0 = kv - lid; + barrier(CLK_LOCAL_MEM_FENCE); + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + p8_lds[t*64 + lid] = acc[t]; + } + barrier(CLK_LOCAL_MEM_FENCE); + { + const int j = lid >> 1; + const int b = lid & 1; + const int n = qn0 + j; + if (n < n_q) { + const int kvb = kvblk0 + b*32; + __local float * src = p8_lds + j*64 + b*32; + const global half * mp = mrow + (size_t)n*mstride + kvb; + float4 s = vload4(0, src)*scale + slope*convert_float4(vload4(0, mp)); + vstore4(s, 0, src); + float amax = fmax(fmax(s.x, s.y), fmax(s.z, s.w)); + for (int c = 1; c < 8; ++c) { + s = vload4(c, src)*scale + slope*convert_float4(vload4(c, mp)); + vstore4(s, c, src); + amax = fmax(amax, fmax(fmax(s.x, s.y), fmax(s.z, s.w))); + } + const size_t prow = qbase + n; + const int blk = kvb >> 5; + global uchar * qdst = qp + prow*(size_t)p_pitch + (size_t)kvb; + float sum = 0.0f; + // finite sentinel: the program builds with -cl-finite-math-only + if (amax > -1.0e30f) { + for (int c = 0; c < 8; ++c) { + const float4 e = exp(vload4(c, src) - amax); + sum += (e.x + e.y) + (e.z + e.w); + vstore4(convert_uchar4_sat_rte(e*255.0f), c, qdst); + } + } else { + for (int c = 0; c < 8; ++c) { + vstore4((uchar4)(0), c, qdst); + } + } + bmax[prow*pblk + blk] = amax; + bsum[prow*pblk + blk] = sum; + } + } + } +} From 50518b64c6f2191a116d2760042f106c4b3387d7 Mon Sep 17 00:00:00 2001 From: Imdadullah Mohammed <7274724+imdadvs@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:21:03 +1100 Subject: [PATCH 08/88] model : hrm : do not compute slot count as uint32_t (#32601) load_arch_hparams multiplies n_hrm_layers_per_stack, n_hrm_h_cycles and (n_hrm_l_cycles + 1) into a uint32_t, then asserts the product equals block_count. Any factors whose true product is block_count + k*2^32 still pass the assert; 1073741825 * 2 * 2 = 2^32 + 4 compares equal to block_count = 4. load_arch_tensors iterates the same three values in int and writes past the end of the block_count-sized layers vector. --- src/models/hrm-text.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/models/hrm-text.cpp b/src/models/hrm-text.cpp index 8e3b34c57580..4c3d52e32702 100644 --- a/src/models/hrm-text.cpp +++ b/src/models/hrm-text.cpp @@ -1,5 +1,7 @@ #include "models.h" +#include + // HRM-Text: alternating low/high transformer stacks over the same token stream. // Reference: HrmTextModel in transformers, DFM Mimir 1B. @@ -19,8 +21,15 @@ void llama_model_hrm_text::load_arch_hparams(llama_model_loader & ml) { GGML_ASSERT(hparams.n_hrm_l_cycles > 0); // the GGUF block count is the expanded cache-slot count - const uint32_t n_slot = hparams.n_hrm_layers_per_stack * hparams.n_hrm_h_cycles * (hparams.n_hrm_l_cycles + 1); - GGML_ASSERT(hparams.n_layer() == n_slot); + // 64-bit: a 32-bit product can wrap and match n_layer(), then load_arch_tensors() indexes past model.layers + const uint64_t n_slot = (uint64_t) hparams.n_hrm_layers_per_stack * hparams.n_hrm_h_cycles * (hparams.n_hrm_l_cycles + 1); + if (hparams.n_hrm_layers_per_stack >= hparams.n_layer() || n_slot != hparams.n_layer()) { + throw std::runtime_error(format( + "hrm: cache-slot count %" PRIu64 " (layers_per_stack %u, h_cycles %u, l_cycles %u) " + "does not match block_count %u", + n_slot, hparams.n_hrm_layers_per_stack, hparams.n_hrm_h_cycles, + hparams.n_hrm_l_cycles, hparams.n_layer())); + } switch (hparams.n_embd) { case 1536: From b94959a64d011915d77a5381c7d4846dcda99530 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20G=C3=A4=C3=9Fler?= Date: Thu, 19 Nov 2026 23:21:24 +0100 Subject: [PATCH 09/88] CUDA: implement support for duplicate expert IDs (#32505) implement support for duplicate expert IDs --- ggml/include/ggml.h | 6 - ggml/src/ggml-cuda/common.cuh | 10 ++ ggml/src/ggml-cuda/fattn.cu | 23 +-- ggml/src/ggml-cuda/ggml-cuda.cu | 3 +- ggml/src/ggml-cuda/mmf.cu | 9 +- ggml/src/ggml-cuda/mmf.cuh | 245 +++++++++----------------------- ggml/src/ggml-cuda/mmid.cu | 209 ++++++++++++++++++++------- ggml/src/ggml-cuda/top-k.cu | 11 +- tests/test-backend-ops.cpp | 6 +- 9 files changed, 251 insertions(+), 271 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 284825ca6caf..dc9997514d06 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -1316,12 +1316,6 @@ extern "C" { // indirect matrix multiplication // an id of -1 skips the slot and zeroes the matching row of the result - // - // [TAG_MUL_MAT_ID_DUPLICATE_ID] - // note: this op has undefined behaviour if a given `a` is referenced more than once for a given `b` - // (i.e. duplicate experts per token are not guaranteed to be supported in all backends) - // TODO: add backend support: https://github.com/ggml-org/llama.cpp/pull/29998#issuecomment-6153742533 - // the CPU backend skips negative ids, their rows of the result are zero GGML_API struct ggml_tensor * ggml_mul_mat_id( struct ggml_context * ctx, struct ggml_tensor * as, diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index fd047d7c3333..053ed60f798b 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -452,6 +452,16 @@ static __device__ __forceinline__ ggml_cuda_thread_mask_t ggml_cuda_ballot(int p return __ballot_sync(mask, predicate); } +static __device__ __forceinline__ int ggml_cuda_popc(ggml_cuda_thread_mask_t x) { + static_assert(sizeof(ggml_cuda_thread_mask_t) == 4 || sizeof(ggml_cuda_thread_mask_t) == 8, "unsupported thread mask type"); + if constexpr (sizeof(ggml_cuda_thread_mask_t) == 4) { + return __popc(x); + } else { + return __popcll(x); + } +} +template static __device__ __forceinline__ int ggml_cuda_popc(T x) = delete; // Makes implicit type casts result in an error. + static __device__ __forceinline__ int ggml_cuda_all(int predicate, ggml_cuda_thread_mask_t mask = GGML_CUDA_FULL_THREAD_MASK) { return __all_sync(mask, predicate); } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 2e32760847bc..10aa5af15863 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -17,15 +17,6 @@ static __global__ void flash_attn_mask_to_sparse_indices( constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int values_per_lane = 8; - using lane_mask_t = std::conditional_t; - constexpr uint64_t ballot_mask = ~(lane_mask_t)0; - const auto popc = [](const lane_mask_t mask) { - if constexpr (warp_size == 64) { - return __popcll(mask); - } else { - return __popc(mask); - } - }; const int tid = threadIdx.x; const int warp = tid / warp_size; const int lane = tid % warp_size; @@ -48,7 +39,7 @@ static __global__ void flash_attn_mask_to_sparse_indices( __syncthreads(); for (int i0 = 0; i0 < ne30; i0 += blockDim.x*values_per_lane) { - lane_mask_t selected_warp[values_per_lane]; + ggml_cuda_thread_mask_t selected_warp[values_per_lane]; int warp_count = 0; #pragma unroll for (int item = 0; item < values_per_lane; ++item) { @@ -60,8 +51,8 @@ static __global__ void flash_attn_mask_to_sparse_indices( selected |= (!oob || q < q1 - q0) && isfinite(__half2float(mask[q*s31 + i])); } } - selected_warp[item] = (lane_mask_t)ggml_cuda_ballot((int) selected, ballot_mask); - warp_count += popc(selected_warp[item]); + selected_warp[item] = ggml_cuda_ballot((int) selected); + warp_count += ggml_cuda_popc(selected_warp[item]); } if (lane == 0) { @@ -81,16 +72,16 @@ static __global__ void flash_attn_mask_to_sparse_indices( } __syncthreads(); - const lane_mask_t lane_mask = lane == 0 ? 0 : ((lane_mask_t)1 << lane) - 1; + const ggml_cuda_thread_mask_t lane_mask = lane == 0 ? 0 : ((ggml_cuda_thread_mask_t)1 << lane) - 1; int warp_item_offset = 0; #pragma unroll for (int item = 0; item < values_per_lane; ++item) { const int i = i0 + (warp*values_per_lane + item)*warp_size + lane; - const int dst = row_count + warp_offsets[warp] + warp_item_offset + popc(selected_warp[item] & lane_mask); - if ((selected_warp[item] & ((lane_mask_t)1 << lane)) && dst < n_kv_max) { + const int dst = row_count + warp_offsets[warp] + warp_item_offset + ggml_cuda_popc(selected_warp[item] & lane_mask); + if ((selected_warp[item] & ((ggml_cuda_thread_mask_t)1 << lane)) && dst < n_kv_max) { indices[dst] = i; } - warp_item_offset += popc(selected_warp[item]); + warp_item_offset += ggml_cuda_popc(selected_warp[item]); } __syncthreads(); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index a58f020c29df..a2db28adefdf 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -2730,7 +2730,8 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * ids_from_sorted_host[i12*n_expert_used + iex] = ids_to_sorted_host.size(); ids_to_sorted_host.push_back(i12*ne11 + iex % ne11); tokens_per_expert[i02]++; - break; + // TODO: removing the break here was done to make duplicate IDs work but this caused a ~10% performance regression, better solution needed. + // break; } } } diff --git a/ggml/src/ggml-cuda/mmf.cu b/ggml/src/ggml-cuda/mmf.cu index 040d390e0cc5..396ad1c1184d 100644 --- a/ggml/src/ggml-cuda/mmf.cu +++ b/ggml/src/ggml-cuda/mmf.cu @@ -43,7 +43,6 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr const int64_t s13 = src1->nb[3] / ts_src1; const int64_t s3 = dst->nb[3] / ts_dst; - const int64_t ids_s0 = ids ? ids->nb[0] / ggml_type_size(ids->type) : 0; const int64_t ids_s1 = ids ? ids->nb[1] / ggml_type_size(ids->type) : 0; mmf_ids_data ids_info{}; @@ -70,7 +69,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr nchannels_y = ids->ne[0]; } - if (ids && ncols_dst > 16) { + if (ids) { const int64_t n_expert_used = ids->ne[0]; const int64_t n_experts = ne02; const int64_t n_tokens = ne12; @@ -110,7 +109,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 1; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; case GGML_TYPE_F16: { @@ -118,7 +117,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 2; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; case GGML_TYPE_BF16: { @@ -126,7 +125,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 2; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; default: diff --git a/ggml/src/ggml-cuda/mmf.cuh b/ggml/src/ggml-cuda/mmf.cuh index c49f6c47ad1d..46a123a5c3c1 100644 --- a/ggml/src/ggml-cuda/mmf.cuh +++ b/ggml/src/ggml-cuda/mmf.cuh @@ -47,12 +47,11 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr bool ggml_cuda_should_use_mmf(enum ggml_type type, int cc, int warp_size, const int64_t * scr0_ne, const size_t * src0_nb, const int src1_ncols, bool mul_mat_id); -template +template __launch_bounds__(ggml_cuda_get_physical_warp_size()*nwarps, 1) static __global__ void mul_mat_f( - const T * __restrict__ x, const float * __restrict__ y, const int32_t * __restrict__ ids, float * __restrict__ dst, - const int ncols, const int ncols_dst_total, const int nchannels_dst, const int stride_row, const int stride_col_y, const int stride_col_dst, - const int stride_col_id, const int stride_row_id, + const T * __restrict__ x, const float * __restrict__ y, float * __restrict__ dst, + const int ncols, const int stride_row, const int stride_col_y, const int stride_col_dst, const int channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, const int sample_ratio, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst) { // TODO: handle this in a consistent and simpler way after AMD MFMA support has been added @@ -90,85 +89,26 @@ static __global__ void mul_mat_f( constexpr int ntA = rows_per_block / tile_A::I; constexpr int ntB = (cols_per_block + tile_B::I - 1) / tile_B::I; - const int row0 = blockIdx.x * rows_per_block; - - int expert_idx = 0; - [[maybe_unused]] int col_base = 0; - - const int channel_dst = has_ids ? 0 : blockIdx.y; - - if constexpr (has_ids) { - // experts + tiles of ncols_dst are packed in the y dimension - int col_tiles = (ncols_dst_total + cols_per_block - 1) / cols_per_block; - const int nchannels_x = gridDim.y / col_tiles; - const int tile_idx = blockIdx.y / nchannels_x; - expert_idx = blockIdx.y - tile_idx * nchannels_x; - col_base = tile_idx * cols_per_block; - } + const int row0 = blockIdx.x * rows_per_block; - const int channel_x = has_ids ? expert_idx : (channel_dst / channel_ratio); + const int channel_dst = blockIdx.y; + const int channel_x = channel_dst / channel_ratio; const int channel_y = channel_dst; const int sample_dst = blockIdx.z; const int sample_x = sample_dst / sample_ratio; const int sample_y = sample_dst; x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row0*stride_row ; - y += int64_t(sample_y) *stride_sample_y + (has_ids ? 0 : channel_y *stride_channel_y); - dst += int64_t(sample_dst)*stride_sample_dst + (has_ids ? 0 : channel_dst*stride_channel_dst); - - if constexpr (has_ids) { - constexpr int y_stride_scale = std::is_same_v ? 1 : 2; - const int64_t col_offset = col_base; - y += col_offset * stride_col_y * y_stride_scale; - dst += col_offset * stride_col_dst; - ids += col_offset * stride_row_id; - } + y += int64_t(sample_y) *stride_sample_y + channel_y *stride_channel_y; + dst += int64_t(sample_dst)*stride_sample_dst + channel_dst*stride_channel_dst; [[maybe_unused]] const float2 * y2 = (const float2 *) y; extern __shared__ char data_mmv[]; - char * shmem_base = data_mmv; - [[maybe_unused]] int * slot_map = (int *) shmem_base; - char * compute_base = has_ids ? (shmem_base + GGML_PAD(cols_per_block, 16) * sizeof(int)) : shmem_base; - tile_C C[ntA][ntB]; - T * tile_xy = (T *) compute_base + threadIdx.y*(tile_A::I * tile_k_padded); - - if constexpr (has_ids) { - int found = 0; - - for (int j0 = 0; j0 < cols_per_block; j0 += nwarps) { - const int j = j0 + threadIdx.y; - - if (threadIdx.x == 0) { - slot_map[j] = -1; - } - ggml_cuda_syncwarp(); - - if (col_base + j >= ncols_dst_total) { - continue; - } - - const int32_t * __restrict__ id_row = ids + j*stride_row_id; - - for (int k = threadIdx.x; k < nchannels_dst; k += warp_size) { - int match = id_row[k*stride_col_id] == expert_idx; - - if (match) { - slot_map[j] = k; - found = 1; - break; - } - } - } - - if (!__syncthreads_or(found)) { - return; - } - } - + T * tile_xy = (T *) data_mmv + threadIdx.y*(tile_A::I * tile_k_padded); for (int col = threadIdx.y*warp_size + threadIdx.x; col < ncols; col += nwarps*warp_size) { tile_A A[ntA][warp_size / tile_A::J]; @@ -194,26 +134,15 @@ static __global__ void mul_mat_f( for (int j0 = 0; j0 < tile_B::I; ++j0) { const int j = j0 + itB*tile_B::I; - if constexpr (!has_ids) { - tile_xy[j0*tile_k_padded + threadIdx.x] = j < cols_per_block ? y[j*stride_col_y + col] : 0.0f; - } else { - const bool valid = j < cols_per_block && (col_base + j) < ncols_dst_total && slot_map[j] >= 0; - tile_xy[j0*tile_k_padded + threadIdx.x] = valid ? y[slot_map[j]*stride_channel_y + j*stride_col_y + col] : 0.0f; - } + tile_xy[j0*tile_k_padded + threadIdx.x] = j < cols_per_block ? y[j*stride_col_y + col] : 0.0f; } } else if constexpr (std::is_same_v || std::is_same_v) { #pragma unroll for (int j0 = 0; j0 < tile_B::I; ++j0) { const int j = j0 + itB*tile_B::I; - if constexpr (!has_ids) { - const float2 tmp = j < cols_per_block ? y2[j*stride_col_y + col] : make_float2(0.0f, 0.0f); - tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); - } else { - const bool valid = j < cols_per_block && (col_base + j) < ncols_dst_total && slot_map[j] >= 0; - float2 tmp = valid ? *(const float2*) &y[slot_map[j]*stride_channel_y + 2*(j*stride_col_y + col)] : make_float2(0.0f, 0.0f); - tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); - } + const float2 tmp = j < cols_per_block ? y2[j*stride_col_y + col] : make_float2(0.0f, 0.0f); + tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); } } else { static_assert(std::is_same_v, "unsupported type"); @@ -231,7 +160,7 @@ static __global__ void mul_mat_f( } } - float * buf_iw = (float *) compute_base; + float * buf_iw = (float *) data_mmv; constexpr int kiw = nwarps*rows_per_block + mmf_get_padding(); if (nwarps > 1) { @@ -278,26 +207,15 @@ static __global__ void mul_mat_f( } } - if constexpr (!has_ids) { #pragma unroll - for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { - dst[j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; - } - } else { - const int slot = (j < cols_per_block) ? slot_map[j] : -1; - if (slot >= 0 && (col_base + j) < ncols_dst_total) { -#pragma unroll - for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { - dst[slot*stride_channel_dst + j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; - } - } + for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { + dst[j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; } } } #else - GGML_UNUSED_VARS(x, y, ids, dst, - ncols, ncols_dst_total, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, + GGML_UNUSED_VARS(x, y, dst, + ncols, stride_row, stride_col_y, stride_col_dst, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); NO_DEVICE_CODE; @@ -588,22 +506,21 @@ static __global__ void mul_mat_f_ids( template static inline void mul_mat_f_switch_ids( - const T * x, const float * y, const int32_t * ids, float * dst, + const T * x, const float * y, float * dst, const int64_t ncols_x, const int64_t ncols_dst, const int64_t nchannels_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int64_t stride_row_id, const int64_t channel_ratio, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t sample_ratio, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, const dim3 & block_nums, const dim3 & block_dims, const int nbytes_shared_total, cudaStream_t stream, const mmf_ids_data * ids_data) { + const bool has_ids_data = ids_data && ids_data->ids_src_compact; - // Use the compact-ids kernel only for larger tiles; for small ncols_dst (< 16) - // we prefer the normal mul_mat_f path with has_ids=true. - if (has_ids_data && ncols_dst > 16) { + if (has_ids_data) { if (ids_data->max_tiles == 0) { return; } + GGML_ASSERT(block_nums.z == 1); dim3 block_nums_ids(block_nums.x, ids_data->max_tiles, 1); const uint3 sis1_fd = ids_data->sis1 > 0 ? init_fastdiv_values((uint32_t) ids_data->sis1) : make_uint3(0, 0, 1); @@ -615,19 +532,10 @@ static inline void mul_mat_f_switch_ids( channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, sis1_fd, nch_fd); - } else if (ids) { - const int64_t col_tiles = (ncols_dst + cols_per_block - 1) / cols_per_block; - dim3 block_nums_ids = block_nums; - block_nums_ids.y *= col_tiles; - - mul_mat_f<<>> - (x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); } else { - mul_mat_f<<>> - (x, y, ids, dst, ncols_x, cols_per_block, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, + mul_mat_f<<>> + (x, y, dst, ncols_x, stride_row, stride_col_y, stride_col_dst, + channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); } } @@ -637,7 +545,6 @@ void mul_mat_f_cuda( const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int64_t stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, @@ -673,70 +580,59 @@ void mul_mat_f_cuda( const int nbytes_shared_iter = nwarps_best * (volta_mma_available(cc) ? tile_A_32::I : tile_A_16::I) * (warp_size + mmf_get_padding(cc)) * 4; const int nbytes_cols_per_block_pad = (amd_wmma_available(cc) || amd_mfma_available(cc)) ? tile_B_16::I : tile_B_8::I; const int nbytes_shared_combine = GGML_PAD(cols_per_block, nbytes_cols_per_block_pad) * (nwarps_best*rows_per_block + mmf_get_padding(cc)) * 4; - const int nbytes_shared = std::max(nbytes_shared_iter, nbytes_shared_combine); - const int nbytes_slotmap = ids ? GGML_PAD(cols_per_block, 16) * sizeof(int) : 0; - const int nbytes_shared_total = nbytes_shared + nbytes_slotmap; - const int64_t grid_y = ids ? nchannels_x : nchannels_dst; + const int nbytes_shared_total = std::max(nbytes_shared_iter, nbytes_shared_combine); - const dim3 block_nums(nrows_x/rows_per_block, grid_y, nsamples_dst); + const dim3 block_nums(nrows_x/rows_per_block, nchannels_dst, nsamples_dst); const dim3 block_dims(warp_size, nwarps_best, 1); switch (nwarps_best) { case 1: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 2: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 3: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 4: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 5: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 6: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 7: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 8: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; default: GGML_ABORT("fatal error"); @@ -750,95 +646,94 @@ static void mul_mat_f_switch_cols_per_block( const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, cudaStream_t stream, const mmf_ids_data * ids_data) { - const int ncols_case = (ids && ncols_dst > 16) ? 16 : ncols_dst; + const int ncols_case = ids ? 16 : ncols_dst; GGML_ASSERT(ids || ncols_dst <= 16); switch (ncols_case) { case 1: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 2: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 3: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 4: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 5: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 6: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 7: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 8: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 9: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 10: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 11: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 12: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 13: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 14: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 15: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 16: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; default: @@ -851,7 +746,6 @@ static void mul_mat_f_switch_rows_per_block( const int rows_per_block, const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, @@ -860,13 +754,13 @@ static void mul_mat_f_switch_rows_per_block( case MMF_ROWS_PER_BLOCK: { mul_mat_f_switch_cols_per_block( x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case MMF_ROWS_PER_BLOCK_CDNA: { mul_mat_f_switch_cols_per_block( x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; default: @@ -878,7 +772,6 @@ static void mul_mat_f_switch_rows_per_block( template void mul_mat_f_cuda( \ const T * x, const float * y, const int32_t * ids, float * dst, \ const int64_t ncols_x, const int64_t nrows_x, int64_t ncols_dst_total, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, \ - const int64_t stride_col_id, const int64_t stride_row_id, \ const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, \ const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x,\ const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, \ diff --git a/ggml/src/ggml-cuda/mmid.cu b/ggml/src/ggml-cuda/mmid.cu index 6b425a377244..fe9458763e13 100644 --- a/ggml/src/ggml-cuda/mmid.cu +++ b/ggml/src/ggml-cuda/mmid.cu @@ -24,6 +24,50 @@ template struct mm_ids_pow2 { static constexpr int value = 2*mm_ids_pow2 template <> struct mm_ids_pow2<1> { static constexpr int value = 1; }; template <> struct mm_ids_pow2<0> { static constexpr int value = 1; }; +template +static __device__ __forceinline__ void check_experts( + mm_ids_helper_store * store, int & nex_prev, int & it_compact, + const int expert, const int it, const int iex, const int expert_found) { + if (increment_nex_prev) { + nex_prev += expert_found < expert; + } + + if (write_to_store) { + const ggml_cuda_thread_mask_t iex_used = ggml_cuda_ballot(expert_found == expert); + const ggml_cuda_thread_mask_t mask = (ggml_cuda_thread_mask_t(1) << threadIdx.x) - 1; + const int it_compact_offset = ggml_cuda_popc(iex_used & mask); + + if (expert_found == expert) { + store[it_compact + it_compact_offset] = mm_ids_helper_store(it, iex); + } + + it_compact += ggml_cuda_popc(iex_used); + } +} + +static __device__ __forceinline__ void dump_store( + int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, + const int n_expert_used, const int nchannels_y, const int sis1, const bool write_inverse, + const mm_ids_helper_store * __restrict__ store, const int nex_prev, int & n_dumped, const int it_compact) { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + + for (int itc = threadIdx.x; itc < it_compact; itc += warp_size) { + const mm_ids_helper_store store_it = store[itc]; + const int it = store_it.it(); + const int iex_used = store_it.iex_used(); + ids_dst[nex_prev + n_dumped + itc] = it*n_expert_used + iex_used; + // ids_src1 holds the forward map, or the inverse map (token slot -> compact row) for quant dedup + if (write_inverse) { + ids_src1[it*n_expert_used + iex_used] = nex_prev + n_dumped + itc; + } else { + ids_src1[nex_prev + n_dumped + itc] = it*sis1 + iex_used % nchannels_y; + } + } + n_dumped += it_compact; +} + +constexpr int n_unroll = 4; // Manually unroll this many loop iterations for better performance. + // Helper function for mul_mat_id, converts ids to a more convenient format. // ids_src1 describes how to permute the flattened column indices of src1 in order to get a compact src1 tensor sorted by expert. // ids_dst describes the same mapping but for the dst tensor. @@ -36,85 +80,138 @@ static __global__ void mm_ids_helper( const int32_t * __restrict__ ids, int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec, const int n_tokens, const int n_expert_used_var, const int nchannels_y, const uint3 tile_width, - const int si1, const int sis1, const bool write_inverse) { + const int si1, const int sis1, const bool write_inverse, const int ne_store) { constexpr int warp_size = ggml_cuda_get_physical_warp_size(); const int n_expert_used = n_expert_used_template == 0 ? n_expert_used_var : n_expert_used_template; - const int expert = blockIdx.x; + + const int expert = blockIdx.x; // The expert this CUDA block handles. extern __shared__ char data_mm_ids_helper[]; mm_ids_helper_store * store = (mm_ids_helper_store *) data_mm_ids_helper; int nex_prev = 0; // Number of columns for experts with a lower index. + int n_dumped = 0; // Number of data values that have been dumped to output buffers. int it_compact = 0; // Running index for the compact slice of this expert. + // Step 1: Iterate over n_tokens, increment nex_prev to determine the output indices, fill up store. + // Step 1.5: If the store does not have enough space to hold all values, iterate over the rest of the tokens just to increment nex_prev. + // Step 2: Dump the stored values using nex_prev to get the correct output indices. + // Step 3: If we were not able to process all values, resume at the index up to which we were able to dump the output and re-do. + if constexpr (n_expert_used_template == 0) { // Generic implementation: - for (int it = 0; it < n_tokens; ++it) { - int iex_used = -1; // The index at which the expert is used, if any. - for (int iex = threadIdx.x; iex < n_expert_used; iex += warp_size) { - const int expert_used = ids[it*si1 + iex]; - nex_prev += expert_used < expert; - if (expert_used == expert) { - iex_used = iex; - } + int it = 0; + for (; it < n_tokens && it_compact + max(warp_size, n_expert_used) <= ne_store; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + int it_dumped = it; + for (; it < n_tokens; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; - if (iex_used != -1) { - store[it_compact] = mm_ids_helper_store(it, iex_used); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = false; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + + nex_prev = warp_reduce_sum(nex_prev); + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; - if (warp_reduce_any(iex_used != -1)) { - it_compact++; + for (int it = it_dumped; it < n_tokens; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = false; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + if (it_compact + max(warp_size, n_expert_used) >= ne_store) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + } } } + if (it_compact > 0) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + } } else { // Implementation optimized for specific numbers of experts used: // a warp holds a whole number of token slots, so the slot count is padded to a power of 2 constexpr int neu_padded = mm_ids_pow2::value; static_assert(neu_padded <= warp_size && warp_size % neu_padded == 0, "bad n_expert_used"); - for (int it0 = 0; it0 < n_tokens; it0 += warp_size/neu_padded) { - const int it = it0 + threadIdx.x / neu_padded; - - const int iex = threadIdx.x % neu_padded; // The index at which the expert is used, if any. - const int expert_used = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? - ids[it*si1 + iex] : INT_MAX; - const int iex_used = expert_used == expert ? iex : -1; - nex_prev += expert_used < expert; - - // Whether the threads at this token position have used the expert: - const int it_compact_add_self = warp_reduce_any(iex_used != -1); + const int iex = threadIdx.x % neu_padded; // The index at which the expert is used, if any. - // Do a scan over threads at lower token positions in warp to get the correct index for writing data: - int it_compact_add_lower = 0; + int it0 = 0; + for (; it0 < n_tokens && it_compact + n_unroll*warp_size <= ne_store; it0 += n_unroll*warp_size/neu_padded) { #pragma unroll - for (int offset = neu_padded; offset < warp_size; offset += neu_padded) { - const int tmp = ggml_cuda_shfl_up(it_compact_add_self, offset, warp_size); - if (threadIdx.x >= static_cast(offset)) { - it_compact_add_lower += tmp; - } - } + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; - if (iex_used != -1) { - store[it_compact + it_compact_add_lower] = mm_ids_helper_store(it, iex_used); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + int it0_dumped = it0; + for (; it0 < n_tokens; it0 += n_unroll*warp_size/neu_padded) { +#pragma unroll + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; - // The thread with the highest index in the warp always has the sum over the whole warp, use it to increment all threads: - it_compact += ggml_cuda_shfl(it_compact_add_lower + it_compact_add_self, warp_size - 1, warp_size); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = false; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + } } - } - nex_prev = warp_reduce_sum(nex_prev); - ggml_cuda_syncwarp(); - for (int itc = threadIdx.x; itc < it_compact; itc += warp_size) { - const mm_ids_helper_store store_it = store[itc]; - const int it = store_it.it(); - const int iex_used = store_it.iex_used(); - ids_dst[nex_prev + itc] = it*n_expert_used + iex_used; - // ids_src1 holds the forward map, or the inverse map (token slot -> compact row) for quant dedup - if (write_inverse) { - ids_src1[it*n_expert_used + iex_used] = nex_prev + itc; - } else { - ids_src1[nex_prev + itc] = it*sis1 + iex_used % nchannels_y; + nex_prev = warp_reduce_sum(nex_prev); + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + + for (it0 = it0_dumped; it0 < n_tokens; it0 += n_unroll*warp_size/neu_padded) { +#pragma unroll + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = false; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + if (it_compact + warp_size >= ne_store) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + } + } + } + if (it_compact > 0) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); } } @@ -123,7 +220,7 @@ static __global__ void mm_ids_helper( } int col_low = nex_prev; - int col_high = nex_prev + min(int(tile_width.z), it_compact); + int col_high = nex_prev + min(int(tile_width.z), n_dumped); // The while loop covers all tiles at the seams containing the column with % tile_width == 0. while (col_high > fastdiv(col_low + tile_width.z - 1, tile_width) * tile_width.z) { @@ -131,7 +228,7 @@ static __global__ void mm_ids_helper( = {expert, col_low, col_high, /*padding =*/ 0}; col_low = col_high; - col_high = min(col_high + int(tile_width.z), nex_prev + it_compact); + col_high = min(col_high + int(tile_width.z), nex_prev + n_dumped); } // Finally, at most one extra tile_spec between the seams per expert. @@ -157,10 +254,12 @@ static void launch_mm_ids_helper( const dim3 num_blocks(n_experts, 1, 1); const dim3 block_size(warp_size, 1, 1); - const size_t nbytes_shared = n_tokens*sizeof(mm_ids_helper_store); - GGML_ASSERT(nbytes_shared <= smpbo); + const size_t ne_shared_pad = n_expert_used_template == 0 ? std::max(n_expert_used_var, warp_size) : n_unroll*warp_size; + const size_t nbytes_store_core = std::min(smpbo - ne_shared_pad * sizeof(mm_ids_helper_store), n_tokens * sizeof(mm_ids_helper_store)); + const size_t nbytes_shared = nbytes_store_core + ne_shared_pad * sizeof(mm_ids_helper_store); + const size_t ne_store = nbytes_shared / sizeof(mm_ids_helper_store); mm_ids_helper<<>> - (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse); + (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse, ne_store); } void ggml_cuda_launch_mm_ids_helper( diff --git a/ggml/src/ggml-cuda/top-k.cu b/ggml/src/ggml-cuda/top-k.cu index 227751eeadeb..2639a664d034 100644 --- a/ggml/src/ggml-cuda/top-k.cu +++ b/ggml/src/ggml-cuda/top-k.cu @@ -184,13 +184,6 @@ static __global__ void top_k_radix_gather( constexpr int NBINS = 1 << RADIX_BITS; constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int nwarps = BLOCK_SIZE / warp_size; - const auto popc = [](const ggml_cuda_thread_mask_t mask) { - if constexpr (warp_size == 64) { - return __popcll(mask); - } else { - return __popc(mask); - } - }; __shared__ int warp_ties[nwarps]; const int row = blockIdx.x / blocks_per_row; @@ -247,11 +240,11 @@ static __global__ void top_k_radix_gather( const bool is_tie = col < warp_end && top_k_float_to_ordered(row_src[col]) == threshold; const ggml_cuda_thread_mask_t ties = ggml_cuda_ballot(is_tie); - const int tie_pos = pos + popc(ties & (((ggml_cuda_thread_mask_t) 1 << lane) - 1)); + const int tie_pos = pos + ggml_cuda_popc(ties & (((ggml_cuda_thread_mask_t) 1 << lane) - 1)); if (is_tie && tie_pos < pos_end) { row_dst[k - rank + tie_pos] = col; } - pos += popc(ties); + pos += ggml_cuda_popc(ties); } } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index d6b849944830..6d99453d89c4 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -12407,6 +12407,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_F32, 16, 16, b, 50, 200, 64)); } + // One very large one to trigger a code path in CUDA requiring >1 pass over expert IDs due to shared memory limits: + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q8_0, GGML_TYPE_F32, 16, 16, false, 32, 65536, 256)); + // For issue 27873 test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_IQ2_XXS, GGML_TYPE_F32, 1, 1, false, 1, 8192, 4096)); @@ -12441,8 +12444,6 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_TQ1_0, GGML_TYPE_F32, 28, 10, false, 1024, 1, 4096)); test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_TQ1_0, GGML_TYPE_F32, 128, 8, false, 1024, 1, 2048)); - // TODO: disabled until CUDA backend support is added [TAG_MUL_MAT_ID_DUPLICATE_ID] -#if 0 // repeated expert ids within a row for (ggml_type ta : {GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { for (int n : {9, 16, 33, 64}) { @@ -12454,7 +12455,6 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id_dup(ta, GGML_TYPE_F32, 1025, 10, false, 64, 33, 256, 0, true)); test_cases.emplace_back(new test_mul_mat_id_dup(ta, GGML_TYPE_F32, 2050, 10, true, 64, 33, 256)); } -#endif for (ggml_type type_a : all_types) { test_cases.emplace_back(new test_mul_mat_id(type_a, GGML_TYPE_F32, 4, 2, false, 64, 16, 3*ggml_blck_size(type_a))); From 8bf88ba9368e70fe3ba1b0001b34e70ffc713716 Mon Sep 17 00:00:00 2001 From: Hongqiang Wang Date: Thu, 19 Nov 2026 20:58:46 -0800 Subject: [PATCH 10/88] vulkan: disable subgroup arithmetic on Qualcomm's driver (#30826) On Adreno, subgroupAdd() after divergent code returns wrong sums. The fused ADD+RMS_NORM partial-sum path hits this, so the decode-step norm is garbage and models emit stray tokens after long prompts. Clear subgroup_arithmetic for the Qualcomm proprietary driver, which also turns off add_rms_fusion and the other subgroupAdd paths. test-backend-ops on Adreno 850 and X2-90: ADD_RMS_NORM 20/25 -> 25/25, RMS_NORM_MUL_ADD 33/45 -> 45/45. llama 3B Q4_0 on Adreno 850: pp512 and tg128 unchanged. --- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index ecd46d8282d2..cd8ef9ba3362 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4735,6 +4735,10 @@ vk_device ggml_vk_get_device(size_t idx) { device->subgroup_arithmetic = false; } #endif + // Workaround for subgroupAdd() returning wrong sums on Adreno after divergent code + if (device->driver_id == vk::DriverId::eQualcommProprietary) { + device->subgroup_arithmetic = false; + } device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle); #ifdef __APPLE__ From 7e960f40fb0bd2eede76406f807d6bc3f7aa339c Mon Sep 17 00:00:00 2001 From: shaofeiqi Date: Thu, 19 Nov 2026 22:26:28 -0800 Subject: [PATCH 11/88] opencl: fold GQA head for f16 FA for better efficiency (#32631) Assisted-by: Codex Co-authored-by: Li He Co-authored-by: Hongqiang Wang --- ggml/src/ggml-opencl/ggml-opencl.cpp | 13 ++++++-- .../kernels/mul_mm_f16_f32_kq_p8.cl | 30 ++++++++++++------- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 776a8e75776a..894f8235e9a0 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -23128,8 +23128,17 @@ static void ggml_cl_fa_kq_p8_dispatch( CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); - const size_t n_tiles = (N + 31) / 32; - size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * D_B}; + // Pack query heads of each KV group into a short batch's tile. + static const bool fold_enabled = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_P8_FOLD"); + return !e || e[0] != '0'; + }(); + const int gqa = D_B / D_A; + const int fold = fold_enabled && gqa > 1 && N < 32 && gqa <= INT_MAX / N ? gqa : 1; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &fold)); + + const size_t n_tiles = ((size_t) N * fold + 31) / 32; + size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * (fold > 1 ? D_A : D_B)}; const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl index 2c0a56c855c7..9c4f71a6d910 100644 --- a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl +++ b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl @@ -119,7 +119,8 @@ __kernel void mul_mm_f16_f32_kq_p8( int N, int D_A, int D_B, - int p_pitch // bytes per P row, >= M, multiple of 32 + int p_pitch, // bytes per P row, >= M, multiple of 32 + int gqa_fold ) { // Match the n-tile-first grid in ggml_cl_fa_kq_p8_dispatch. @@ -135,7 +136,8 @@ __kernel void mul_mm_f16_f32_kq_p8( const uint col = block_id_m * TILESIZE_M; const uint row = block_id_n * TILESIZE_N; - const uint depth_A = block_id_d / (D_B/D_A); + const uint fold = (uint)gqa_fold; + const uint depth_A = fold > 1 ? block_id_d : block_id_d / (D_B/D_A); const uint depth_B = block_id_d; int line_stride_matrix_A_in_bytes = K * D_A * 2; @@ -158,11 +160,18 @@ __kernel void mul_mm_f16_f32_kq_p8( __local float matrix_B_local[1024]; - // Clamp Q loads in the last tile; columns past N are not stored. - const uint c0 = min(row + b_globalOffsetInWords_xy.y, (uint)N - 1); - const uint c1 = min(row + b_globalOffsetInWords_xy.y + 16, (uint)N - 1); - const uint b_globalOffsetInWords00 = c0*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; - const uint b_globalOffsetInWords16 = c1*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + // Folded columns enumerate (query, head within the KV group). + const uint c0 = min(row + b_globalOffsetInWords_xy.y, (uint)N * fold - 1); + const uint c1 = min(row + b_globalOffsetInWords_xy.y + 16, (uint)N * fold - 1); + uint b_globalOffsetInWords00; + uint b_globalOffsetInWords16; + if (fold > 1) { + b_globalOffsetInWords00 = (c0/fold)*strideBinElements + (depth_B*fold + c0%fold)*K + b_globalOffsetInWords_xy.x; + b_globalOffsetInWords16 = (c1/fold)*strideBinElements + (depth_B*fold + c1%fold)*K + b_globalOffsetInWords_xy.x; + } else { + b_globalOffsetInWords00 = c0*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + b_globalOffsetInWords16 = c1*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + } for (uint step=0; step < K; step+=TILESIZE_K) { regA = mm_load_a(matrix_A, subMatrixAStartInElements, line_stride_matrix_A_in_bytes); @@ -199,9 +208,10 @@ __kernel void mul_mm_f16_f32_kq_p8( if (lane < 32) { const int j = lane >> 1; const int b = lane & 1; - const uint n = row + half_*16 + j; - const uint h = depth_B; - if (n < (uint)N) { + const uint c = row + half_*16 + j; + const uint n = c / fold; + const uint h = depth_B*fold + c % fold; + if (c < (uint)N * fold) { float slope = 1.0f; if (max_bias > 0.0f) { const float base = (int)h < n_head_log2 ? m0 : m1; From 2d8d003937b4ad42c1ada09dcdb0236eb3290a8f Mon Sep 17 00:00:00 2001 From: Leon <118652405+LeON-Nie-code@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:36:58 +0800 Subject: [PATCH 12/88] webgpu : add COL2IM_1D support (#31708) --- docs/ops.md | 2 +- docs/ops/WebGPU.csv | 71 ++++++++++--------- .../ggml-webgpu/ggml-webgpu-shader-lib.hpp | 18 +++++ ggml/src/ggml-webgpu/ggml-webgpu.cpp | 32 +++++++++ .../ggml-webgpu/wgsl-shaders/col2im_1d.wgsl | 45 ++++++++++++ tests/test-backend-ops.cpp | 20 ++++-- 6 files changed, 150 insertions(+), 38 deletions(-) create mode 100644 ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl diff --git a/docs/ops.md b/docs/ops.md index bdf64ca0af60..88e92c701d10 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -24,7 +24,7 @@ Legend: | ARGSORT | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | CEIL | ❌ | ❌ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | CLAMP | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | -| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONCAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONT | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONV_1D_DW | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 8b5e0c80ed43..2ad8ded659ec 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -5426,39 +5426,44 @@ "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,2,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,1,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=3,T_in=17,s0=2,p0=1,view=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=255,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=256,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=257,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=16777217,s0=1,p0=0,view=0","support","1","yes","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[3,2,3,1],ne_kernel=[2,2,1,3],stride=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[10,10,9,1],ne_kernel=[3,3,1,9],stride=2","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[129,63,35,1],ne_kernel=[3,3,48,35],stride=1","support","0","no","WebGPU" diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index 52b1bcc88ca3..cc7f660ef8e4 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -1269,6 +1269,7 @@ class ggml_webgpu_shader_lib { std::unordered_map argsort_pipelines; // key is order std::unordered_map argsort_merge_pipelines; // key is order std::unordered_map cumsum_pipelines; // key is fixed, no variants yet + std::unordered_map col2im_1d_pipelines; // key is fixed, no variants yet std::unordered_map arange_pipelines; // key is fixed, no variants yet std::unordered_map count_equal_pipelines; // key is src_overlap std::unordered_map timestep_embedding_pipelines; // key is fixed, no variants yet @@ -2096,6 +2097,23 @@ class ggml_webgpu_shader_lib { return pool2d_pipelines[key]; } + webgpu_pipeline get_col2im_1d_pipeline(const ggml_webgpu_shader_lib_context & context) { + auto it = col2im_1d_pipelines.find(1); + if (it != col2im_1d_pipelines.end()) { + return it->second; + } + + const uint32_t wg_size = std::min(256u, context.max_wg_size); + std::vector defines = { "WG_SIZE=" + std::to_string(wg_size) }; + auto processed = preprocessor.preprocess(wgsl_col2im_1d, defines); + auto decisions = std::make_shared(); + decisions->wg_size = wg_size; + webgpu_pipeline pipeline = ggml_webgpu_create_pipeline(device, processed, "col2im_1d"); + pipeline.context = decisions; + col2im_1d_pipelines[1] = pipeline; + return pipeline; + } + webgpu_pipeline get_pad_pipeline(const ggml_webgpu_shader_lib_context & context) { ggml_webgpu_pad_pipeline_key key = {}; key.reflect = context.dst->op == GGML_OP_PAD_REFLECT_1D; diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 6aa0cc92a32b..75527b111f6a 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -908,6 +908,32 @@ static webgpu_encoded_op ggml_webgpu_arange(webgpu_context & ctx, ggml_tensor * return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +static webgpu_encoded_op ggml_webgpu_col2im_1d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { + ggml_webgpu_shader_lib_context shader_lib_ctx = {}; + shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + webgpu_pipeline pipeline = ctx->shader_lib->get_col2im_1d_pipeline(shader_lib_ctx); + auto * decisions = static_cast(pipeline.context.get()); + + std::vector params = { + (uint32_t) ggml_nelements(dst), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / sizeof(float)), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / sizeof(float)), + (uint32_t) src->ne[0], + (uint32_t) src->ne[1], + (uint32_t) dst->ne[0], + (uint32_t) (src->ne[0] / dst->ne[1]), + (uint32_t) ggml_get_op_params_i32(dst, 0), + (uint32_t) ggml_get_op_params_i32(dst, 2), + }; + std::vector entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), + ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst) }; + uint32_t wg_x; + uint32_t wg_y; + const uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size); + compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y); + return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); +} + static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { ggml_webgpu_shader_lib_context shader_lib_ctx = {}; shader_lib_ctx.src0 = src; @@ -3712,6 +3738,8 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, return ggml_webgpu_arange(ctx, node); case GGML_OP_POOL_2D: return ggml_webgpu_pool2d(ctx, src0, node); + case GGML_OP_COL2IM_1D: + return ggml_webgpu_col2im_1d(ctx, src0, node); case GGML_OP_PAD_REFLECT_1D: case GGML_OP_PAD: return ggml_webgpu_pad(ctx, src0, node); @@ -5292,6 +5320,10 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const supports_op = src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1); break; + case GGML_OP_COL2IM_1D: + supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous(src0) && + ggml_is_contiguous(op); + break; case GGML_OP_SUM_ROWS: case GGML_OP_MEAN: supports_op = op->type == GGML_TYPE_F32 && src0->type == op->type && ggml_is_contiguous_rows(src0); diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl new file mode 100644 index 000000000000..f89528f2476d --- /dev/null +++ b/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl @@ -0,0 +1,45 @@ +@group(0) @binding(0) +var src: array; + +@group(0) @binding(1) +var dst: array; + +struct Params { + ne: u32, + offset_src: u32, + offset_dst: u32, + src_ne0: u32, + t_in: u32, + t_out: u32, + kernel: u32, + stride: u32, + padding: u32, +}; + +@group(0) @binding(2) +var params: Params; + +@compute @workgroup_size(WG_SIZE) +fn main(@builtin(num_workgroups) num_wg: vec3, + @builtin(global_invocation_id) gid: vec3) { + let idx = gid.x + num_wg.x * WG_SIZE * gid.y; + if (idx >= params.ne) { + return; + } + + let channel = idx / params.t_out; + let t_abs = idx % params.t_out + params.padding; + var first: u32 = 0; + if (t_abs >= params.kernel) { + first = (t_abs - params.kernel) / params.stride + 1; + } + let last = min(t_abs / params.stride, params.t_in - 1); + + // Gather overlapping columns in the same order as the CPU reference. + var sum: f32 = 0.0; + for (var t = first; t <= last; t++) { + let k = t_abs - t * params.stride; + sum += src[params.offset_src + t * params.src_ne0 + channel * params.kernel + k]; + } + dst[params.offset_dst + idx] = sum; +} diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 6d99453d89c4..a870016b0339 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -6940,9 +6940,10 @@ struct test_col2im_1d : public test_case { const int64_t T_in; // input length (number of columns) const int s0; // stride const int p0; // padding cropped from both sides + const bool view; std::string vars() override { - return VARS_TO_STR6(type, K, OC, T_in, s0, p0); + return VARS_TO_STR7(type, K, OC, T_in, s0, p0, view); } double max_nmse_err() override { @@ -6951,11 +6952,17 @@ struct test_col2im_1d : public test_case { test_col2im_1d(ggml_type type = GGML_TYPE_F32, int64_t K = 4, int64_t OC = 3, int64_t T_in = 7, - int s0 = 2, int p0 = 0) - : type(type), K(K), OC(OC), T_in(T_in), s0(s0), p0(p0) {} + int s0 = 2, int p0 = 0, bool view = false) + : type(type), K(K), OC(OC), T_in(T_in), s0(s0), p0(p0), view(view) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * cols = ggml_new_tensor_2d(ctx, type, K*OC, T_in); + ggml_tensor * cols; + if (view) { + ggml_tensor * base = ggml_new_tensor_1d(ctx, type, K * OC * T_in + 1); + cols = ggml_view_2d(ctx, base, K * OC, T_in, K * OC * ggml_type_size(type), ggml_type_size(type)); + } else { + cols = ggml_new_tensor_2d(ctx, type, K * OC, T_in); + } ggml_set_name(cols, "cols"); ggml_tensor * out = ggml_col2im_1d(ctx, cols, s0, (int) OC, p0); @@ -11341,6 +11348,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_col2im_1d(type, 8, 2, 3, 2, 5)); // cropping eats most of the signal, T_out = 2 } + test_cases.emplace_back(new test_col2im_1d(GGML_TYPE_F32, 5, 3, 17, 2, 1, true)); + for (int64_t n : {255, 256, 257, 16777217}) { + test_cases.emplace_back(new test_col2im_1d(GGML_TYPE_F32, 1, 1, n, 1, 0)); + } + for (ggml_type kernel_type : {GGML_TYPE_F32, GGML_TYPE_F16}) { test_cases.emplace_back(new test_conv_transpose_2d({3, 2, 3, 1}, {2, 2, 1, 3}, 1, kernel_type)); test_cases.emplace_back(new test_conv_transpose_2d({10, 10, 9, 1}, {3, 3, 1, 9}, 2, kernel_type)); From 16f80bd0c0fa6b27e7d0ec7fcb5a0e0dc5f3fd47 Mon Sep 17 00:00:00 2001 From: Ruben Ortlam Date: Fri, 20 Nov 2026 08:38:14 +0100 Subject: [PATCH 13/88] vulkan: chunked GATED_DELTA_NET implementation (#30207) * vulkan: add cm2 chunked GATED_DELTA_NET shader * fix shmem bank conflict bottleneck * optimize further * add coopmat maintenance1 variant * optimize for RDNA4 * add gmem version RDNA4 * optimize for Ampere * fix nvidia shmem overuse * fix cm2 validation errors * improve cm2 perf * improve cm1 perf * clean up * enable by default * show cm maintenance1 marker in device info * properly check for cm_m1 features * add tests * add v32 mode, improve chunked condition * allow other subgroup sizes * vulkan: specialize the GDN CM2 workgroup size Assisted-by: Codex * vulkan: coopmat2 GDN implementation * work around Nvidia shader compiler crash * remove shared shader cm2 code --------- Co-authored-by: Jeff Bolz --- ggml/src/ggml-vulkan/CMakeLists.txt | 6 + .../ggml-vulkan/ggml-vulkan-push-constants.h | 1 + ggml/src/ggml-vulkan/ggml-vulkan-types.h | 31 ++ ggml/src/ggml-vulkan/ggml-vulkan.cpp | 212 ++++++++- .../ggml-vulkan/vulkan-shaders/CMakeLists.txt | 4 + .../feature-tests/coopmat_maintenance1.comp | 8 + .../vulkan-shaders/gated_delta_net.comp | 22 +- .../vulkan-shaders/gated_delta_net_cm.comp | 437 ++++++++++++++++++ .../vulkan-shaders/gated_delta_net_cm2.comp | 320 +++++++++++++ .../vulkan-shaders/vulkan-shaders-gen.cpp | 19 +- tests/test-backend-ops.cpp | 96 +++- 11 files changed, 1134 insertions(+), 22 deletions(-) create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp diff --git a/ggml/src/ggml-vulkan/CMakeLists.txt b/ggml/src/ggml-vulkan/CMakeLists.txt index 791753a8cf9a..d8fa6ef409bb 100644 --- a/ggml/src/ggml-vulkan/CMakeLists.txt +++ b/ggml/src/ggml-vulkan/CMakeLists.txt @@ -101,6 +101,12 @@ if (Vulkan_FOUND) "GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT" ) + test_shader_extension_support( + "GL_EXT_cooperative_matrix_maintenance1" + "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/coopmat_maintenance1.comp" + "GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT" + ) + test_shader_extension_support( "GL_EXT_integer_dot_product" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/integer_dot.comp" diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 859cca181cd2..0a04c1d56892 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -787,6 +787,7 @@ struct vk_op_gated_delta_net_push_constants { uint32_t n_seqs; uint32_t s_off; uint32_t sq1, sq2, sq3; + uint32_t sk1, sk2, sk3; uint32_t sv1, sv2, sv3; uint32_t sb1, sb2, sb3; uint32_t neq1, rq3; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index b4fec2da44a9..211948ee793b 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -36,6 +36,21 @@ typedef struct VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV { } VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV; #endif +#ifndef VK_EXT_cooperative_matrix_maintenance1 +#define VK_EXT_cooperative_matrix_maintenance1 1 +#define VK_EXT_COOPERATIVE_MATRIX_MAINTENANCE_1_EXTENSION_NAME "VK_EXT_cooperative_matrix_maintenance1" +#define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT ((VkStructureType)1000659000) +typedef struct VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT { + VkStructureType sType; + void* pNext; + VkBool32 cooperativeMatrixProperties2; + VkBool32 cooperativeMatrixReductions; + VkBool32 cooperativeMatrixConversions; + VkBool32 cooperativeMatrixPerElementOperations; + VkBool32 cooperativeMatrixGetCoordinate; +} VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT; +#endif + #if __has_include() # include #elif __has_include() @@ -221,6 +236,12 @@ static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; } #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3) +#define GGML_VK_GDN_CM_V 64u +#define GGML_VK_GDN_CM2_V 32u +#define GGML_VK_GDN_CM_D 128u +#define GGML_VK_GDN_CM_PAD 8u +#define GGML_VK_GDN_CM_LDP (GGML_VK_GDN_CM_D + GGML_VK_GDN_CM_PAD) + struct vk_pipeline_struct; typedef std::shared_ptr vk_pipeline; @@ -767,6 +788,12 @@ struct vk_device_struct { bool coopmat_acc_f32_support {}; bool coopmat_acc_f16_support {}; bool coopmat_bf16_support {}; + bool coopmat_bf16_acc_support {}; + bool coopmat_maintenance1 {}; + bool coopmat_m1_reductions {}; + bool coopmat_m1_conversions {}; + bool coopmat_m1_per_element_ops {}; + bool coopmat_m1_get_coordinate {}; bool coopmat_support_16x16x16_f16acc {}; bool coopmat_support_16x16x16_f32acc {}; bool coopmat1_fa_support {}; @@ -781,6 +808,7 @@ struct vk_device_struct { bool coopmat2; bool coopmat2_bf16_support {}; + bool coopmat2_gdn_support {}; bool coopmat2_decode_vector; bool dot2_f16 {}; @@ -987,6 +1015,9 @@ struct vk_device_struct { vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT]; // [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 vk_pipeline pipeline_gated_delta_net[4][2]; + vk_pipeline pipeline_gated_delta_net_cm; + vk_pipeline pipeline_gated_delta_net_cm_v32; + vk_pipeline pipeline_gated_delta_net_cm_v128; vk_pipeline pipeline_ssm_scan_f32_d128; vk_pipeline pipeline_ssm_scan_f32_d256; vk_pipeline pipeline_ssm_conv_f32; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index cd8ef9ba3362..a9d60d6af57a 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1667,6 +1667,22 @@ static uint32_t ggml_vk_mul_mat_vec_max_cols(const vk_device & device) { return device->coopmat2 && !device->disable_narrow_mul_mat ? 4u : mul_mat_vec_max_cols; } +static uint32_t ggml_vk_gated_delta_net_shmem_size(uint32_t v, bool coopmat2) { + const uint32_t C = 16; + const uint32_t LDP = GGML_VK_GDN_CM_LDP; + const uint32_t bf16_size = sizeof(ggml_bf16_t); + const bool gmem_mirror = !coopmat2 && v == 128; + + const uint32_t qk = 4 * C * LDP * bf16_size; + const uint32_t state = gmem_mirror ? 0 : 2 * v * LDP * bf16_size; + const uint32_t p_inv = 4 * C * C * bf16_size; + const uint32_t delta_solved = coopmat2 ? 2 * C * (v + GGML_VK_GDN_CM_PAD) * bf16_size : 4 * C * v * bf16_size; + const uint32_t lower = (coopmat2 ? C * (C - 1) / 2 : C * C) * sizeof(float); + const uint32_t scan = 4 * C * sizeof(float); + + return qk + state + p_inv + delta_solved + lower + scan; +} + static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { uint32_t lut_size = 0; @@ -4124,13 +4140,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { device->subgroup_min_size <= 16u && device->subgroup_max_size >= 16u) { gdn_subgroup_size = 16u; } + const bool gdn_packed_rows = S_V == 128u && device->vendor_id == VK_VENDOR_ID_NVIDIA && + gdn_subgroup_size == 32u && device->subgroup_arithmetic && device->subgroup_clustered; uint32_t lanes_per_column; if (device->vendor_id == VK_VENDOR_ID_INTEL) { // Intel Xe: full-width reduction (min rows/lane) ~10x over the COLS_PER_WG=8 rule. lanes_per_column = std::min(gdn_subgroup_size, S_V); } else if (S_V >= 128u && device->subgroup_clustered) { - // COLS_PER_WG=8: measured optimum (Ampere sg32->4, Vega20 sg64->8). - lanes_per_column = std::max(1u, gdn_subgroup_size / 8u); + lanes_per_column = gdn_packed_rows ? 8u : std::max(1u, gdn_subgroup_size / 8u); } else { // Use largest power-of-two that divides both S_V and subgroup_size so that // (1) S_V % lanes_per_column == 0 and (2) S_V % (subgroup_size / lanes_per_column) == 0. @@ -4177,9 +4194,60 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { for (uint32_t kda = 0; kda < 2; kda++) { ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda], gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants), - wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column}, 1, true, use_subgroup_ops, gdn_subgroup_size); + wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size); + } + } + + // Chunked GDN prefill uses workgroup matrices on CM2 and subgroup matrices on CM1. + const bool gdn_chunked = getenv("GGML_VK_DISABLE_GDN_CHUNKED") == nullptr; + const uint32_t gdn_shmem = device->properties.limits.maxComputeSharedMemorySize; +#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) + if (gdn_chunked && device->coopmat2 && device->coopmat2_gdn_support) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm, + "gated_delta_net_f32_cm2", gated_delta_net_f32_cm2_len, gated_delta_net_f32_cm2_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, {}, 1, true, true, 32); + } +#endif +#if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) + // shader needs >= 16 lanes and 16 subgroups per WG; prefer wave64 + auto gdn_sg_ok = [&](uint32_t sg) { + const bool reachable = device->subgroup_size_control ? device->subgroup_min_size <= sg && sg <= device->subgroup_max_size + : device->subgroup_size == sg; + return reachable && 16u * sg <= device->properties.limits.maxComputeWorkGroupInvocations && + 16u * sg <= device->properties.limits.maxComputeWorkGroupSize[0]; + }; + const uint32_t gdn_sg = gdn_sg_ok(64) ? 64u : device->subgroup_size; + if (gdn_chunked && !device->coopmat2 && device->coopmat_support && device->coopmat_bf16_support && device->coopmat_m1_per_element_ops && + gdn_sg >= 16 && gdn_sg_ok(gdn_sg)) { + const bool bf16acc = device->coopmat_bf16_acc_support; + const std::vector gdn_spec = { 16u * gdn_sg }; + // V=64: state mirror in shared, 7 bindings + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(GGML_VK_GDN_CM_V, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc" : "gated_delta_net_f32_cm1", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_len : gated_delta_net_f32_cm1_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_data : (const void *)gated_delta_net_f32_cm1_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); + } + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(32u, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm_v32, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc_v32" : "gated_delta_net_f32_cm1_v32", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_v32_len : gated_delta_net_f32_cm1_v32_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_v32_data : (const void *)gated_delta_net_f32_cm1_v32_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); + } + // V=128: state mirror in a gmem scratch buffer, 8 bindings + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(128u, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm_v128, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc_v128" : "gated_delta_net_f32_cm1_v128", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_v128_len : gated_delta_net_f32_cm1_v128_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_v128_data : (const void *)gated_delta_net_f32_cm1_v128_data, + "main", 8, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); } } +#endif + GGML_UNUSED(gdn_chunked); + GGML_UNUSED(gdn_shmem); } if (device->subgroup_arithmetic && device->subgroup_require_full_support) { @@ -4554,6 +4622,11 @@ vk_device ggml_vk_get_device(size_t idx) { } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2")) { coopmat2_support = true; +#endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + } else if (strcmp("VK_EXT_cooperative_matrix_maintenance1", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_COOPMAT_MAINTENANCE1")) { + device->coopmat_maintenance1 = true; #endif } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { @@ -4880,6 +4953,15 @@ vk_device ggml_vk_get_device(size_t idx) { } #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT coopmat_m1_features {}; + coopmat_m1_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT; + if (device->coopmat_support && device->coopmat_maintenance1) { + last_struct->pNext = (VkBaseOutStructure *)&coopmat_m1_features; + last_struct = (VkBaseOutStructure *)&coopmat_m1_features; + } +#endif + VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV coopmat2_decode_vector_features {}; coopmat2_decode_vector_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_DECODE_VECTOR_FEATURES_NV; if (coopmat2_decode_vector_support) { @@ -5064,6 +5146,17 @@ vk_device ggml_vk_get_device(size_t idx) { device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support; #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + device->coopmat_maintenance1 = device->coopmat_support && device->coopmat_maintenance1; + if (device->coopmat_maintenance1) { + device->coopmat_m1_reductions = coopmat_m1_features.cooperativeMatrixReductions; + device->coopmat_m1_conversions = coopmat_m1_features.cooperativeMatrixConversions; + device->coopmat_m1_per_element_ops = coopmat_m1_features.cooperativeMatrixPerElementOperations; + device->coopmat_m1_get_coordinate = coopmat_m1_features.cooperativeMatrixGetCoordinate; + device_extensions.push_back(VK_EXT_COOPERATIVE_MATRIX_MAINTENANCE_1_EXTENSION_NAME); + } +#endif + if (coopmat2_support) { #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) if (coopmat2_features.cooperativeMatrixWorkgroupScope && @@ -5147,6 +5240,13 @@ vk_device ggml_vk_get_device(size_t idx) { prop.KGranularity <= 16) { found_bf16_128 = true; } + // GDN uses M=32, with N/K dimensions that are multiples of 16. + if (prop.workgroupInvocations == 128 && + prop.MGranularity != 0 && 32 % prop.MGranularity == 0 && + prop.NGranularity != 0 && 16 % prop.NGranularity == 0 && + prop.KGranularity != 0 && 16 % prop.KGranularity == 0) { + device->coopmat2_gdn_support = true; + } if (prop.workgroupInvocations == 256 && prop.MGranularity <= 32 && prop.NGranularity <= 32 && @@ -5157,6 +5257,12 @@ vk_device ggml_vk_get_device(size_t idx) { #endif } } + device->coopmat2_gdn_support = device->coopmat2_gdn_support && + coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= 128 && + device->properties.limits.maxComputeWorkGroupInvocations >= 128 && + device->properties.limits.maxComputeWorkGroupSize[0] >= 128 && + uint64_t(ggml_vk_gated_delta_net_shmem_size(GGML_VK_GDN_CM2_V, true)) + coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory <= + device->properties.limits.maxComputeSharedMemorySize; if (found_fp16_128 && found_fp16_256 && found_fp32_128 && found_fp32_256 && coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) { @@ -5274,6 +5380,18 @@ vk_device ggml_vk_get_device(size_t idx) { device->coopmat_bf16_support = true; } } + // bf16 accumulator (bf16/bf16/bf16/bf16) at the shader's fixed 16x16x16 + // shape lets the GDN coopmat1 path keep the hi/lo split as accumulators. + if (bfloat16_support && + prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.CType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.ResultType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup && + prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16 + ) { + device->coopmat_bf16_acc_support = true; + } #endif } @@ -5489,6 +5607,7 @@ static void ggml_vk_print_gpu_info(size_t idx) { bool coopmat_support = false; bool coopmat2_support = false; bool coopmat2_decode_vector_support = false; + bool coopmat_maintenance1_support = false; bool integer_dot_product = false; bool bfloat16_support = false; bool dot2_f16_support = false; @@ -5509,6 +5628,11 @@ static void ggml_vk_print_gpu_info(size_t idx) { } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2")) { coopmat2_support = true; +#endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + } else if (strcmp("VK_EXT_cooperative_matrix_maintenance1", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_COOPMAT_MAINTENANCE1")) { + coopmat_maintenance1_support = true; #endif } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { @@ -5592,6 +5716,15 @@ static void ggml_vk_print_gpu_info(size_t idx) { } #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT coopmat_m1_features {}; + coopmat_m1_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT; + if (coopmat_support && coopmat_maintenance1_support) { + last_struct->pNext = (VkBaseOutStructure *)&coopmat_m1_features; + last_struct = (VkBaseOutStructure *)&coopmat_m1_features; + } +#endif + VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {}; shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR; if (integer_dot_product) { @@ -5685,13 +5818,17 @@ static void ggml_vk_print_gpu_info(size_t idx) { coopmat2_support = false; #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + coopmat_maintenance1_support = coopmat_maintenance1_support && coopmat_m1_features.cooperativeMatrixPerElementOperations; +#endif + coopmat2_decode_vector_support = coopmat2_decode_vector_support && coopmat2_decode_vector_features.cooperativeMatrixDecodeVector; #if !defined(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) coopmat2_decode_vector_support = false; #endif std::string matrix_cores = coopmat2_support ? (coopmat2_decode_vector_support ? "NV_coopmat2v" : "NV_coopmat2") - : coopmat_support ? "KHR_coopmat" + : coopmat_support ? (coopmat_maintenance1_support ? "KHR_coopmat_m1" : "KHR_coopmat") : "none"; bool dot2_f16 = dot2_f16_support && dot2_features.shaderMixedFloatDotProductFloat16AccFloat32; @@ -11172,6 +11309,7 @@ void ggml_vk_lightning_indexer(ggml_backend_vk_context * ctx, vk_context& subctx void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { const ggml_tensor * src_q = dst->src[0]; + const ggml_tensor * src_k = dst->src[1]; const ggml_tensor * src_v = dst->src[2]; const ggml_tensor * src_beta = dst->src[4]; @@ -11187,7 +11325,39 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const uint32_t s_off = S_v * H * n_tokens * n_seqs; - vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op); + const ggml_tensor * src_g = dst->src[3]; + // RDNA3: the scan is faster below ~4k tokens + const uint32_t cm_min_tokens = ctx->device->architecture == AMD_RDNA3 ? 4096u : 64u; + const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr || + ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr || + ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) && + src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens; + + const bool use_cm2 = use_cm && ctx->device->coopmat2; + const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr; + bool use_v32 = use_cm && !use_cm2 && !have_v64 && ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr; + bool use_v128 = use_cm && !use_cm2 && !have_v64 && !use_v32; + const uint32_t nsm = ctx->device->shader_core_count; + if (use_cm && !use_cm2 && have_v64 && nsm != 0) { + const uint32_t wg64 = 2u * H * n_seqs; + // V=32 only pays off while V=64 leaves at least half the cores idle + use_v32 = ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr && 2u * wg64 <= nsm; + if (!use_v32 && ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) { + const uint32_t wg128 = H * n_seqs; + const uint32_t waves64 = (wg64 + nsm - 1) / nsm; + const uint32_t waves128 = (wg128 + nsm - 1) / nsm; + // prefer v128 when occupancy (wgs / (waves * nsm)) is at least as good + use_v128 = (uint64_t)wg128 * waves64 >= (uint64_t)wg64 * waves128; + } + } + + const uint32_t cm_V = use_cm2 ? GGML_VK_GDN_CM2_V : (use_v128 ? 128u : (use_v32 ? 32u : GGML_VK_GDN_CM_V)); + + vk_pipeline pipeline = use_v128 + ? ctx->device->pipeline_gated_delta_net_cm_v128 + : use_v32 ? ctx->device->pipeline_gated_delta_net_cm_v32 + : (use_cm ? ctx->device->pipeline_gated_delta_net_cm + : ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op)); GGML_ASSERT(pipeline != nullptr); ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); @@ -11198,9 +11368,27 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); } + vk_subbuffer mirror_buf{}; + if (use_v128) { + const uint32_t LDP = GGML_VK_GDN_CM_LDP; + const uint32_t blocks = (S_v / cm_V) * n_seqs * H; + const size_t scratch_size = (size_t)blocks * LDP * cm_V * 2u * sizeof(uint16_t); + if (ctx->prealloc_size_x < scratch_size) { + ctx->prealloc_size_x = scratch_size; + ggml_vk_preallocate_buffers(ctx, subctx); + } + if (ctx->prealloc_x_need_sync) { + ggml_vk_sync_buffers(ctx, subctx); + } + mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size }; + } + const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float)); const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float)); const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float)); + const uint32_t sk1 = (uint32_t)(src_k->nb[1] / sizeof(float)); + const uint32_t sk2 = (uint32_t)(src_k->nb[2] / sizeof(float)); + const uint32_t sk3 = (uint32_t)(src_k->nb[3] / sizeof(float)); const uint32_t sv1 = (uint32_t)(src_v->nb[1] / sizeof(float)); const uint32_t sv2 = (uint32_t)(src_v->nb[2] / sizeof(float)); const uint32_t sv3 = (uint32_t)(src_v->nb[3] / sizeof(float)); @@ -11215,6 +11403,7 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_op_gated_delta_net_push_constants pc = { H, n_tokens, n_seqs, s_off, sq1, sq2, sq3, + sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neq1, rq3, @@ -11222,9 +11411,16 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, K }; - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, - pc, { H, n_seqs, S_v }); + if (use_v128) { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf}, + pc, std::array{ S_v / cm_V, n_seqs, H }); + ctx->prealloc_x_need_sync = true; + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, + pc, use_cm ? std::array{ S_v / cm_V, n_seqs, H } : std::array{ H, n_seqs, S_v }); + } } void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt b/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt index cbe7a68bf372..273a80233e61 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt +++ b/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt @@ -15,6 +15,10 @@ if (GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) message(STATUS "Enabling coopmat2 decode_vector glslc support") endif() +if (GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + add_compile_definitions(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + message(STATUS "Enabling coopmat maintenance1 glslc support") +endif() if (GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) message(STATUS "Enabling dot glslc support") diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp new file mode 100644 index 000000000000..049ca2867393 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp @@ -0,0 +1,8 @@ +#version 460 + +#extension GL_KHR_cooperative_matrix : require +#extension GL_EXT_cooperative_matrix_maintenance1 : require + +void main() +{ +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp index 0e384330b9b9..ad2ced78aa39 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp @@ -15,10 +15,19 @@ layout(constant_id = 0) const uint S_V = 128; layout(constant_id = 1) const uint KDA = 0; layout(constant_id = 2) const uint SUBGROUP_SIZE = 32; layout(constant_id = 3) const uint LANES_PER_COLUMN = 32; +layout(constant_id = 4) const bool PACKED_ROWS = false; const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN; const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN; +uint row_index(uint r, uint lane) { + // Keep four adjacent rows together in each lane. + if (PACKED_ROWS) { + return (r / 4u * LANES_PER_COLUMN + lane) * 4u + r % 4u; + } + return r * LANES_PER_COLUMN + lane; +} + layout(local_size_x_id = 2, local_size_y = 1, local_size_z = 1) in; layout(push_constant) uniform Parameters { @@ -27,6 +36,7 @@ layout(push_constant) uniform Parameters { uint n_seqs; uint s_off; uint sq1, sq2, sq3; + uint sk1, sk2, sk3; uint sv1, sv2, sv3; uint sb1, sb2, sb3; uint neq1, rq3; @@ -110,7 +120,7 @@ void main() { FLOAT_TYPE s_shard[ROWS_PER_LANE]; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + r * LANES_PER_COLUMN + lane]); + s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]); } // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. @@ -120,7 +130,7 @@ void main() { for (uint t = 0; t < n_tokens; t++) { const uint q_off = iq3 * sq3 + t * sq2 + iq1 * sq1; - const uint k_off = q_off; + const uint k_off = iq3 * sk3 + t * sk2 + iq1 * sk1; const uint v_off = seq_id * sv3 + t * sv2 + head_id * sv1; const uint gb_off = seq_id * sb3 + t * sb2 + head_id * sb1; const FLOAT_TYPE beta_val = FLOAT_TYPE(data_beta[gb_off]); @@ -128,7 +138,7 @@ void main() { FLOAT_TYPE k_reg[ROWS_PER_LANE]; FLOAT_TYPE q_reg[ROWS_PER_LANE]; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - const uint i = r * LANES_PER_COLUMN + lane; + const uint i = row_index(r, lane); k_reg[r] = FLOAT_TYPE(data_k[k_off + i]); q_reg[r] = FLOAT_TYPE(data_q[q_off + i]); } @@ -142,7 +152,7 @@ void main() { } else { const uint g_base = gb_off * S_V; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - const uint i = r * LANES_PER_COLUMN + lane; + const uint i = row_index(r, lane); g_exp[r] = exp(FLOAT_TYPE(data_g[g_base + i])); } } @@ -175,7 +185,7 @@ void main() { if (target_slot >= 0 && target_slot < int(K)) { const uint slot_base = s_off + uint(target_slot) * state_size_per_snap + state_out_base; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[slot_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[r]; + data_dst[slot_base + col * S_V + row_index(r, lane)] = s_shard[r]; } } } @@ -183,7 +193,7 @@ void main() { if (K == 1u) { [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[s_off + state_out_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[r]; + data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; } } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp new file mode 100644 index 000000000000..c5b4e4084faf --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp @@ -0,0 +1,437 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_EXT_bfloat16 : require +#extension GL_KHR_memory_scope_semantics : enable +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_KHR_shader_subgroup_shuffle : enable +#extension GL_KHR_cooperative_matrix : enable +#extension GL_EXT_cooperative_matrix_maintenance1 : enable + +// Chunked gated-delta-net prefill (non-KDA, S_v == D == 128, K == 1), port of CUDA PR 29353. +// State in register tiles, mirrored ([D x V]) for the projections. +// bf16 hi/lo 3x products for ~fp32 accuracy. +#define OPD bfloat16_t + +#define C 16 // chunk size (tokens per step) +#define D 128 // head dim / value dim +#define TM 16 // tile rows +#define TN 16 // tile cols (bf16 cm has only m16n16k16; n8 would pad) +#ifndef V +#define V 64 // value columns per workgroup block (V=128 = whole head) +#endif +#define NSUB 16 // subgroups per workgroup +layout(constant_id = 0) const uint WGS = NSUB * 32; // NSUB * subgroup size +#define KT 16 // K-tile width for deep (K=D) matmuls (bf16 cm: m16n16k16 only) +#define PAD 8 // shared padding to break COL-load bank conflicts (keep LDP*2 a multiple of 16B) +#define LDP (D + PAD) + +// GMEM_MIRROR: state mirror in a gmem scratch buffer (too big for shared) + +#define STATE_TILES ((D / TM) * (V / TN)) +#define PER_WARP (STATE_TILES / NSUB) +#define VT (V / TN) // value tiles +#define CT (C / TN) // C-column tiles (gram/pmat halves) +const uint NQK = C * D / WGS; + +#define TILE_R(ti) (((ti) / VT) * TM) +#define TILE_C(ti) (((ti) % VT) * TN) + +layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; + +layout(push_constant) uniform Parameters { + uint H; + uint n_tokens; + uint n_seqs; + uint s_off; + uint sq1, sq2, sq3; + uint sk1, sk2, sk3; + uint sv1, sv2, sv3; + uint sb1, sb2, sb3; + uint neq1, rq3; + float scale; + uint K; +} p; + +layout(binding = 0) readonly buffer QBuf { float data_q[]; }; +layout(binding = 1) readonly buffer KBuf { float data_k[]; }; +layout(binding = 2) readonly buffer VBuf { float data_v[]; }; +layout(binding = 3) readonly buffer GBuf { float data_g[]; }; +layout(binding = 4) readonly buffer BetaBuf { float data_beta[]; }; +layout(binding = 5) readonly buffer StateBuf { float data_state[]; }; +layout(binding = 6) buffer DstBuf { float data_dst[]; }; +#ifdef GMEM_MIRROR +layout(binding = 7) coherent buffer MirrorBuf { OPD data_mirror[]; }; +#endif + +shared OPD sh_qh[C * LDP], sh_ql[C * LDP]; // q*scale hi/lo (D padded) +shared OPD sh_kh[C * LDP], sh_kl[C * LDP]; // k hi/lo (D padded) +#ifndef GMEM_MIRROR +shared OPD sh_sh[LDP * V], sh_sl[LDP * V]; // state mirror [D x V] column-major (D padded) +#endif +shared OPD sh_dh[C * V], sh_dl[C * V]; // delta (pre-inv) / delta2 [C x V] row-major +shared OPD sh_soh[C * V], sh_sol[C * V]; // solved [C x V] row-major +shared OPD sh_ph[C * C], sh_pl[C * C]; // decayed P +shared OPD sh_ih[C * C], sh_il[C * C]; // (I + L)^-1 +shared float sh_lower[C * C]; // strictly-lower decayed L + +shared float sh_prefix[C], sh_beta[C], sh_ep[C], sh_carry[C]; + +#define SG gl_ScopeSubgroup +#define MUA gl_MatrixUseA +#define MUB gl_MatrixUseB +#define MACC gl_MatrixUseAccumulator +#define ROW gl_CooperativeMatrixLayoutRowMajor +#define COL gl_CooperativeMatrixLayoutColumnMajor + + +// 3x bf16 product accumulated into acc (hi/lo split for ~fp32 accuracy). +#define PRODUCT(acc, ah, al, bh, bl) \ + acc = coopMatMulAdd(al, bh, acc); \ + acc = coopMatMulAdd(ah, bl, acc); \ + acc = coopMatMulAdd(ah, bh, acc); + +void split(const float x, out OPD h, out OPD l) { + h = OPD(x); + l = OPD(x - float(h)); +} + +#ifdef BF16ACC +// split through a bf16 accumulator +#define SPLIT_STORE(m, arr_h, off_h, arr_l, off_l, ld, layout) { \ + const coopmat h_ = coopmat(m); \ + const coopmat l_ = coopmat(m - coopmat(h_)); \ + coopMatStore(h_, arr_h, off_h, ld, layout); \ + coopMatStore(l_, arr_l, off_l, ld, layout); \ +} + +#ifdef GMEM_MIRROR +#define STORE_MIRROR(m, off) SPLIT_STORE(m, data_mirror, mir_h + off, data_mirror, mir_l + off, LDP, COL) +#else +#define STORE_MIRROR(m, off) SPLIT_STORE(m, sh_sh, off, sh_sl, off, LDP, COL) +#endif +#define STORE_DELTA(m, off) SPLIT_STORE(m, sh_dh, off, sh_dl, off, V, ROW) +#define STORE_SOLVED(m, off) SPLIT_STORE(m, sh_soh, off, sh_sol, off, V, ROW) +#else +// split per element +#ifdef GMEM_MIRROR +float SplitColS(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + c * LDP + r; + split(elem, data_mirror[idx], data_mirror[idx + LDP * V]); + return elem; +} +#define STORE_MIRROR(m, off) coopMatPerElementEXT(m, m, SplitColS, mir_h + off) +#else +float SplitColS(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + c * LDP + r; + split(elem, sh_sh[idx], sh_sl[idx]); + return elem; +} +#define STORE_MIRROR(m, off) coopMatPerElementEXT(m, m, SplitColS, off) +#endif + +float SplitRowD(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + r * V + c; + split(elem, sh_dh[idx], sh_dl[idx]); + return elem; +} + +float SplitRowSO(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + r * V + c; + split(elem, sh_soh[idx], sh_sol[idx]); + return elem; +} + +#define STORE_DELTA(m, off) coopMatPerElementEXT(m, m, SplitRowD, off) +#define STORE_SOLVED(m, off) coopMatPerElementEXT(m, m, SplitRowSO, off) +#endif + +#ifdef GMEM_MIRROR +#define LOAD_S(h, l, off) \ + coopMatLoad(h, data_mirror, mir_h + off, LDP, COL); \ + coopMatLoad(l, data_mirror, mir_l + off, LDP, COL); +// mirror is workgroup-private +#define MIRROR_BARRIER() controlBarrier(gl_ScopeWorkgroup, gl_ScopeWorkgroup, \ + gl_StorageSemanticsBuffer | gl_StorageSemanticsShared, \ + gl_SemanticsAcquireRelease) +#else +#define LOAD_S(h, l, off) \ + coopMatLoad(h, sh_sh, off, LDP, COL); \ + coopMatLoad(l, sh_sl, off, LDP, COL); +#define MIRROR_BARRIER() barrier() +#endif + +float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t out_base, const in uint32_t valid) { + if (r < valid) { + data_dst[out_base + r * (D * p.H) + c] = elem; + } + return elem; +} + +float StoreState(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t base) { + data_dst[base + c * D + r] = elem; + return elem; +} + +float LoadV(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t v_base, const in uint32_t sv2, const in uint32_t valid) { + return r < valid ? data_v[v_base + r * sv2 + c] : 0.0; +} + +// sh_beta[r] == 0 for r >= valid +float ComputeDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, + const in float vv) { + return sh_beta[r] * (vv - sh_ep[r] * ks); +} + +float ApplyExpPrefix(const in uint32_t r, const in uint32_t c, const in float qs) { + return sh_ep[r] * qs; +} + +float StoreLower(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t c_o) { + const uint cc = c_o + c; + if (cc < r) { + sh_lower[r * C + cc] = elem * exp(sh_prefix[r] - sh_prefix[cc]) * sh_beta[r]; + } + return elem; +} + +float StorePmat(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t c_o) { + const uint cc = c_o + c; + float v = 0.0; + if (cc <= r) { + v = elem * exp(sh_prefix[r] - sh_prefix[cc]); + } + split(v, sh_ph[r * C + cc], sh_pl[r * C + cc]); + return elem; +} + +void prefetch(const uint t0, const uint iq1, const uint iq3, const uint seq_id, const uint head_id, + out float q[NQK], out float k[NQK], out float g, out float b) { + const uint n = t0 < p.n_tokens ? min(C, p.n_tokens - t0) : 0u; + [[unroll]] for (uint j = 0; j < NQK; j++) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint t = i / D; + q[j] = 0.0; + k[j] = 0.0; + if (t < n) { + const uint q_off = iq3 * p.sq3 + (t0 + t) * p.sq2 + iq1 * p.sq1 + i % D; + const uint k_off = iq3 * p.sk3 + (t0 + t) * p.sk2 + iq1 * p.sk1 + i % D; + q[j] = data_q[q_off] * p.scale; + k[j] = data_k[k_off]; + } + } + g = 0.0; + b = 0.0; + const uint t = gl_SubgroupInvocationID; + if (gl_SubgroupID == 0 && t < n) { + const uint gb = seq_id * p.sb3 + (t0 + t) * p.sb2 + head_id * p.sb1; + g = data_g[gb]; + b = data_beta[gb]; + } +} + +// sg0: gram K@K^T -> L, sg1: pmat Q@K^T -> P +void gram_pmat(const uint sg) { + const bool gram = sg < CT; + const uint c_o = (sg % CT) * TN; + coopmat x = coopmat(0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + if (gram) { + coopMatLoad(ah, sh_kh, kk, LDP, ROW); + coopMatLoad(al, sh_kl, kk, LDP, ROW); + } else { + coopMatLoad(ah, sh_qh, kk, LDP, ROW); + coopMatLoad(al, sh_ql, kk, LDP, ROW); + } + coopmat bh, bl; + coopMatLoad(bh, sh_kh, c_o * LDP + kk, LDP, COL); + coopMatLoad(bl, sh_kl, c_o * LDP + kk, LDP, COL); + PRODUCT(x, ah, al, bh, bl); + } + if (gram) { + coopMatPerElementEXT(x, x, StoreLower, c_o); + } else { + coopMatPerElementEXT(x, x, StorePmat, c_o); + } +} + +// (I + L)^-1, forward substitution: subgroup per row, lane per column +void invert(const uint sg) { + const uint col = gl_SubgroupInvocationID; + [[unroll]] for (uint row = sg; row < C; row += NSUB) { + float x = col < C ? (col == row ? 1.0 : (col < row ? -sh_lower[row * C + col] : 0.0)) : 0.0; + for (int pivot = int(row) - 1; pivot > 0; pivot--) { + const float xp = subgroupShuffle(x, uint(pivot)); + if (col < uint(pivot)) { + x -= xp * sh_lower[uint(pivot) * C + col]; + } + } + if (col < C) { + split(x, sh_ih[row * C + col], sh_il[row * C + col]); + } + } +} + +float carry_decay(const uint valid) { + const float plast = sh_prefix[valid - 1]; + if (gl_LocalInvocationID.x < C) { + sh_carry[gl_LocalInvocationID.x] = exp(plast - sh_prefix[gl_LocalInvocationID.x]); + } + return exp(plast); +} + +void main() { + const uint head_id = gl_WorkGroupID.z; + const uint seq_id = gl_WorkGroupID.y; + const uint sg = gl_SubgroupID; + const uint tid = gl_LocalInvocationID.x; + const uint v0 = gl_WorkGroupID.x * V; + + const uint iq1 = head_id % p.neq1; + const uint iq3 = seq_id / p.rq3; + + const uint state_base = (seq_id * p.H + head_id) * (D * D); + +#ifdef GMEM_MIRROR + const uint mir_stride = uint(LDP) * V; + const uint mir_block = (head_id * p.n_seqs + seq_id) * gl_NumWorkGroups.x + gl_WorkGroupID.x; + const uint mir_h = mir_block * mir_stride * 2u; + const uint mir_l = mir_h + mir_stride; +#endif + + coopmat state[PER_WARP]; + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopMatLoad(state[j], data_state, state_base + (v0 + TILE_C(ti)) * D + TILE_R(ti), D, COL); + } + + float qreg[NQK], kreg[NQK], greg, breg; + prefetch(0u, iq1, iq3, seq_id, head_id, qreg, kreg, greg, breg); + + for (uint t0 = 0; t0 < p.n_tokens; t0 += C) { + const uint valid = min(C, p.n_tokens - t0); + + barrier(); + if (sg == 0) { + const uint t = gl_SubgroupInvocationID; + const float acc = subgroupInclusiveAdd(greg); + if (t < C) { + sh_prefix[t] = acc; + sh_ep[t] = exp(acc); + sh_beta[t] = breg; + } + } + [[unroll]] for (uint j = 0; j < NQK; j++) { + const uint i = tid + j * WGS; + const uint pi = (i / D) * LDP + (i % D); + split(qreg[j], sh_qh[pi], sh_ql[pi]); + split(kreg[j], sh_kh[pi], sh_kl[pi]); + } + + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + STORE_MIRROR(state[j], TILE_C(ti) * LDP + TILE_R(ti)); + } + MIRROR_BARRIER(); + + prefetch(t0 + C, iq1, iq3, seq_id, head_id, qreg, kreg, greg, breg); + const float cdecay = carry_decay(valid); + + // qs -> base_r and ks -> delta on sg2..2+VT-1 + coopmat base_r = coopmat(0); + if (sg < 2 * CT) { + gram_pmat(sg); + } else if (sg - 2 * CT < VT) { + const uint c_o = (sg - 2 * CT) * TN; + const uint v_base = seq_id * p.sv3 + head_id * p.sv1 + v0 + c_o + t0 * p.sv2; + coopmat vmat = coopmat(0); + coopMatPerElementEXT(vmat, vmat, LoadV, v_base, p.sv2, valid); + coopmat qs = coopmat(0); + coopmat ks = coopmat(0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat qh, ql, kh, kl; + coopMatLoad(qh, sh_qh, kk, LDP, ROW); + coopMatLoad(ql, sh_ql, kk, LDP, ROW); + coopMatLoad(kh, sh_kh, kk, LDP, ROW); + coopMatLoad(kl, sh_kl, kk, LDP, ROW); + coopmat sbh, sbl; + LOAD_S(sbh, sbl, c_o * LDP + kk); + PRODUCT(qs, qh, ql, sbh, sbl); + PRODUCT(ks, kh, kl, sbh, sbl); + } + coopMatPerElementEXT(base_r, qs, ApplyExpPrefix); + coopmat delta; + coopMatPerElementEXT(delta, ks, ComputeDeltaV, vmat); + STORE_DELTA(delta, c_o); + } + barrier(); + + invert(sg); + barrier(); + + // solved = (I+L)^-1 @ delta (sg0..VT-1) + if (sg < VT) { + const uint c_o = sg * TN; + coopmat solved = coopmat(0); + coopmat ih, il; + coopMatLoad(ih, sh_ih, 0, C, ROW); + coopMatLoad(il, sh_il, 0, C, ROW); + coopmat dh, dl; + coopMatLoad(dh, sh_dh, c_o, V, ROW); + coopMatLoad(dl, sh_dl, c_o, V, ROW); + PRODUCT(solved, ih, il, dh, dl); + STORE_SOLVED(solved, c_o); + } + barrier(); + + // out = base + P@solved (sg2..2+VT-1) + if (sg >= 2 * CT && sg - 2 * CT < VT) { + const uint c_o = (sg - 2 * CT) * TN; + coopmat O = base_r; + coopmat ph, pl; + coopMatLoad(ph, sh_ph, 0, C, ROW); + coopMatLoad(pl, sh_pl, 0, C, ROW); + coopmat svh, svl; + coopMatLoad(svh, sh_soh, c_o, V, ROW); + coopMatLoad(svl, sh_sol, c_o, V, ROW); + PRODUCT(O, ph, pl, svh, svl); + const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0 + c_o + t0 * (D * p.H); + coopMatPerElementEXT(O, O, StoreOut, out_base, valid); + } + // delta2 = solved * carry -> sh_dh/dl (all threads) + for (uint i = tid; i < C * V; i += WGS) { + const float sv = float(sh_soh[i]) + float(sh_sol[i]); + split(sv * sh_carry[i / V], sh_dh[i], sh_dl[i]); + } + barrier(); + + // state = cdecay*state + K^T @ delta2 + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopmat kth, ktl; + coopMatLoad(kth, sh_kh, TILE_R(ti), LDP, COL); + coopMatLoad(ktl, sh_kl, TILE_R(ti), LDP, COL); + coopmat dh, dl; + coopMatLoad(dh, sh_dh, TILE_C(ti), V, ROW); + coopMatLoad(dl, sh_dl, TILE_C(ti), V, ROW); + state[j] = state[j] * cdecay; + PRODUCT(state[j], kth, ktl, dh, dl); + } + // no end-of-chunk barrier: covered by the chunk-top barrier + } + + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopMatPerElementEXT(state[j], state[j], StoreState, + p.s_off + state_base + (v0 + TILE_C(ti)) * D + TILE_R(ti)); + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp new file mode 100644 index 000000000000..270ef35db3a5 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp @@ -0,0 +1,320 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_EXT_bfloat16 : require +#extension GL_KHR_memory_scope_semantics : require +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require +#extension GL_KHR_cooperative_matrix : require +#extension GL_NV_cooperative_matrix2 : require + +// Chunked gated-delta-net prefill (non-KDA, S_v == D == 128, K == 1). +// BF16 hi/lo products use FP32 accumulators. +#define OPD bfloat16_t + +#define C 16 // chunk size (tokens per step) +#define D 128 // head dim / value dim +#define V 32 // value columns per workgroup block +#define WGS 128 +#define NSUB (WGS / 32) +#define KT 32 // K-tile width for deep (K=D) matmuls +#define PAD 8 +#define LDP (D + PAD) +#define LDV (V + PAD) +#define KQ_ROWS (2 * C) +#define NQK (C * D / WGS) + +layout(local_size_x = WGS, local_size_y = 1, local_size_z = 1) in; + +layout(push_constant) uniform Parameters { + uint H; + uint n_tokens; + uint n_seqs; + uint s_off; + uint sq1, sq2, sq3; + uint sk1, sk2, sk3; + uint sv1, sv2, sv3; + uint sb1, sb2, sb3; + uint neq1, rq3; + float scale; + uint K; +} p; + +layout(binding = 0) readonly buffer QBuf { float data_q[]; }; +layout(binding = 1) readonly buffer KBuf { float data_k[]; }; +layout(binding = 2) readonly buffer VBuf { float data_v[]; }; +layout(binding = 3) readonly buffer GBuf { float data_g[]; }; +layout(binding = 4) readonly buffer BetaBuf { float data_beta[]; }; +layout(binding = 5) readonly buffer StateBuf { float data_state[]; }; +layout(binding = 6) buffer DstBuf { float data_dst[]; }; + +// K and scaled Q occupy the two row blocks of one 32-row operand. +shared OPD sh_kqh[2 * C * LDP], sh_kql[2 * C * LDP]; +shared OPD sh_sh[V * LDP], sh_sl[V * LDP]; // state mirror [V x D] row-major (D padded) +shared OPD sh_ph[C * C], sh_pl[C * C]; +shared OPD sh_ih[C * C], sh_il[C * C]; +shared OPD sh_dh[C * LDV], sh_dl[C * LDV]; // delta / solved [C x V] row-major (V padded) +shared float sh_lower[C * (C - 1) / 2]; // packed strictly-lower Gram entries +shared float sh_prefix[C], sh_ep[C], sh_beta[C], sh_carry[C]; + +#define WG gl_ScopeWorkgroup +#define MUA gl_MatrixUseA +#define MUB gl_MatrixUseB +#define MACC gl_MatrixUseAccumulator +#define ROW gl_CooperativeMatrixLayoutRowMajor +#define COL gl_CooperativeMatrixLayoutColumnMajor + +#define PRODUCT(acc, ah, al, bh, bl) \ + acc = coopMatMulAdd(ah, bh, acc); \ + acc = coopMatMulAdd(al, bh, acc); \ + acc = coopMatMulAdd(ah, bl, acc); + +void split(const float x, out OPD h, out OPD l) { + h = OPD(x); + l = OPD(x - float(h)); +} + +float StoreGramPmat(const in uint32_t r, const in uint32_t c, const in float elem) { + if (r < C) { + if (c < r) { + sh_lower[r * (r - 1) / 2 + c] = elem * exp(sh_prefix[r] - sh_prefix[c]) * sh_beta[r]; + } + } else { + const uint row = r - C; + const float y = c <= row ? elem * exp(sh_prefix[row] - sh_prefix[c]) : 0.0; + split(y, sh_ph[row * C + c], sh_pl[row * C + c]); + } + return elem; +} + +float SplitRowS(const in uint32_t r, const in uint32_t c, const in float elem) { + const uint i = r * LDP + c; + split(elem, sh_sh[i], sh_sl[i]); + return elem; +} + +float ApplyExpPrefix(const in uint32_t r, const in uint32_t c, const in float qs) { + return sh_ep[c] * qs; +} + +float LoadV(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t v_base, const in uint32_t sv2, const in uint32_t valid) { + return c < valid ? data_v[v_base + c * sv2 + r] : 0.0; +} + +float StoreDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, const in float vv) { + const float x = sh_beta[c] * (vv - sh_ep[c] * ks); + const uint i = c * LDV + r; + split(x, sh_dh[i], sh_dl[i]); + return ks; +} + +float StoreSolved(const in uint32_t r, const in uint32_t c, const in float elem) { + const uint i = c * LDV + r; + split(elem, sh_dh[i], sh_dl[i]); + // The state mirror is no longer needed after KS/QS. + const uint j = r * LDP + c; + split(sh_carry[c] * elem, sh_sh[j], sh_sl[j]); + return elem; +} + +float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t out_base, const in uint32_t valid) { + if (c < valid) { + data_dst[out_base + c * (p.H * D) + r] = elem; + } + return elem; +} + +void prefetch(const uint t0, const uint q_base, const uint k_base, const uint gb_base, + out float q[NQK], out float k[NQK], out float g, out float b) { + const uint valid = t0 < p.n_tokens ? min(C, p.n_tokens - t0) : 0u; + const uint r = gl_SubgroupInvocationID; + g = 0.0; + b = 0.0; + if (gl_SubgroupID == 0 && r < valid) { + const uint off = gb_base + (t0 + r) * p.sb2; + g = data_g[off]; + b = data_beta[off]; + } + [[unroll]] for (uint j = 0; j < NQK; ++j) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint token = i / D; + q[j] = 0.0; + k[j] = 0.0; + if (token < valid) { + const uint q_off = q_base + (t0 + token) * p.sq2 + i % D; + const uint k_off = k_base + (t0 + token) * p.sk2 + i % D; + q[j] = data_q[q_off]; + k[j] = data_k[k_off]; + } + } +} + +void stage_inputs(const in float q[NQK], const in float k[NQK]) { + [[unroll]] for (uint j = 0; j < NQK; ++j) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint token = i / D; + const uint key = i % D; + const uint ki = token * LDP + key; + const uint qi = (C + token) * LDP + key; + split(k[j], sh_kqh[ki], sh_kql[ki]); + split(p.scale * q[j], sh_kqh[qi], sh_kql[qi]); + } +} + +// [K; Q] * K^T computes Gram and P in one 32-row matrix. +void gram_pmat() { + coopmat x = coopmat(0.0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + coopmat bh, bl; + coopMatLoad(ah, sh_kqh, kk, LDP, ROW); + coopMatLoad(al, sh_kql, kk, LDP, ROW); + coopMatLoad(bh, sh_kqh, kk, LDP, COL); + coopMatLoad(bl, sh_kql, kk, LDP, COL); + PRODUCT(x, ah, al, bh, bl); + } + coopMatPerElementNV(x, x, StoreGramPmat); +} + +void invert() { + const uint col = gl_SubgroupInvocationID % C; + // Each half-subgroup covers all columns of its assigned rows. + const uint section = gl_SubgroupInvocationID / C; + const uint row_base = (gl_SubgroupID * 2u + section) * (C / (2 * NSUB)); + // Keep the diagonal zero so pivots at or above the row do nothing. + float x[C / (2 * NSUB)]; + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const uint row = row_base + j; + x[j] = col < row ? -sh_lower[row * (row - 1) / 2 + col] : 0.0; + } + [[dont_unroll]] for (int pivot = C - 2; pivot > 0; --pivot) { + const float lower = col < uint(pivot) ? sh_lower[uint(pivot) * uint(pivot - 1) / 2 + col] : 0.0; + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const float xp = subgroupShuffle(x[j], uint(pivot) + section * C); + x[j] -= xp * lower; + } + } + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const uint row = row_base + j; + split(col == row ? 1.0 : x[j], sh_ih[row * C + col], sh_il[row * C + col]); + } +} + +void main() { + const uint head_id = gl_WorkGroupID.z; + const uint seq_id = gl_WorkGroupID.y; + const uint v0 = gl_WorkGroupID.x * V; + const uint iq1 = head_id % p.neq1; + const uint iq3 = seq_id / p.rq3; + const uint q_base = iq3 * p.sq3 + iq1 * p.sq1; + const uint k_base = iq3 * p.sk3 + iq1 * p.sk1; + const uint v_base = seq_id * p.sv3 + head_id * p.sv1 + v0; + const uint gb_base = seq_id * p.sb3 + head_id * p.sb1; + const uint state_base = (seq_id * p.H + head_id) * (D * D) + v0 * D; + const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0; + + // Transposing the state-side products gives them V=32 rows with C=16 columns. + coopmat state; + coopMatLoad(state, data_state, state_base, D, ROW); + + float qreg[NQK], kreg[NQK], greg, breg; + prefetch(0u, q_base, k_base, gb_base, qreg, kreg, greg, breg); + + [[dont_unroll]] for (uint t0 = 0; t0 < p.n_tokens; t0 += C) { + const uint valid = min(C, p.n_tokens - t0); + barrier(); + if (gl_SubgroupID == 0) { + const uint r = gl_SubgroupInvocationID; + // shuffle scan instead of subgroupInclusiveAdd: works around an NVIDIA r620 shader compiler crash + float sum = greg; + [[unroll]] for (uint d = 1; d < C; d <<= 1) { + const float t = subgroupShuffleUp(sum, d); + if (r >= d) { + sum += t; + } + } + const float last = subgroupShuffle(sum, valid - 1); + if (r < C) { + sh_prefix[r] = sum; + sh_ep[r] = exp(sum); + sh_beta[r] = breg; + sh_carry[r] = exp(last - sum); + } + } + stage_inputs(qreg, kreg); + coopmat vmat; + if (valid == C && (v_base % 4u) == 0 && (p.sv2 % 4u) == 0) { + coopMatLoad(vmat, data_v, v_base + t0 * p.sv2, p.sv2, COL); + } else { + vmat = coopmat(0.0); + coopMatPerElementNV(vmat, vmat, LoadV, v_base + t0 * p.sv2, p.sv2, valid); + } + barrier(); + // Current inputs are in shared memory; keep the next chunk in registers. + prefetch(t0 + C, q_base, k_base, gb_base, qreg, kreg, greg, breg); + + gram_pmat(); + barrier(); + invert(); + coopMatPerElementNV(state, state, SplitRowS); + barrier(); + + coopmat ks = coopmat(0.0), base_r = coopmat(0.0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + coopmat kh, kl, qh, ql; + coopMatLoad(ah, sh_sh, kk, LDP, ROW); + coopMatLoad(al, sh_sl, kk, LDP, ROW); + coopMatLoad(kh, sh_kqh, kk, LDP, COL); + coopMatLoad(kl, sh_kql, kk, LDP, COL); + coopMatLoad(qh, sh_kqh, C * LDP + kk, LDP, COL); + coopMatLoad(ql, sh_kql, C * LDP + kk, LDP, COL); + PRODUCT(ks, ah, al, kh, kl); + PRODUCT(base_r, ah, al, qh, ql); + } + coopMatPerElementNV(base_r, base_r, ApplyExpPrefix); + coopMatPerElementNV(ks, ks, StoreDeltaV, vmat); + barrier(); + + coopmat solved = coopmat(0.0); + { + coopmat rh, rl; + coopmat ih, il; + coopMatLoad(rh, sh_dh, 0, LDV, COL); + coopMatLoad(rl, sh_dl, 0, LDV, COL); + coopMatLoad(ih, sh_ih, 0, C, COL); + coopMatLoad(il, sh_il, 0, C, COL); + PRODUCT(solved, rh, rl, ih, il); + } + barrier(); + coopMatPerElementNV(solved, solved, StoreSolved); + barrier(); + + { + coopmat xh, xl; + coopmat ph, pl; + coopMatLoad(xh, sh_dh, 0, LDV, COL); + coopMatLoad(xl, sh_dl, 0, LDV, COL); + coopMatLoad(ph, sh_ph, 0, C, COL); + coopMatLoad(pl, sh_pl, 0, C, COL); + PRODUCT(base_r, xh, xl, ph, pl); + } + coopMatPerElementNV(base_r, base_r, StoreOut, out_base + t0 * (p.H * D), valid); + + coopmat xh, xl; + coopmat kh, kl; + coopMatLoad(xh, sh_sh, 0, LDP, ROW); + coopMatLoad(xl, sh_sl, 0, LDP, ROW); + coopMatLoad(kh, sh_kqh, 0, LDP, ROW); + coopMatLoad(kl, sh_kql, 0, LDP, ROW); + state *= sh_ep[valid - 1]; + PRODUCT(state, xh, xl, kh, kl); + } + + coopMatStore(state, data_dst, p.s_off + state_base, D, ROW); +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index e988600e3d44..e20c94758900 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -348,7 +348,10 @@ compile_count_guard acquire_compile_slot() { } void string_to_spv_func(std::string name, std::string in_path, std::string out_path, std::map defines, bool coopmat, bool dep_file, compile_count_guard slot) { - std::string target_env = (name.find("_cm2") != std::string::npos) ? "--target-env=vulkan1.3" : "--target-env=vulkan1.2"; + // coopmat2 and the maintenance1 GDN coopmat1 variants need SPIR-V 1.6 (vulkan1.3) + const bool needs_spv16 = name.find("_cm2") != std::string::npos || + name.find("gated_delta_net_f32_cm1") != std::string::npos; + std::string target_env = needs_spv16 ? "--target-env=vulkan1.3" : "--target-env=vulkan1.2"; #ifdef _WIN32 std::vector cmd = {GLSLC, "-fshader-stage=compute", target_env, "\"" + in_path + "\"", "-o", "\"" + out_path + "\""}; @@ -1128,6 +1131,20 @@ void process_shaders() { string_to_spv("gated_delta_net_f32_nocluster", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); string_to_spv("gated_delta_net_f32_shmem", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "0"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); +#if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm2.comp", base_dict, true, false, true); +#endif +#if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}}), true, true, false, false, "_bf16acc"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", base_dict, true, true); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}, {"V", "32"}}), true, true, false, false, "_bf16acc_v32"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"V", "32"}}), true, true, false, false, "_v32"); + // whole-head V=128 variant: state mirror in a gmem scratch buffer (won't fit LDS). + // For head counts that tail the CU grid at V=64 (e.g. 48-head 27B on 64 CUs). + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}, {"GMEM_MIRROR", "1"}, {"V", "128"}}), true, true, false, false, "_bf16acc_v128"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"GMEM_MIRROR", "1"}, {"V", "128"}}), true, true, false, false, "_v128"); +#endif + string_to_spv("opt_step_adamw_f32", "opt_step_adamw.comp", merge_maps(base_dict, {{"A_TYPE", "float"}})); string_to_spv("opt_step_sgd_f32", "opt_step_sgd.comp", merge_maps(base_dict, {{"A_TYPE", "float"}})); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index a870016b0339..f75d93bc3458 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -5261,16 +5261,20 @@ struct test_gated_delta_net : public test_case { const bool permuted; const bool kda; const int64_t K; // snapshot slot count: 1 = final-only, >1 = last K states + const bool correlated; + const bool padded_v; + const bool padded_q; + const bool permuted_k; std::string vars() override { - return VARS_TO_STR9(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K); + return VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); } test_gated_delta_net(ggml_type type = GGML_TYPE_F32, int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1, - int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1) + int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false) : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), - v_repeat(v_repeat), permuted(permuted), kda(kda), K(K) {} + v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q; @@ -5280,11 +5284,15 @@ struct test_gated_delta_net : public test_case { // create with dims 1 and 2 swapped, then permute back to get non-contiguous layout q = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); - v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3); + v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size + padded_v, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3); } else { q = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); k = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); - v = ggml_new_tensor_4d(ctx, type, head_size, head_count * v_repeat, n_seq_tokens, n_seqs); + v = ggml_new_tensor_4d(ctx, type, head_size + padded_v, head_count * v_repeat, n_seq_tokens, n_seqs); + } + if (padded_v) { + ggml_set_name(v, "v"); + v = ggml_view_4d(ctx, v, head_size, head_count * v_repeat, n_seq_tokens, n_seqs, v->nb[1], v->nb[2], v->nb[3], 0); } ggml_set_name(q, "q"); ggml_set_name(k, "k"); @@ -5299,6 +5307,17 @@ struct test_gated_delta_net : public test_case { // q/k are L2-normalised in qwen35/kimi-linear before delta_net q = ggml_l2_norm(ctx, q, 1e-6f); k = ggml_l2_norm(ctx, k, 1e-6f); + // Set layouts after normalization, which produces contiguous tensors. + if (padded_q) { + ggml_tensor * q_padded = ggml_new_tensor_4d(ctx, type, head_size + 1, head_count, n_seq_tokens, n_seqs); + q_padded = ggml_view_4d(ctx, q_padded, head_size, head_count, n_seq_tokens, n_seqs, q_padded->nb[1], q_padded->nb[2], q_padded->nb[3], 0); + q = ggml_cpy(ctx, q, q_padded); + } + if (permuted_k) { + ggml_tensor * k_permuted = ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs); + k_permuted = ggml_permute(ctx, k_permuted, 0, 2, 1, 3); + k = ggml_cpy(ctx, k, k_permuted); + } ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); return out; } @@ -5307,9 +5326,17 @@ struct test_gated_delta_net : public test_case { for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { if (ggml_is_view_op(t->op)) { continue; } if (strcmp(t->name, "g") == 0) { - init_tensor_uniform(t, -20.0f, -1e-4f); + init_tensor_uniform(t, correlated ? -1e-4f : -20.0f, -1e-4f); } else if (strcmp(t->name, "beta") == 0) { - init_tensor_uniform(t, 0.0f, 1.0f); + init_tensor_uniform(t, correlated ? 0.9f : 0.0f, correlated ? 0.9f : 1.0f); + } else if (correlated && strcmp(t->name, "k") == 0) { + // Identical unit keys and weak decay stress cancellation in the triangular solve. + GGML_ASSERT(t->type == GGML_TYPE_F32); + std::vector data(ggml_nelements(t), 0.0f); + for (size_t i = 0; i < data.size(); i += size_t(t->ne[0])) { + data[i] = 1.0f; + } + ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(float)); } else if (strcmp(t->name, "v") == 0) { init_tensor_uniform(t, -0.3f, 5.0f); } else { @@ -13634,6 +13661,15 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 33, 1, 1, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 100, 1, 1, false, true)); + // KDA at D=128: decode, prefill, tails, strides, and snapshots. + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 2, 2, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, 1, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, 1, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4, 2, 2, false, true, 4)); + // MMA-eligible GDN shapes: whole heads, value slices, tails, and the HIP prefill threshold. test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 1, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 3, 4)); @@ -13645,6 +13681,30 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 2)); // Keep the WebGPU dispatch below 65535 workgroups (32 per token for this shape). test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2047, 2, 3)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4097, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 127, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 3)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 513, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 2, 2)); + + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 2, 2, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4095, 1, 2)); + + // Correlated keys, high beta, and weak decay stress the chunked triangular solve. + for (int64_t n_tokens : {64, 65, 257}) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, 1, true)); + } + + // Odd V strides require element loads instead of aligned matrix loads. + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, 1, false, true)); + + // Q and K can have different strides in both scalar and chunked paths. + for (int64_t n_tokens : {4, 65}) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true)); + } // K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first // (slot 0 = final state, slot s = state s tokens back). @@ -14296,12 +14356,34 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 256, 1)); // PP-256 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 512, 1)); // PP-512 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1024, 1)); // PP-1024 + // MMA-eligible prefill sweep (16 heads, d=128, K=1): Vulkan cm2 vs CUDA MMA + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 64, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 128, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 1024, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 4096, 1)); // Small model configs (fewer heads = less GPU occupancy for autoregressive) test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1)); // 4h PP-64 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 256, 1)); // 4h PP-256 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 512, 1)); // 4h PP-512 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 1024, 1)); // 4h PP-1024 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 64, 1, 1, false, true)); // KDA PP-64 + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 1024, 1, 1, false, true)); + // GDN model shapes: 35B (v_repeat=2), 27B (v_repeat=3), batch sweep + for (int T : { 2048, 4096, 8192, 16384, 32768 }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, T, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, T, 1, 3)); + } + + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4096, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1)); // lightning_indexer for (int kv : { 256, 4096, 65536 }) { From c0b97be0b297177a88df08e96c01420976bb18d0 Mon Sep 17 00:00:00 2001 From: Amadeus dyw <74057036+SG-Amadeus@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:38:43 +0800 Subject: [PATCH 14/88] vulkan: optimize RMS_NORM_MUL_ROPE loop control (#31149) --- .../ggml-vulkan/vulkan-shaders/rms_norm.comp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp index b9f0a1841b51..b73fdeca48fd 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp @@ -87,6 +87,12 @@ void rms_norm(uint num_iters) { #endif FLOAT_TYPE sum = FLOAT_TYPE(0.0f); // partial sum for thread in warp +#if RMS_NORM_ROPE_FUSION + for (uint col = tid; col < ncols; col += BLOCK_SIZE) { + const FLOAT_TYPE xi = FLOAT_TYPE(data_a[a_offset + col]); + sum += xi * xi; + } +#else [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { FLOAT_TYPE xi = FLOAT_TYPE(0); if (col < ncols) { @@ -94,6 +100,7 @@ void rms_norm(uint num_iters) { } sum += xi * xi; } +#endif #if USE_SUBGROUP_ADD sum = subgroupAdd(sum); @@ -131,6 +138,15 @@ void rms_norm(uint num_iters) { const FLOAT_TYPE mean = sum / FLOAT_TYPE(ncols); const FLOAT_TYPE scale = inversesqrt(mean + FLOAT_TYPE(p.param1)); +#if RMS_NORM_ROPE_FUSION + for (uint col = tid; col < ncols; col += BLOCK_SIZE) { + FLOAT_TYPE value = scale * FLOAT_TYPE(data_a[a_offset + col]); + if (do_multiply) { + value *= FLOAT_TYPE(data_b[b_offset + fastmod(col, p.ne10)]); + } + data_d[d_offset + col] = D_TYPE(value); + } +#else if (do_multiply) { if (ncols > p.ne10) { [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { @@ -169,6 +185,7 @@ void rms_norm(uint num_iters) { data_d[d_offset + col] = FLOAT_TO_D(scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col]))); } } +#endif #if RMS_NORM_ROPE_FUSION barrier(); rope_params rp = p.rope; @@ -185,6 +202,10 @@ void rms_norm(uint num_iters) { } void main() { +#if RMS_NORM_ROPE_FUSION + const uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; + rms_norm(num_blocks); +#else // instantiate the rms_norm function for several different // dimensions, to allow loop unrolling uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; @@ -209,4 +230,5 @@ void main() { } else if (num_blocks == 1) { rms_norm(1); } +#endif } From 9fbe30c2a0c207f9de7f38b23c43bc044b7a9981 Mon Sep 17 00:00:00 2001 From: Chinmay Shrivastava Date: Fri, 20 Nov 2026 01:42:16 -0600 Subject: [PATCH 15/88] CUDA: keep the MUL_MAT_ID precision in the per-expert fallback (#31345) * tests: add CUDA-only MUL_MAT/MUL_MAT_ID cases with results above the fp16 range IQ1_M weights have no MMQ kernel, so once the batch is bigger than the MMVQ limit the path is dequantize + cuBLAS. These cases produce results around 1.3e5, past the fp16 max of 65504, so an fp16 result buffer turns them into inf while the CPU reference stays finite. They are only added for the CUDA backend. Vulkan deliberately accumulates quantized matmuls in fp16 at default precision and would fail them by design. * CUDA: use an fp32 result for quantized src0 in the cuBLAS fallback On the F16 compute path, quantized weights went through cuBLAS with fp16 accumulation and an fp16 result buffer that was converted to fp32 afterwards. Anything above 65504 became inf and the next layer turned into NaN (see #30951: gpt-oss-120b with IQ1_M experts at -ub 512). Set prefer_f32_output for quantized src0 so the GEMM still uses fp16 operands but accumulates and stores in fp32, the same mode already used on Volta, RDNA4 and CDNA. Every other quantized path already accumulates in fp32. Diagnosis and fix by denizyuret in #30951. * CUDA: keep the MUL_MAT_ID precision in the per-expert fallback The per-expert dst_slice kept op = GGML_OP_NONE, so ggml_prec_get_acc returned UNDEFINED and a requested precision was ignored. Set the op to GGML_OP_MUL_MAT. Also revert the fp32 result change and remove the tests. --------- Co-authored-by: JonSnow1807 --- ggml/src/ggml-cuda/ggml-cuda.cu | 1 + 1 file changed, 1 insertion(+) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index a2db28adefdf..8702dd32d366 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -2783,6 +2783,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * ggml_tensor dst_slice; memset(&dst_slice, 0, sizeof(dst_slice)); memcpy(dst_slice.op_params, dst->op_params, sizeof(dst_slice.op_params)); + dst_slice.op = GGML_OP_MUL_MAT; // ggml_prec_get_acc/ggml_prec_get_src check the op dst_slice.buffer = dst->buffer; dst_slice.type = type_dst_sorted; dst_slice.ne[0] = ne0; From ea84d7090302e8cb9fa1e49d34c08fde5e5c2c55 Mon Sep 17 00:00:00 2001 From: Teng Mei <73174080+meitmt@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:44:04 +0900 Subject: [PATCH 16/88] CUDA: optimize Orin single-column MMVQ (#31268) * CUDA: optimize Orin single-column MMVQ * Create a separate Orin branch in `calc_rows_per_block` --- ggml/src/ggml-cuda/mmvq.cu | 46 +++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 612d3e313b25..091fc3071561 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -96,7 +96,8 @@ enum mmvq_parameter_table_id { MMVQ_PARAMETERS_RDNA2, MMVQ_PARAMETERS_RDNA3_0, MMVQ_PARAMETERS_RDNA4, - MMVQ_PARAMETERS_GB10 + MMVQ_PARAMETERS_GB10, + MMVQ_PARAMETERS_ORIN }; static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { @@ -112,6 +113,8 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { return MMVQ_PARAMETERS_TURING; #elif __CUDA_ARCH__ == GGML_CUDA_CC_GB10 return MMVQ_PARAMETERS_GB10; +#elif __CUDA_ARCH__ == GGML_CUDA_CC_ORIN + return MMVQ_PARAMETERS_ORIN; #else return MMVQ_PARAMETERS_GENERIC; #endif @@ -136,6 +139,9 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) { if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_GB10) { return MMVQ_PARAMETERS_GB10; } + if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_ORIN) { + return MMVQ_PARAMETERS_ORIN; + } return MMVQ_PARAMETERS_GENERIC; } @@ -580,6 +586,9 @@ static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_d } return generic; } + if (table_id == MMVQ_PARAMETERS_ORIN) { + return calc_nwarps(type, ncols_dst, MMVQ_PARAMETERS_GENERIC); + } return 1; } @@ -620,6 +629,41 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int return 1; } } + if (table_id == MMVQ_PARAMETERS_ORIN) { + switch (ncols_dst) { + case 1: + if (small_k) { + return nwarps; + } + // One row per warp (more rows per block, more loads in flight) for these types, measured on Jetson Orin Nano. + // Other types are faster in isolated mat-vec too, but gained at most 2 % end to end. + switch (type) { + case GGML_TYPE_Q4_0: + case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q5_1: + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + case GGML_TYPE_IQ4_NL: + return nwarps; + default: + break; + } + return mmvq_two_rows_ncols1(type) ? 2 : 1; + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + return 2; + default: + return 1; + } + } return 1; } From d7d1b632da766f1247456b4f42406a96a0609d93 Mon Sep 17 00:00:00 2001 From: Nikhil Jain Date: Thu, 19 Nov 2026 23:45:44 -0800 Subject: [PATCH 17/88] webgpu : fix 2D indexing for copy kernel (#32576) * Only run webgpu CI on my fork * Add webgpu only workflow * resolve merge conflicts * Add 2d indexing to copy kernel * move test --- ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl | 8 +++++--- tests/test-backend-ops.cpp | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl index 0d0d81ab650f..2466b2f0b7ca 100644 --- a/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl +++ b/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl @@ -53,12 +53,14 @@ var params: Params; @compute @workgroup_size(WG_SIZE) fn main( @builtin(global_invocation_id) gid: vec3, + @builtin(num_workgroups) num_wg: vec3, ) { - if (gid.x >= params.ne) { + let idx = gid.x + num_wg.x * WG_SIZE * gid.y; + if (idx >= params.ne) { return; } - var i = gid.x; + var i = idx; let i3 = i / (params.src_ne2 * params.src_ne1 * params.src_ne0); i = i % (params.src_ne2 * params.src_ne1 * params.src_ne0); let i2 = i / (params.src_ne1 * params.src_ne0); @@ -66,7 +68,7 @@ fn main( let i1 = i / params.src_ne0; let i0 = i % params.src_ne0; - var j = gid.x; + var j = idx; let j3 = j / (params.dst_ne2 * params.dst_ne1 * params.dst_ne0); j = j % (params.dst_ne2 * params.dst_ne1 * params.dst_ne0); let j2 = j / (params.dst_ne1 * params.dst_ne0); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index f75d93bc3458..42e356ae0617 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -11507,7 +11507,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_cpy(GGML_TYPE_F16, GGML_TYPE_F16, {128, 2, 3, 1}, {128, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, false, {128, 4, 3, 1})); // strided dst test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {64, 16, 1, 1}, {1, 64, 16, 1}, {1, 2, 0, 3}, {0, 0, 0, 0}, false, {32, 64, 16, 1})); // permuted src, strided dst test_cases.emplace_back(new test_cpy(GGML_TYPE_F16, GGML_TYPE_F16, {64, 16, 1, 1}, {1, 64, 16, 1}, {1, 2, 0, 3}, {0, 0, 0, 0}, false, {32, 64, 16, 1})); // permuted src, strided dst - + test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {2, 2, 524281, 1}, {-1,-1,-1,-1}, {1, 0, 2, 3})); // CPY - different src/dst shapes (reshaping via CPY) // Use permutations of {3, 5, 7, 32}. Total elements: 3*5*7*32 = 3360. // Each src permutation is tested against canonical sorted and reverse dst (skip self). From 52e8db65500e3078b859f5a0e8c4b5e5a0c8315c Mon Sep 17 00:00:00 2001 From: sys2008 <165458212+sys2008@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:46:59 +0800 Subject: [PATCH 18/88] kleidiai : allow OHOS (HarmonyOS) AArch64 target (#32265) * kleidiai : allow OHOS (HarmonyOS) AArch64 target * kleidiai : allow OHOS AArch64 target Assisted-by: GLM --- ggml/src/ggml-cpu/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-cpu/CMakeLists.txt b/ggml/src/ggml-cpu/CMakeLists.txt index 8327c52e6dae..172789bd70fa 100644 --- a/ggml/src/ggml-cpu/CMakeLists.txt +++ b/ggml/src/ggml-cpu/CMakeLists.txt @@ -635,7 +635,7 @@ function(ggml_add_cpu_backend_variant_impl tag_name) set(GGML_CPU_KLEIDIAI_AARCH64 OFF) if (GGML_SYSTEM_ARCH STREQUAL "ARM" AND - (APPLE OR WIN32 OR CMAKE_SYSTEM_NAME MATCHES "^(Linux|Android)$") AND + (APPLE OR WIN32 OR CMAKE_SYSTEM_NAME MATCHES "^(Linux|Android|OHOS)$") AND (CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64|ARM64|arm64-v8a)$" OR CMAKE_OSX_ARCHITECTURES MATCHES "arm64" OR CMAKE_GENERATOR_PLATFORM_LWR STREQUAL "arm64" OR From bed8ec2f8d484520d4822c582a94424a03e172e7 Mon Sep 17 00:00:00 2001 From: Aaron Teo Date: Fri, 20 Nov 2026 15:47:41 +0800 Subject: [PATCH 19/88] llamafile(s390x): add QK data type support (#32600) * llamafile: add QK support for s390x Signed-off-by: Aaron Teo * llamafile: clean up for s390x Signed-off-by: Aaron Teo --------- Signed-off-by: Aaron Teo --- ggml/src/ggml-cpu/llamafile/sgemm.cpp | 361 ++++++++++++++++++++++++++ 1 file changed, 361 insertions(+) diff --git a/ggml/src/ggml-cpu/llamafile/sgemm.cpp b/ggml/src/ggml-cpu/llamafile/sgemm.cpp index 68105f029fbf..5d660911316d 100644 --- a/ggml/src/ggml-cpu/llamafile/sgemm.cpp +++ b/ggml/src/ggml-cpu/llamafile/sgemm.cpp @@ -1474,6 +1474,282 @@ class tinyBLAS_Q0_VXE { const int32_t ith; const int32_t nth; }; + +template +class tinyBLAS_QK_VXE { + public: + tinyBLAS_QK_VXE(int64_t k, + const TA * A, int64_t lda, + const block_q8_K * B, int64_t ldb, + float * C, int64_t ldc, + int32_t ith, int32_t nth) + : A(A), B(B), C(C), k(k), lda(lda), ldb(ldb), ldc(ldc), ith(ith), nth(nth) { + } + + void matmul(int64_t m, int64_t n) { + const int64_t n4 = n / 4 * 4; + const int64_t n2 = n / 2 * 2; + gemm<4>(m, 0, n4); + gemm<2>(m, n4, n2); + gemm<1>(m, n2, n); + } + + private: + // one block of A is loaded once and used for RN columns of B + template + void gemm(int64_t m, int64_t n0, int64_t n) { + const int64_t tiles = m * ((n - n0) / RN); + const int64_t duty = (tiles + nth - 1) / nth; + const int64_t start = duty * ith; + const int64_t end = MIN(start + duty, tiles); + + for (int64_t job = start; job < end; ++job) { + const int64_t ii = job % m; + const int64_t jj = n0 + RN * (job / m); + float32x4_t v_sum[RN] = {}; + + for (int64_t l = 0; l < k; ++l) { + const TA & x = A[lda * ii + l]; + + int8x16_t v_x[n_group]; + load(x, v_x); + + // scale and minimum of the 16 groups, 8 groups per vector + int16x8_t v_scalel, v_scaleh; + int16x8_t v_minl, v_minh; + load_scale(x, v_scalel, v_scaleh, v_minl, v_minh); + + int16x8_t v_scale[n_group]; + for (int32_t g = 0; g < n_group; ++g) { + v_scale[g] = vec_splats((g < n_group / 2 ? v_scalel : v_scaleh)[g % (n_group / 2)]); + } + + const int8_t * y_qs[RN]; + for (int32_t j = 0; j < RN; ++j) { + y_qs[j] = B[ldb * (jj + j) + l].qs; + } + + // the columns are in the inner loop, so that their sums do not wait for each other + int32x4_t v_dot[RN] = {}; + for (int32_t g = 0; g < n_group; ++g) { + for (int32_t j = 0; j < RN; ++j) { + const int8x16_t v_y = vec_xl(0, y_qs[j] + 16 * g); + const int16x8_t v_xy = vec_meadd(v_x[g], v_y, vec_mulo(v_x[g], v_y)); + v_dot[j] = vec_meadd(v_xy, v_scale[g], vec_moadd(v_xy, v_scale[g], v_dot[j])); + } + } + + const float x_d = unhalf(x.d); + for (int32_t j = 0; j < RN; ++j) { + const block_q8_K & y = B[ldb * (jj + j) + l]; + v_sum[j] = vec_madd(vec_float(v_dot[j]), vec_splats(x_d * y.d), v_sum[j]); + } + + if (has_min) { + const float x_dmin = dmin(x); + + for (int32_t j = 0; j < RN; ++j) { + const block_q8_K & y = B[ldb * (jj + j) + l]; + + const int16_t * y_bsums = y.bsums; + const int16x8_t v_bsumsl = vec_xl(0, y_bsums); + const int16x8_t v_bsumsh = vec_xl(0, y_bsums + n_group / 2); + + const int32x4_t v_minsl = vec_meadd(v_bsumsl, v_minl, vec_mulo(v_bsumsl, v_minl)); + const int32x4_t v_minsh = vec_meadd(v_bsumsh, v_minh, vec_mulo(v_bsumsh, v_minh)); + v_sum[j] = vec_madd(vec_float(v_minsl + v_minsh), vec_splats(-x_dmin * y.d), v_sum[j]); + } + } + } + + for (int32_t j = 0; j < RN; ++j) { + C[ldc * (jj + j) + ii] = hsum(v_sum[j]); + } + } + } + + // a block has 16 groups of 16 weights, Q4_K and Q5_K share one scale and minimum per 2 groups + static constexpr int32_t n_group = QK_K / 16; + + // Q3_K and Q6_K have no minimum, their weights are loaded as signed values. + static constexpr bool has_min = !std::is_same::value && !std::is_same::value; + + static float dmin(const block_q2_K & x) { return unhalf(x.dmin); } + static float dmin(const block_q4_K & x) { return unhalf(x.dmin); } + static float dmin(const block_q5_K & x) { return unhalf(x.dmin); } + template static float dmin(const T &) { return 0.0f; } + + static void load(const block_q2_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x03); + const uint8_t * x_qs = x.qs; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qs_shift = 2 * (g % 8 / 2); + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + v_x[g] = (int8x16_t)vec_and(vec_sr(v_qs, qs_shift), v_mask); + } + } + + static void load(const block_q3_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x03); + const uint8x16_t v_one = vec_splats((uint8_t)0x01); + + const uint8_t * x_qs = x.qs; + const uint8_t * x_hmask = x.hmask; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qs_shift = 2 * (g % 8 / 2); + const int32_t hmask_offset = 16 * (g % 2); + const int32_t hmask_shift = g / 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + const uint8x16_t v_hmask = vec_xl(0, x_hmask + hmask_offset); + const uint8x16_t v_lo = vec_and(vec_sr(v_qs, qs_shift), v_mask); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_hmask, hmask_shift), v_one), 2); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)4); + } + } + + static void load(const block_q4_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x0F); + const uint8_t * x_qs = x.qs; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 4) + g % 2); + const bool qs_low = g % 4 < 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + v_x[g] = (int8x16_t)(qs_low ? vec_and(v_qs, v_mask) : vec_sr(v_qs, 4)); + } + } + + static void load(const block_q5_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x0F); + const uint8x16_t v_one = vec_splats((uint8_t)0x01); + const uint8_t * x_qs = x.qs; + const uint8_t * x_qh = x.qh; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 4) + g % 2); + const bool qs_low = g % 4 < 2; + const int32_t qh_offset = 16 * (g % 2); + const int32_t qh_shift = g / 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + const uint8x16_t v_qh = vec_xl(0, x_qh + qh_offset); + const uint8x16_t v_lo = qs_low ? vec_and(v_qs, v_mask) : vec_sr(v_qs, 4); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_qh, qh_shift), v_one), 4); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi); + } + } + + static void load(const block_q6_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask4 = vec_splats((uint8_t)0x0F); + const uint8x16_t v_mask2 = vec_splats((uint8_t)0x03); + const uint8_t * x_ql = x.ql; + const uint8_t * x_qh = x.qh; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t ql_offset = 16 * (4 * (g / 8) + 2 * (g % 4 / 2) + g % 2); + const bool ql_low = g % 8 < 4; + const int32_t qh_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qh_shift = 2 * (g % 8 / 2); + + const uint8x16_t v_ql = vec_xl(0, x_ql + ql_offset); + const uint8x16_t v_qh = vec_xl(0, x_qh + qh_offset); + const uint8x16_t v_lo = ql_low ? vec_and(v_ql, v_mask4) : vec_sr(v_ql, 4); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_qh, qh_shift), v_mask2), 4); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)32); + } + } + + static void load_scale(const block_q2_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + const uint8_t * x_scales = x.scales; + const uint8x16_t v_s = vec_xl(0, x_scales); + const uint8x16_t v_scale = vec_and(v_s, vec_splats((uint8_t)0x0F)); + const uint8x16_t v_min = vec_sr(v_s, 4); + + v_scalel = (int16x8_t)vec_unpackh(v_scale); + v_scaleh = (int16x8_t)vec_unpackl(v_scale); + v_minl = (int16x8_t)vec_unpackh(v_min); + v_minh = (int16x8_t)vec_unpackl(v_min); + } + + static void load_scale(const block_q3_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + // 6-bit scales: low 4 bits in scales[0..7], high 2 bits in scales[8..11] + const uint8x16_t v_lo_byte = { 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 8, 9, 10, 11 }; + const uint8x16_t v_lo_shift = { 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4 }; + const uint8x16_t v_hi_byte = { 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15 }; + const uint8x16_t v_hi_shift = { 0, 0, 0, 0, 2, 2, 2, 2, 4, 4, 4, 4, 6, 6, 6, 6 }; + + // the load starts 4 bytes before scales, so that it stays inside the block + const uint8_t * x_qs = x.qs; + const uint8x16_t v_s = vec_xl(0, x_qs + sizeof(x.qs) - 4); + const uint8x16_t v_lo = vec_and(vec_sr(vec_perm(v_s, v_s, v_lo_byte), v_lo_shift), vec_splats((uint8_t)0x0F)); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(vec_perm(v_s, v_s, v_hi_byte), v_hi_shift), vec_splats((uint8_t)0x03)), 4); + const int8x16_t v_scale = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)32); + + v_scalel = vec_unpackh(v_scale); + v_scaleh = vec_unpackl(v_scale); + v_minl = vec_splats((int16_t)0); + v_minh = vec_splats((int16_t)0); + } + + static void load_scale(const block_q4_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + load_scale_min_k4(x.scales, v_scalel, v_scaleh, v_minl, v_minh); + } + + static void load_scale(const block_q5_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + load_scale_min_k4(x.scales, v_scalel, v_scaleh, v_minl, v_minh); + } + + static void load_scale(const block_q6_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + const int8_t * x_scales = x.scales; + const int8x16_t v_scale = vec_xl(0, x_scales); + + v_scalel = vec_unpackh(v_scale); + v_scaleh = vec_unpackl(v_scale); + v_minl = vec_splats((int16_t)0); + v_minh = vec_splats((int16_t)0); + } + + // 8 scales and 8 minimums of 6 bits, same packing as get_scale_min_k4 in ggml-quants.c + static void load_scale_min_k4(const uint8_t * q, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + // bytes 0..3 and 4..7 have the high 2 bits of scale 4..7 and minimum 4..7, move them to bytes 8..11 + const uint8x16_t v_hi_scale = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0 }; + const uint8x16_t v_hi_min = { 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 0, 0, 0, 0 }; + // each scale and minimum is for 2 groups + const uint8x16_t v_group_scale = { 0, 0, 1, 1, 2, 2, 3, 3, 24, 24, 25, 25, 26, 26, 27, 27 }; + const uint8x16_t v_group_min = { 4, 4, 5, 5, 6, 6, 7, 7, 24, 24, 25, 25, 26, 26, 27, 27 }; + + // the 4 bytes after the 12 scale bytes are in the same block + const uint8x16_t v_s = vec_xl(0, q); + const uint8x16_t v_lo = vec_and(v_s, vec_splats((uint8_t)0x3F)); + const uint8x16_t v_hi = vec_sl(vec_sr(v_s, 6), 4); + const uint8x16_t v_scale_47 = vec_or(vec_and(v_s, vec_splats((uint8_t)0x0F)), vec_perm(v_hi, v_hi, v_hi_scale)); + const uint8x16_t v_min_47 = vec_or(vec_sr(v_s, 4), vec_perm(v_hi, v_hi, v_hi_min)); + const uint8x16_t v_scale = vec_perm(v_lo, v_scale_47, v_group_scale); + const uint8x16_t v_min = vec_perm(v_lo, v_min_47, v_group_min); + + v_scalel = (int16x8_t)vec_unpackh(v_scale); + v_scaleh = (int16x8_t)vec_unpackl(v_scale); + v_minl = (int16x8_t)vec_unpackh(v_min); + v_minh = (int16x8_t)vec_unpackl(v_min); + } + + const TA * const A; + const block_q8_K * const B; + float * const C; + const int64_t k; + const int64_t lda; + const int64_t ldb; + const int64_t ldc; + const int32_t ith; + const int32_t nth; +}; #endif #if defined(__ARM_FEATURE_DOTPROD) @@ -4488,6 +4764,91 @@ bool llamafile_sgemm(const struct ggml_compute_params * params, int64_t m, int64 #endif } + case GGML_TYPE_Q2_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q2_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q3_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q3_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q4_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q4_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q5_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q5_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q6_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q6_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + case GGML_TYPE_IQ4_NL: { if (Btype != GGML_TYPE_Q8_0) return false; From 55d323507de290f5baacf56082b087a6bccfc7d9 Mon Sep 17 00:00:00 2001 From: nicholas-mainardi-domyn Date: Fri, 20 Nov 2026 08:51:41 +0100 Subject: [PATCH 20/88] model: add Domyn Edge 4B Model (#32559) * feat: add domyn-edge model * Generate tokenizer hash for conversion + fix tests * Address changes according to code-review skill * catch ValueError in convert_hf_to_gguf_update.py * renegerate fusion test baseline + fix model naming style --- conversion/__init__.py | 1 + conversion/base.py | 3 + conversion/domynedge.py | 53 +++++++++++ convert_hf_to_gguf_update.py | 6 +- gguf-py/gguf/constants.py | 18 ++++ gguf-py/gguf/tensor_mapping.py | 8 ++ src/llama-arch.cpp | 1 + src/llama-arch.h | 1 + src/llama-model.cpp | 3 + src/llama-vocab.cpp | 3 +- src/models/domyn-edge.cpp | 164 +++++++++++++++++++++++++++++++++ src/models/models.h | 13 +++ tests/fusion/MTL.csv | 2 + tests/test-llama-archs.cpp | 10 +- tests/test-tokenizer-random.py | 9 +- 15 files changed, 285 insertions(+), 10 deletions(-) create mode 100644 conversion/domynedge.py create mode 100644 src/models/domyn-edge.cpp diff --git a/conversion/__init__.py b/conversion/__init__.py index 1182c06be3c0..253a18fd48aa 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -78,6 +78,7 @@ "DistilBertForMaskedLM": "bert", "DistilBertForSequenceClassification": "bert", "DistilBertModel": "bert", + "DomynEdgeForCausalLM": "domynedge", "Dots1ForCausalLM": "dots1", "Dots3NoteForCausalLM": "dots3", "Dots3NoteForConditionalGeneration": "dots3", diff --git a/conversion/base.py b/conversion/base.py index 7cfbff321e0d..540a66ba5098 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -2470,6 +2470,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: if chkhsh == "5635e1c8d621dff7b4825f41f2f97b6ceb39bcf2d5c541db28577080d6efd5e5": # ref: https://huggingface.co/thinkingmachines/Inkling-2-Small res = "inkling2" + if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3": + # ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF + res = "domyn-edge" if res is None: logger.warning("\n") diff --git a/conversion/domynedge.py b/conversion/domynedge.py new file mode 100644 index 000000000000..df07add83cbf --- /dev/null +++ b/conversion/domynedge.py @@ -0,0 +1,53 @@ +from .base import TextModel, ModelBase +import gguf + + +@ModelBase.register("DomynEdgeForCausalLM") +@ModelBase.example("domyn/Domyn-Edge-Teacher-IF") +class DomynEdgeModel(TextModel): + model_arch = gguf.MODEL_ARCH.DOMYN_EDGE + + def set_gguf_parameters(self): + super().set_gguf_parameters() + hparams = self.hparams + self.gguf_writer.add_vocab_size(hparams["vocab_size"]) + + position_layers = hparams["position_layers"] # list of "rope"/"nope" strings per layer + head_sizes = hparams["head_sizes"] # list of int head dims per layer + + # Per-layer rope/SWA pattern: True="rope", False="nope" + rope_pattern = [v == "rope" for v in position_layers] + self.gguf_writer.add_rope_pattern(rope_pattern) + self.gguf_writer.add_sliding_window_pattern(rope_pattern) # SWA <-> RoPE in domyn-edge + + # window_sizes entries are flash-attn style [left, right] (current token excluded; -1 = full attention), + # while llama.cpp's n_swa counts the current token, hence the +1 (matches HF's sliding_window=1025) + swa_window = hparams.get("sliding_window") + if swa_window is None: + window_sizes = hparams.get("window_sizes") # list of [size, offset] pairs per layer + if window_sizes is None: + raise KeyError("Neither `sliding_window` nor `window_sizes` found among domyn edge hyperparameters") + left = next((ws[0] for v, ws in zip(position_layers, window_sizes) if v == "rope"), None) + swa_window = left + 1 if left is not None and left > 0 else None + if swa_window is None: + raise ValueError("No sliding window size found among domyn edge hyperparameters") + self.gguf_writer.add_sliding_window(swa_window) + + # Head dims differ between full-attention ("nope") and SWA ("rope") layers + full_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "nope"} + swa_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "rope"} + + if len(full_head_dims) != 1: + raise ValueError(f"Expected one head dimension for full attention layers, found {len(full_head_dims)}") + full_head_dim = full_head_dims.pop() + + self.gguf_writer.add_key_length(full_head_dim) + self.gguf_writer.add_value_length(full_head_dim) + + if len(swa_head_dims) != 1: + raise ValueError(f"Expected one head dimension for SWA attention layers, found {len(swa_head_dims)}") + swa_head_dim = swa_head_dims.pop() + + self.gguf_writer.add_key_length_swa(swa_head_dim) + self.gguf_writer.add_value_length_swa(swa_head_dim) + self.gguf_writer.add_rope_dimension_count_swa(swa_head_dim) diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py index ff5fca4fff89..91fb418a5f2d 100755 --- a/convert_hf_to_gguf_update.py +++ b/convert_hf_to_gguf_update.py @@ -168,6 +168,7 @@ class TOKENIZER_TYPE(IntEnum): {"name": "mmbert", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jhu-clsp/mmBERT-base", }, {"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", }, {"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", }, + {"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", }, ] # some models are known to be broken upstream, so we will skip them as exceptions @@ -227,8 +228,6 @@ def download_model(model): repo = model["repo"] tokt = model["tokt"] - os.makedirs(f"models/tokenizers/{name}", exist_ok=True) - files = ["config.json", "tokenizer.json", "tokenizer_config.json"] if name == "gpt-4o": @@ -243,6 +242,7 @@ def download_model(model): if os.path.isdir(repo): # If repo is a path on the file system, copy the directory + os.makedirs(f"models/tokenizers/{name}", exist_ok=True) for file in files: src_path = os.path.join(repo, file) dst_path = f"models/tokenizers/{name}/{file}" @@ -484,7 +484,7 @@ def get_vocab_base_pre(self, tokenizer) -> str: tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}", use_fast=False) else: tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}") - except (OSError, TypeError) as e: + except (OSError, TypeError, ValueError) as e: logger.error(f"Failed to load tokenizer for model {name}. Error: {e}") continue # Skip this model and continue with the next one in the loop diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index e07ea2f4b7c2..f36566a815d9 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -778,6 +778,7 @@ class MODEL_ARCH(IntEnum): KOLIBRI1 = auto() LIMITE = auto() INKLING2 = auto() + DOMYN_EDGE = auto() class VISION_PROJECTOR_TYPE(IntEnum): @@ -1778,6 +1779,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.KOLIBRI1: "kolibri1", MODEL_ARCH.LIMITE: "limite", MODEL_ARCH.INKLING2: "inkling2", + MODEL_ARCH.DOMYN_EDGE: "domynedge", } VISION_PROJECTOR_TYPE_NAMES: dict[VISION_PROJECTOR_TYPE, str] = { @@ -7085,6 +7087,22 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_POST_CONV, MODEL_TENSOR.FFN_RES_QUERY, ], + MODEL_ARCH.DOMYN_EDGE: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_K_NORM, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_PRE_NORM, + MODEL_TENSOR.FFN_POST_NORM, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.OUTPUT_NORM, + ], } # tensors that will not be serialized diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index c844a9322b12..d48d46b9a307 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -272,6 +272,7 @@ class TensorNameMap: "model.layers.{bid}.pre_attention_layernorm", # kormo "head.layers.{bid}.norm1", # laya "model.layers.{bid}.attn_norm", # inkling2 + "model.layers.{bid}.pre_attention_norm", # domynedge ), # Attention norm 2 @@ -440,6 +441,7 @@ class TensorNameMap: "model.layers.{bid}.post_attn_norm", # kolibri1 "model.layers.layers.{bid}.post_mixer_norm.weight", # plamo2 "model.layers.{bid}.post_operator_norm", # lfm3 + "model.layers.{bid}.post_attention_norm", # domynedge ), # Rotary embeddings @@ -579,6 +581,7 @@ class TensorNameMap: "layers.{bid}.pre_feedforward_layernorm", # embeddinggemma "model.layers.{bid}.pre_ff_layernorm.weight", "model.layers.{bid}.pre_mlp_layernorm", # afmoe + "model.layers.{bid}.pre_feedforward_norm", # domynedge ), MODEL_TENSOR.FFN_PRE_NORM_2: ( @@ -603,6 +606,7 @@ class TensorNameMap: "model.layers.{bid}.feed_forward.up_proj", "model.layers.{bid}.post_moe_norm", # grok-2 "model.layers.{bid}.post_ffn_norm", # lfm3 + "model.layers.{bid}.post_feedforward_norm", # domynedge ), MODEL_TENSOR.FFN_POST_NORM_1: ( @@ -692,6 +696,7 @@ class TensorNameMap: "encoder.layers.{bid}.mlp.dense_h_to_4h", # chatglm "transformer.h.{bid}.mlp.c_fc_1", # exaone "model.layers.{bid}.feed_forward.up_proj", # llama4 jamba granite-hybrid + "model.layers.{bid}.feedforward.up_proj", # domynedge "transformer_encoder.{bid}.ffn.w12", # neobert "model.layers.{bid}.block_sparse_moe.up", # smallthinker "model.transformer.blocks.{bid}.up_proj", # llada @@ -755,6 +760,7 @@ class TensorNameMap: "layers.{bid}.mlp.gate_proj", # qwen3-embedding "model.layers.{bid}.mlp.language_mlp.gate_proj", # cogvlm "model.blocks.{bid}.mlp.mlp_gate", # talkie + "model.layers.{bid}.feedforward.gate_proj", # domynedge ), MODEL_TENSOR.FFN_GATE_EXP: ( @@ -923,6 +929,7 @@ class TensorNameMap: "encoder.layers.{bid}.mlp.dense_4h_to_h", # chatglm "model.layers.h.{bid}.mlp.c_proj", # exaone "model.layers.{bid}.feed_forward.down_proj", # llama4 jamba granite-hybrid + "model.layers.{bid}.feedforward.down_proj", # domynedge "transformer_encoder.{bid}.ffn.w3", # neobert "model.layers.{bid}.block_sparse_moe.down", # smallthinker "model.transformer.blocks.{bid}.ff_out", # llada @@ -997,6 +1004,7 @@ class TensorNameMap: "layers.{bid}.self_attn.k_norm", # qwen3-embedding "model.layers.{bid}.self_attn.k_rope_only_layernorm", # dots3note "model.layers.{bid}.attention.key_layernorm", # apertus + "model.layers.{bid}.attention.k_norm", # domynedge ), MODEL_TENSOR.ROPE_FREQS: ( diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index c50e9f98a200..1c90b2180bfd 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -184,6 +184,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_KOLIBRI1, "kolibri1" }, { LLM_ARCH_RICURSIVE, "ricursive" }, { LLM_ARCH_INKLING2, "inkling2" }, + { LLM_ARCH_DOMYN_EDGE, "domynedge" }, { LLM_ARCH_UNKNOWN, "(unknown)" }, }; diff --git a/src/llama-arch.h b/src/llama-arch.h index 9c517a9fe15d..a8c0fdf098fd 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -188,6 +188,7 @@ enum llm_arch { LLM_ARCH_LIMITE, LLM_ARCH_RICURSIVE, LLM_ARCH_INKLING2, + LLM_ARCH_DOMYN_EDGE, LLM_ARCH_UNKNOWN, }; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index ac5266a42d2a..629b3a7a6899 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -394,6 +394,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_k2_horizon(params); case LLM_ARCH_KOLIBRI1: return new llama_model_kolibri1(params); + case LLM_ARCH_DOMYN_EDGE: + return new llama_model_domyn_edge(params); default: throw std::runtime_error(std::string("unsupported model architecture: '") + llm_arch_name(arch) + "'"); } @@ -3873,6 +3875,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_HRM_TEXT: case LLM_ARCH_BEAM: case LLM_ARCH_KOLIBRI1: + case LLM_ARCH_DOMYN_EDGE: return LLAMA_ROPE_TYPE_NEOX; case LLM_ARCH_DFLASH: diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 3aecacb516bc..f3e1d0192414 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -2566,7 +2566,8 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { tokenizer_pre == "qwen2" || tokenizer_pre == "deepseek-r1-qwen" || tokenizer_pre == "kormo" || - tokenizer_pre == "f2llmv2") { + tokenizer_pre == "f2llmv2" || + tokenizer_pre == "domyn-edge") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; clean_spaces = false; } else if ( diff --git a/src/models/domyn-edge.cpp b/src/models/domyn-edge.cpp new file mode 100644 index 000000000000..6452894d34be --- /dev/null +++ b/src/models/domyn-edge.cpp @@ -0,0 +1,164 @@ +#include "models.h" + +void llama_model_domyn_edge::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + // required: the base loader defaults it to n_rot_full if the key is not found + ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT_SWA, hparams.n_rot_swa); + // RoPE cannot rotate more dims than the SWA head has: CPU aborts, GPU backends read past the row + if (hparams.n_rot_swa > hparams.n_embd_head_k_swa) { + throw std::runtime_error(format("invalid n_rot_swa: %u, max %u", hparams.n_rot_swa, hparams.n_embd_head_k_swa)); + } + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + + ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + ml.get_arr(LLM_KV_ATTENTION_ROPE_PATTERN, hparams.rope_pattern); + + // only for print_info / saver; get_rope_params uses cparams + hparams.rope_freq_base_train_swa = hparams.rope_freq_base_train; + hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train; + + switch (hparams.n_layer()) { + case 36: type = LLM_TYPE_4B; break; + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_domyn_edge::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); + + // if output is NULL, init from the input tok embed + if (output == NULL) { + output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + } + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + const int64_t n_embd_head_i = hparams.n_embd_head_k(i); + const int64_t n_embd_k_i = hparams.n_embd_k_gqa(i); + const int64_t n_embd_v_i = hparams.n_embd_v_gqa(i); + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0); + + const int64_t n_embd_q_i = n_embd_head_i * n_head; + create_tensor_qkv(layer, i, n_embd, n_embd_q_i, n_embd_k_i, n_embd_v_i, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_i * n_head, n_embd}, 0); + + // K-norm has a learnable weight; Q-norm does not + layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_i}, 0); + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0); + + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + } +} + +llama_rope_params llama_model_domyn_edge::get_rope_params(const llama_cparams & cparams, int il) const { + auto res = llama_model::get_rope_params(cparams, il); + + // the SWA layers use the global base and scale + res.freq_base = cparams.rope_freq_base; + res.freq_scale = cparams.rope_freq_scale; + + return res; +} + +llama_model_domyn_edge::graph::graph(const llm_graph_params & params) + : llm_graph_context(params) { + ggml_tensor * cur; + ggml_tensor * inpL = build_inp_embd(model.tok_embd); + ggml_tensor * inp_pos = build_inp_pos(); + + auto * inp_attn = build_attn_inp_kv_iswa(); + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + const int64_t n_embd_head = hparams.n_embd_head_k(il); + const int64_t n_head_il = hparams.n_head(il); + const int64_t n_head_kv_il = hparams.n_head_kv(il); + const float kq_scale = 1.0f / sqrtf((float)n_embd_head); + + ggml_tensor * residual = inpL; + + // pre-attention norm + cur = build_norm(inpL, layer.attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + auto [Qcur, Kcur, Vcur] = build_qkv(layer, cur, n_embd_head, n_head_il, n_head_kv_il, il); + + // Q-norm: RMSNorm without learnable weight (elementwise_affine=False) + Qcur = build_norm(Qcur, NULL, NULL, LLM_NORM_RMS, il); + cb(Qcur, "Qcur_normed", il); + + // K-norm: RMSNorm with learnable weight + Kcur = build_norm(Kcur, layer.attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(Kcur, "Kcur_normed", il); + + // build_rope already applies RoPE only if the current layer is a RoPE layer + Qcur = build_rope(Qcur, inp_pos, il); + cb(Qcur, "Qcur_rope", il); + + Kcur = build_rope(Kcur, inp_pos, il); + cb(Kcur, "Kcur_rope", il); + + cur = build_attn(inp_attn, + layer.wo, NULL, layer.wo_s, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il); + cb(cur, "attn_out", il); + + // post-attention norm applied to attn output before residual add + cur = build_norm(cur, layer.attn_post_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_post_norm", il); + + if (il == n_layer - 1 && inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + residual = ggml_get_rows(ctx0, residual, inp_out_ids); + } + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, residual); + cb(ffn_inp, "ffn_inp", il); + + // pre-FFN norm + cur = build_norm(ffn_inp, layer.ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + // SwiGLU FFN + cur = build_ffn(cur, + layer.ffn_up, NULL, NULL, + layer.ffn_gate, NULL, NULL, + layer.ffn_down, NULL, NULL, NULL, + LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(cur, "ffn_out", il); + + // post-FFN norm applied to ffn output before residual add + cur = build_norm(cur, layer.ffn_post_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_post_norm", il); + + cur = ggml_add(ctx0, cur, ffn_inp); + inpL = build_cvec(cur, il); + cb(inpL, "l_out", il); + } + + cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur, model.output_s); + cb(cur, "result_output", -1); + res->t_logits = cur; +} + +std::unique_ptr llama_model_domyn_edge::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} diff --git a/src/models/models.h b/src/models/models.h index e7849e07d3d9..e0a4db5f7588 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -3308,3 +3308,16 @@ struct llama_model_kolibri1 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; + +struct llama_model_domyn_edge : public llama_model_base { + llama_model_domyn_edge(const struct llama_model_params & params) : llama_model_base(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + llama_rope_params get_rope_params(const llama_cparams & cparams, int il) const override; + + struct graph : public llm_graph_context { + graph(const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 310934e31725..295740c7cd3c 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -65,6 +65,8 @@ deepseek4 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAM deepseek41 ,0 ,any ,MUL+ADD , 12 deepseek41 ,0 ,any ,RMS_NORM+MUL , 29 deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6 +domynedge ,0 ,any ,RMS_NORM+MUL , 8 +domynedge ,0 ,any ,RMS_NORM+MUL+ADD , 3 dots1 ,0 ,any ,ADD+ADD , 1 dots1 ,0 ,any ,MUL+ADD , 2 dots1 ,0 ,any ,RMS_NORM+MUL , 9 diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index f10404e8c28a..90a32abc72cf 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -496,16 +496,22 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); } else if (arch == LLM_ARCH_COHERE2MOE || arch == LLM_ARCH_MIMO2 || arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_SPARK2_5 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_GRANITE_SWA || arch == LLM_ARCH_DOTS3NOTE || - arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE) { + arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE || arch == LLM_ARCH_DOMYN_EDGE) { std::vector pattern; pattern.reserve(n_layer); for (uint32_t il = 0; il < n_layer; il++) { pattern.push_back(il % 2); } ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); - if (arch == LLM_ARCH_FLINT) { + if (arch == LLM_ARCH_FLINT || arch == LLM_ARCH_DOMYN_EDGE) { ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, pattern); } + if (arch == LLM_ARCH_DOMYN_EDGE) { + // SWA (rope) layers use a smaller head dim than the full-attention (nope) layers + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_SWA, n_embd_head/2); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, n_embd_head/2); + ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT_SWA, n_embd_head/2); + } } else if (arch == LLM_ARCH_LFM3) { ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, std::vector({0, 0, 1})); ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); diff --git a/tests/test-tokenizer-random.py b/tests/test-tokenizer-random.py index 7f5ea3f45684..4b4fbdf75510 100644 --- a/tests/test-tokenizer-random.py +++ b/tests/test-tokenizer-random.py @@ -80,6 +80,7 @@ def __init__(self, libllama: LibLlama, path_model: str, mparams={}, cparams={}): raise RuntimeError("error: failed to load model '%s'" % path_model) if isinstance(cparams, dict): cparams = libllama.context_default_params(**cparams) + self.vocab = self.lib.llama_model_get_vocab(self.model) self.ctx = self.lib.llama_init_from_model(self.model, cparams) if not self.ctx: raise RuntimeError("error: failed to create context for model '%s'" % path_model) @@ -98,10 +99,10 @@ def free(self): def tokenize(self, text: str, add_special: bool = False, parse_special: bool = False) -> list[int]: encoded_text: bytes = text.encode("utf-8") - num = self.lib.llama_tokenize(self.model, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) + num = self.lib.llama_tokenize(self.vocab, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) while num < 0 and len(self.token_ids) < (16 << 20): self.token_ids = self.ffi.new("llama_token[]", -2 * num) - num = self.lib.llama_tokenize(self.model, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) + num = self.lib.llama_tokenize(self.vocab, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) return list(self.token_ids[0:num]) def detokenize(self, ids: list[int], remove_special: bool = False, unparse_special: bool = False) -> str: @@ -109,10 +110,10 @@ def detokenize(self, ids: list[int], remove_special: bool = False, unparse_speci self.token_ids = self.ffi.new("llama_token[]", 2 * len(ids)) for i, id in enumerate(ids): self.token_ids[i] = id - num = self.lib.llama_detokenize(self.model, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) + num = self.lib.llama_detokenize(self.vocab, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) while num < 0 and len(self.text_buff) < (16 << 20): self.text_buff = self.ffi.new("uint8_t[]", -2 * num) - num = self.lib.llama_detokenize(self.model, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) + num = self.lib.llama_detokenize(self.vocab, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) return str(self.ffi.buffer(self.text_buff, num), encoding="utf-8", errors="replace") # replace errors with '\uFFFD' # pyright: ignore[reportArgumentType] From 4c4a0f0a4246bc36a3724d12238d5624714dcb2f Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Fri, 20 Nov 2026 16:13:00 +0800 Subject: [PATCH 21/88] llama : reserve graph nodes for the MoE cache (#32636) The MoE cache adds a slot lookup to every MoE layer, and with --moe-cache-cpu-share a second expert path, but graph_max_nodes() did not account for it. Models on the default 8*n_tensors budget with few tensors per layer (cohere2moe: 443 tensors, 49 layers) overflow the graph context when the cache is combined with a quantized KV cache (K/V rotation), aborting in ggml_new_tensor with GGML_ASSERT(obj_new). Fixes #32584 Assisted-by: Claude Opus 5.5 --- src/llama-context.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 6252147a728a..7f1cc4c44cdf 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2949,6 +2949,12 @@ uint32_t llama_context::graph_max_nodes() const { } } + // the MoE cache adds a lookup to each MoE layer, and a second expert path with a CPU share (up to ~16 tensors per layer), + // which the per-tensor estimates above do not cover for models with few tensors per layer + if (cparams.moe_cache_size > 0) { + res += 32u*model.hparams.n_layer_all; + } + // every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling for (const auto & [seq_id, sampler] : sampling.samplers) { res += llama_sampler_backend_n_nodes(sampler) * cparams.n_outputs_max_per_seq; From 55b8d8d8980065eefb353b8d5ddff3caa077164d Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 20 Nov 2026 09:57:44 +0100 Subject: [PATCH 22/88] ui: full-screen diagram preview that zooms around what is on screen, inert diagrams (#32591) * ui: keep Pele diagrams inert Pele turns a node with `click ... href` into a live link, where Mermaid's strict security level left diagrams without links. Unwrap every link in Pele's output, keeping its children, so the inline block, the live-preview editor, the preview dialog and the downloaded svg stay inert. The Diagrams story's flowchart now carries click directives and its play test checks that no link or href is left. Assisted-by: Claude (Opus 5.5 Medium) * ui: open diagrams full screen, zoom around what is on screen The diagram preview dialog fills the window on every device. The preview places the diagram from its top left corner, so a zoom keeps a screen point fixed: the wheel and a trackpad pinch zoom around the pointer, the buttons and +/- keys around the middle of the screen, wherever the diagram has been panned to. Two-finger pinch, double-click and arrow keys work too. The diagram opens fitted and keeps fitting until panned or zoomed; Reset view fits it again. Adds MermaidPreview and DialogMermaidPreview stories with play tests and a unit test for the zoom math. Assisted-by: Claude (Opus 5.5 Medium) * ui: add a diagrams trace to the demo fixtures Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/demo/fixtures/traces.ts | 30 +++ .../MarkdownContent/markdown-diagrams.ts | 8 + .../app/content/MermaidPreview.svelte | 253 ++++++++++++++---- .../app/content/MermaidPreviewControls.svelte | 2 +- .../src/lib/components/app/content/index.ts | 16 +- .../app/dialogs/DialogMermaidPreview.svelte | 3 +- .../src/lib/components/app/dialogs/index.ts | 24 +- .../chat/src/lib/utils/diagram-viewport.ts | 75 ++++++ .../content/MarkdownContent.stories.svelte | 28 +- .../content/MermaidPreview.stories.svelte | 132 +++++++++ .../DialogMermaidPreview.stories.svelte | 41 +++ .../stories/fixtures/mermaid-diagrams.ts | 5 +- .../tests/stories/fixtures/mermaid-preview.ts | 30 +++ .../chat/tests/unit/diagram-viewport.test.ts | 111 ++++++++ 14 files changed, 672 insertions(+), 86 deletions(-) create mode 100644 ui/apps/chat/src/lib/utils/diagram-viewport.ts create mode 100644 ui/apps/chat/tests/stories/content/MermaidPreview.stories.svelte create mode 100644 ui/apps/chat/tests/stories/dialogs/DialogMermaidPreview.stories.svelte create mode 100644 ui/apps/chat/tests/stories/fixtures/mermaid-preview.ts create mode 100644 ui/apps/chat/tests/unit/diagram-viewport.test.ts diff --git a/ui/apps/chat/demo/fixtures/traces.ts b/ui/apps/chat/demo/fixtures/traces.ts index cc7ed8979a95..dc766458e478 100644 --- a/ui/apps/chat/demo/fixtures/traces.ts +++ b/ui/apps/chat/demo/fixtures/traces.ts @@ -301,9 +301,39 @@ function agenticDebugging(): Trace { return trace; } +/** A reply with a diagram, for diagram preview demos. */ +function diagrams(): Trace { + const trace = new Trace('How a request flows through llama-server'); + + trace.user('Can you draw how a chat request flows through llama-server?'); + trace.assistant( + [ + 'Here is the path a request takes:', + '', + '```mermaid', + 'flowchart LR', + ' U[Browser] -->|POST /v1/chat/completions| S(llama-server)', + ' S --> Q{Slot free?}', + ' Q -->|yes| P[Prompt processing]', + ' Q -->|no| W[Queue]', + ' W --> P', + ' P --> G[Sample token]', + ' G -->|more| G', + ' G -->|SSE tokens| U', + ' click S href "https://github.com/ggml-org/llama.cpp" "llama.cpp on GitHub" _blank', + '```', + '', + 'Requests wait in the queue until a slot is free, then tokens stream back as they are sampled.' + ].join('\n') + ); + + return trace; +} + /** Built-in traces, by name. */ export const DEMO_TRACES: Record Trace> = { 'agentic-debugging': agenticDebugging, + diagrams, 'long-chat': longChat }; diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts index ba607bfbce06..ec3e35dd9d5f 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts @@ -43,6 +43,13 @@ function diagramWidth(node: HTMLElement): number | undefined { return width > 0 ? width : undefined; } +// Pele wraps a node with a `click ... href` directive in a link. Diagrams come from model +// output, so they stay inert, as they were under Mermaid's strict security level: each link +// gives way to its children. The preview dialog and the downloaded file copy this svg. +function unwrapLinks(root: HTMLElement) { + for (const link of root.querySelectorAll('a')) link.replaceWith(...link.childNodes); +} + /** * Renders the mermaid diagrams in `container` that haven't been rendered yet, with Pele. * Marks nodes immediately to prevent duplicate renders during streaming. Colors come @@ -77,6 +84,7 @@ export async function renderMermaidDiagrams(container: HTMLElement) { }); node.innerHTML = svg; + unwrapLinks(node); } catch (error) { // the message quotes the diagram source, so it goes in as text const message = document.createElement('div'); diff --git a/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte b/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte index d981f67d1ed9..9348025817d7 100644 --- a/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte @@ -1,7 +1,16 @@ + + +
-
zoomBy(DIAGRAM_ZOOM_FACTOR)} + onZoomOut={() => zoomBy(1 / DIAGRAM_ZOOM_FACTOR)} + scale={view.scale} {svgHtml} />
diff --git a/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte b/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte index 1899db38907d..18f96c5294cc 100644 --- a/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte @@ -31,7 +31,7 @@
+ {/each} +
+ +
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte new file mode 100644 index 000000000000..fabc65c5425c --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte @@ -0,0 +1,34 @@ + + + +{#if reasoning.isOff} + + +{:else if reasoning.currentEffort !== ReasoningEffort.DEFAULT} + + + + Reasoning {REASONING_EFFORT_LABELS[reasoning.currentEffort]} + +{/if} diff --git a/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte b/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte index 4bfccbc91d7e..bc652d811dba 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte @@ -18,10 +18,18 @@ searchClass?: string; children: Snippet; /** - * Optional sticky footer: it sticks to the bottom of DropdownMenu.Content's own - * scrollport, which must stay the scroll container (overflow-y-auto + max-height). + * Optional footer. By default it sticks to the bottom of the parent's scrollport + * (overflow-y-auto + max-height), see `scrollport`. */ footer?: Snippet; + /** + * Scroll the header and the list in a box of their own, with the footer under it + * instead of sticking. For a parent that scales as it opens (a dropdown's zoom-in): + * WebKit pins a bottom-sticky element against the scaled box, so the footer would + * ride up the list until the animation ends. The parent is then a flex column that + * does not scroll itself (flex flex-col overflow-hidden + max-height). + */ + scrollport?: boolean; } let { @@ -34,6 +42,7 @@ onSearchChange, onSearchKeyDown, placeholder = 'Search...', + scrollport = false, searchClass = '', searchValue = $bindable('') }: Props = $props(); @@ -42,32 +51,42 @@ let stickyHeaderHeight = $state(0); -
- -
+{#snippet body()} +
+ +
+ +
+ +
+ {@render children()} -
- -
- {@render children()} + {#if isEmpty} +
{emptyMessage}
+ {/if} +
+
+{/snippet} - {#if isEmpty} -
{emptyMessage}
- {/if} +{#if scrollport} +
+ {@render body()}
-
+{:else} + {@render body()} +{/if} {#if footer} -
+
Date: Fri, 20 Nov 2026 17:19:14 +0800 Subject: [PATCH 24/88] llama : move the graph node budget into the model classes (#32648) graph_max_nodes() picked the nodes-per-tensor factor from lists of architectures. Each model class now gives it through a new virtual, llama_model::graph_nodes_per_tensor(), which defaults to 8. The architectures that need 32 or 64 override it in models.h, and DFlash keeps its hparams-based rule in dflash.cpp. LoRA adapter nodes are now added for every architecture, not only for the ones on the default factor. --- src/llama-context.cpp | 39 +++------------------------------------ src/llama-model.h | 3 +++ src/models/dflash.cpp | 14 ++++++++++++++ src/models/models.h | 21 +++++++++++++++++++++ 4 files changed, 41 insertions(+), 36 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 7f1cc4c44cdf..ea41283f99d2 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2911,42 +2911,9 @@ void llama_context::output_reorder() { // uint32_t llama_context::graph_max_nodes() const { - uint32_t res; - if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || - model.arch == LLM_ARCH_HRM_TEXT) { - res = std::max(1024u, 64u * model.n_tensors()); - } else if (model.arch == LLM_ARCH_QWEN3NEXT || - model.arch == LLM_ARCH_KIMI_LINEAR || - model.arch == LLM_ARCH_METIS16 || - model.arch == LLM_ARCH_BAILINGMOE3 || - model.arch == LLM_ARCH_QWEN35 || - model.arch == LLM_ARCH_QWEN35MOE || - model.arch == LLM_ARCH_ZONOS3 || - model.arch == LLM_ARCH_CLEF || - model.arch == LLM_ARCH_CLOVER_MOE || - model.arch == LLM_ARCH_QWEN4EXP || - model.arch == LLM_ARCH_DEEPSEEK4 || - model.arch == LLM_ARCH_DEEPSEEK41 || - model.arch == LLM_ARCH_XING4_0 || - (model.arch == LLM_ARCH_DFLASH && model.hparams.dsv4_hc_mult > 0) || - model.arch == LLM_ARCH_NANBEIGE || - model.arch == LLM_ARCH_MINIMAX_01 || - model.arch == LLM_ARCH_MINIMAX_M3 || - model.arch == LLM_ARCH_HY_V4 || - model.arch == LLM_ARCH_INKLING2) { - res = std::max(1024u, 32u * model.n_tensors()); - } else if (model.arch == LLM_ARCH_DFLASH && model.hparams.dflash_selector_rank > 0) { - // DFlash2's convolutions and selector are shape work rather than matmuls, - // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft. - // The selector lattice scales with the draft block size; 12u was calibrated - // on block-8 drafters, so scale the budget for larger blocks (e.g. Ripple's 16). - const uint32_t block_scale = std::max(1u, model.hparams.dflash_block_size/8u); - res = std::max(1024u, 12u*block_scale*model.n_tensors()); - } else { - res = std::max(1024u, 8u*model.n_tensors()); - for (const auto & lora : model.loras) { - res += lora->get_n_nodes(); - } + uint32_t res = std::max(1024u, model.graph_nodes_per_tensor()*model.n_tensors()); + for (const auto & lora : model.loras) { + res += lora->get_n_nodes(); } // the MoE cache adds a lookup to each MoE layer, and a second expert path with a CPU share (up to ~16 tensors per layer), diff --git a/src/llama-model.h b/src/llama-model.h index 8d2f5629efae..1cc5d743a781 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -1052,6 +1052,9 @@ struct llama_model { llama_memory_i * create_memory(const llama_memory_params & params, const llama_cparams & cparams) const; + // graph size budget: max graph nodes per model tensor + virtual uint32_t graph_nodes_per_tensor() const { return 8; } + ggml_cgraph * build_graph(const llm_graph_params & params) const; virtual void load_stats (llama_model_loader & ml) = 0; diff --git a/src/models/dflash.cpp b/src/models/dflash.cpp index 000222f4c0d1..98a8d1d9acec 100644 --- a/src/models/dflash.cpp +++ b/src/models/dflash.cpp @@ -125,6 +125,20 @@ void llama_model_dflash::load_arch_tensors(llama_model_loader &) { } } +uint32_t llama_model_dflash::graph_nodes_per_tensor() const { + if (hparams.dsv4_hc_mult > 0) { + return 32; + } + if (hparams.dflash_selector_rank > 0) { + // DFlash2's convolutions and selector are shape work rather than matmuls, + // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft. + // The selector lattice scales with the draft block size; 12u was calibrated + // on block-8 drafters, so scale the budget for larger blocks (e.g. Ripple's 16). + return 12u*std::max(1u, hparams.dflash_block_size/8u); + } + return llama_model_base::graph_nodes_per_tensor(); +} + void llama_model_dflash::load_tensors_layers_base() { LLAMA_LOAD_LOCALS; diff --git a/src/models/models.h b/src/models/models.h index e0a4db5f7588..979ceffc271b 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -442,6 +442,7 @@ struct llama_model_nanbeige : public llama_model_base { llama_model_nanbeige(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } int n_loops = 1; int n_layer_phys = 0; @@ -801,6 +802,7 @@ struct llama_model_zonos3 : public llama_model_base { llama_model_zonos3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -1282,6 +1284,7 @@ struct llama_model_deepseek4 : public llama_model_base { llama_model_deepseek4(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { struct no_build {}; @@ -1439,6 +1442,7 @@ struct llama_model_xing4_0 : public llama_model_base { llama_model_xing4_0(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { graph(const llama_model & model, const llm_graph_params & params); @@ -1571,6 +1575,7 @@ struct llama_model_dflash : public llama_model_base { llama_model_dflash(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override; enum variant_type { VARIANT_DFLASH, @@ -1833,6 +1838,7 @@ struct llama_model_metis16 : public llama_model_base { llama_model_metis16(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } uint32_t n_pass = 1; uint32_t n_stream = 1; @@ -2134,6 +2140,7 @@ struct llama_model_hrm_text : public llama_model_base { llama_model_hrm_text(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2176,6 +2183,7 @@ struct llama_model_bailingmoe3 : public llama_model_base { llama_model_bailingmoe3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2346,6 +2354,7 @@ struct llama_model_hy_v4 : public llama_model_base { llama_model_hy_v4(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2475,6 +2484,7 @@ struct llama_model_inkling2 : public llama_model_base { llama_model_inkling2(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2599,6 +2609,7 @@ struct llama_model_minimax_01 : public llama_model_base { llama_model_minimax_01(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2629,6 +2640,7 @@ struct llama_model_minimax_m3 : public llama_model_base { llama_model_minimax_m3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } msa_params msa_p; struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2673,6 +2685,7 @@ struct llama_model_qwen3next : public llama_model_base { llama_model_qwen3next(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2715,6 +2728,7 @@ struct llama_model_qwen35 : public llama_model_base { llama_model_qwen35(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2851,6 +2865,7 @@ struct llama_model_qwen4exp : public llama_model_base { void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2965,6 +2980,7 @@ struct llama_model_qwen35moe : public llama_model_base { llama_model_qwen35moe(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3007,6 +3023,7 @@ struct llama_model_clover_moe : public llama_model_base { llama_model_clover_moe(const llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3055,6 +3072,7 @@ struct llama_model_kimi_k3 : public llama_model_base { llama_model_kimi_k3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3095,6 +3113,7 @@ struct llama_model_kimi_k31 : public llama_model_base { llama_model_kimi_k31(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3141,6 +3160,7 @@ struct llama_model_glm5_next : public llama_model_base { llama_model_glm5_next(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } // k-pool indexer inputs on top of the generic hybrid input class llm_graph_input_kpool; @@ -3225,6 +3245,7 @@ struct llama_model_kimi_linear : public llama_model_base { llama_model_kimi_linear(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); From 9d6f04fa99936708b9df140b7b2df62a8925afd5 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 20 Nov 2026 10:33:34 +0100 Subject: [PATCH 25/88] ui: show vision as glasses and audio as headphones (#32617) The model modality icons match the ones the Llama apps use: glasses for vision, headphones for audio. The attach menu's list of what the model takes reads the same icons instead of its own microphone and picture. Assisted-by: Claude (Opus 5.5 Medium) --- .../ChatFormActionAddDrawer.svelte | 19 +++++++++---------- .../ChatFormActionAddDropdown.svelte | 16 +++++++++------- ui/lib/ui/src/lib/models/constants.ts | 4 ++-- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte index b777b7c00117..55e87129efc7 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte @@ -8,24 +8,23 @@ ChevronRight, File, Folder, - Image, MessageSquare, - Mic, - PencilRuler, - Video + PencilRuler } from '@lucide/svelte'; import { ATTACHMENT_FILE_ITEMS, ATTACHMENT_MENU_TEXT, ATTACHMENT_MODALITY_TEXT, - ICON_CLASS_DEFAULT + ICON_CLASS_DEFAULT, + MODALITY_ICONS } from '#lib/constants/index.ts'; import { getChatFormActionsContext } from '#lib/contexts/index.ts'; import { AttachmentAction, AttachmentItemEnabledWhen } from '#lib/enums/attachment.enums.ts'; + import { ModelModality } from '#lib/enums/index.ts'; import { useAttachmentMenu } from '#lib/hooks/use-attachment-menu.svelte.ts'; import { useToolsPanel } from '#lib/hooks/use-tools-panel.svelte.ts'; import type { ToolGroup } from '#lib/types/index.ts'; - import type { Snippet } from 'svelte'; + import type { Component, Snippet } from 'svelte'; interface Props { class?: string; @@ -54,17 +53,17 @@ } ); - const FILE_MODALITY_ICONS: Record = { + const FILE_MODALITY_ICONS: Record = { [AttachmentItemEnabledWhen.HAS_AUDIO_MODALITY]: { - icon: Mic, + icon: MODALITY_ICONS[ModelModality.AUDIO], label: ATTACHMENT_MODALITY_TEXT[AttachmentItemEnabledWhen.HAS_AUDIO_MODALITY] }, [AttachmentItemEnabledWhen.HAS_VIDEO_MODALITY]: { - icon: Video, + icon: MODALITY_ICONS[ModelModality.VIDEO], label: ATTACHMENT_MODALITY_TEXT[AttachmentItemEnabledWhen.HAS_VIDEO_MODALITY] }, [AttachmentItemEnabledWhen.HAS_VISION_MODALITY]: { - icon: Image, + icon: MODALITY_ICONS[ModelModality.VISION], label: ATTACHMENT_MODALITY_TEXT[AttachmentItemEnabledWhen.HAS_VISION_MODALITY] } }; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte index 77d10bd9e0ae..b4e6aa821398 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte @@ -3,18 +3,20 @@ import * as DropdownMenu from '@ggml-org/llama-ui/ui/dropdown-menu'; import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip'; import { cn } from '@ggml-org/llama-ui/utils'; - import { File, Folder, Image, MessageSquare, Mic, Plus, Video } from '@lucide/svelte'; + import { File, Folder, MessageSquare, Plus } from '@lucide/svelte'; import { ChatFormActionAddToolsSubmenu } from '#lib/components/app/index.ts'; import { ATTACHMENT_FILE_ITEMS, ATTACHMENT_MENU_TEXT, ATTACHMENT_MODALITY_TEXT, ATTACHMENT_TOOLTIP_TEXT, - ICON_CLASS_DEFAULT + ICON_CLASS_DEFAULT, + MODALITY_ICONS } from '#lib/constants/index.ts'; import { getChatFormActionsContext } from '#lib/contexts/index.ts'; - import { AttachmentAction, AttachmentItemEnabledWhen } from '#lib/enums/index.ts'; + import { AttachmentAction, AttachmentItemEnabledWhen, ModelModality } from '#lib/enums/index.ts'; import { useAttachmentMenu } from '#lib/hooks/use-attachment-menu.svelte.ts'; + import type { Component } from 'svelte'; interface Props { class?: string; @@ -44,17 +46,17 @@ } ); - const FILE_MODALITY_ICONS: Record = { + const FILE_MODALITY_ICONS: Record = { [AttachmentItemEnabledWhen.HAS_AUDIO_MODALITY]: { - icon: Mic, + icon: MODALITY_ICONS[ModelModality.AUDIO], label: ATTACHMENT_MODALITY_TEXT[AttachmentItemEnabledWhen.HAS_AUDIO_MODALITY] }, [AttachmentItemEnabledWhen.HAS_VIDEO_MODALITY]: { - icon: Video, + icon: MODALITY_ICONS[ModelModality.VIDEO], label: ATTACHMENT_MODALITY_TEXT[AttachmentItemEnabledWhen.HAS_VIDEO_MODALITY] }, [AttachmentItemEnabledWhen.HAS_VISION_MODALITY]: { - icon: Image, + icon: MODALITY_ICONS[ModelModality.VISION], label: ATTACHMENT_MODALITY_TEXT[AttachmentItemEnabledWhen.HAS_VISION_MODALITY] } }; diff --git a/ui/lib/ui/src/lib/models/constants.ts b/ui/lib/ui/src/lib/models/constants.ts index ebfbf84ae727..9fff8ca1065e 100644 --- a/ui/lib/ui/src/lib/models/constants.ts +++ b/ui/lib/ui/src/lib/models/constants.ts @@ -2,9 +2,9 @@ // models-discover-download and model-compatibility). import { ModelCapability, ModelModality } from './enums.js'; import type { ModelModalities } from './types.js'; -import VisionIcon from '@lucide/svelte/icons/eye'; +import VisionIcon from '@lucide/svelte/icons/glasses'; import ReasoningIcon from '@lucide/svelte/icons/lightbulb'; -import AudioIcon from '@lucide/svelte/icons/mic'; +import AudioIcon from '@lucide/svelte/icons/headphones'; import VideoIcon from '@lucide/svelte/icons/video'; import ToolUseIcon from '@lucide/svelte/icons/wrench'; import type { Component } from 'svelte'; From b81aa847c288e0f7d2c72ea1871b828f1afccde1 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 20 Nov 2026 11:26:26 +0100 Subject: [PATCH 26/88] ui: slim the design tokens and set all text through type roles (#32615) * ui: drop component tokens that only alias a semantic token A component token now exists only for what a component decides itself: a value no semantic token has, or one that only this component changes between themes. Components that take a semantic token as it is read it directly, so 88 of the 118 component tokens go, with no change to what is drawn. Also drops semantic tokens that repeat another one (status-* is fill-*, elevation-tooltip is elevation-surface), the unused info lamp tokens and 14 primitives nothing reads, and adds fg-soft for the label of an option that is not the picked one (tabs, toggle group). Assisted-by: Claude (Opus 5.5 Medium) * ui: add a short summary on top of DESIGN.md The rules most changes need, in one screen: components, colour, type, shape, sizes, surfaces, tokens and no arbitrary values. The sections below keep the detail. Assisted-by: Claude (Opus 5.5 Medium) * ui: derive design tokens by rule and drop the alias layers Semantic tokens are either a pick (a primitive per theme) or a derivation, mixed from another semantic token by a fixed rule and declared once: hover fills, status surfaces and lines, dark shadows (--elevation-strength), the middle of a matte edge, a lamp's rim and glyph. Primitives keep colours only. shadcn's colour names stay as Tailwind utilities and no longer exist as variables; neutral semantic utilities that duplicated them are gone. Assisted-by: Claude (Opus 5.5 Medium) * ui: set all text through type roles and move off-scale values onto the scale Tailwind's text sizes and bracketed sizes become the type roles, with a new text-caption-sm (10px) for tags and counts. Body and caption roles no longer set a weight, and line heights are written as Tailwind writes its own, so the swap from text-sm and text-xs changes no pixel. A unit test keeps old sizes from coming back. Arbitrary values with a scale equivalent use it (z-20, max-w-4/5, min-w-32), and the two easing curves repeated across the app are ease-out-quint and ease-sheet. DESIGN.md is updated and regenerated. Assisted-by: Claude (Opus 5.5 Medium) * ui: bump @ggml-org/llama-ui to 0.5.0 Removed and renamed tokens are breaking for an app that reads them. Assisted-by: Claude (Opus 5.5 Medium) * ui: add a display type role for the biggest headline The greeting on a new chat keeps its 30px from md up, now as text-display instead of a Tailwind size. Assisted-by: Claude (Opus 5.5 Medium) * ui: one corner scale, one set of shadows and three more derived tokens Six corner roles named values Tailwind's rounded-md to rounded-4xl already have, and components used the Tailwind names nine times out of ten. The roles are gone; the whole scale is computed from --radius. Tailwind's shadow sizes were restated next to the elevation tokens and did not follow the theme, so they were five times fainter in dark. The five uses take elevation tokens and a unit test keeps both from coming back. A button group's seam is the button's own text colour at 25%, the dark status text is the dark status fill, and the pressed shadow scales with --elevation-strength like the inset one. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/DESIGN.md | 385 +++++++++--------- ui/apps/chat/scripts/design-md.js | 49 ++- ui/apps/chat/src/app.css | 60 ++- .../app/badges/BadgesModality.svelte | 2 +- .../ChatAttachmentsListItem.svelte | 2 +- .../ChatAttachmentsListItemMcpResource.svelte | 6 +- ...hatAttachmentsListItemThumbnailFile.svelte | 12 +- ...atAttachmentsListItemThumbnailImage.svelte | 2 +- ...tAttachmentsPreviewCurrentItemAudio.svelte | 2 +- ...hatAttachmentsPreviewCurrentItemPdf.svelte | 4 +- ...tAttachmentsPreviewCurrentItemVideo.svelte | 2 +- .../ChatAttachmentsPreviewFileInfo.svelte | 4 +- ...hatAttachmentsPreviewThumbnailStrip.svelte | 4 +- .../app/chat/ChatForm/ChatForm.svelte | 8 +- .../ChatFormActionAddButton.svelte | 2 +- .../ChatFormActionAddDrawer.svelte | 8 +- .../ChatFormActionAddDropdown.svelte | 2 +- .../ChatFormActionAddToolsSubmenu.svelte | 22 +- .../ChatFormActionReasoning.svelte | 10 +- .../ContextGaugeDetailRow.svelte | 2 +- .../ContextGaugeDetails.svelte | 8 +- .../ContextGaugeLoadModel.svelte | 8 +- .../ContextGaugePopup.svelte | 6 +- .../ChatFormCurrentWorkingDirectory.svelte | 14 +- ...ChatFormCurrentWorkingDirectoryChip.svelte | 2 +- ...mCurrentWorkingDirectoryResultsList.svelte | 8 +- .../ChatFormPickerItemHeader.svelte | 4 +- .../ChatFormPicker/ChatFormPickerList.svelte | 2 +- .../ChatFormPickerCommand.svelte | 4 +- .../ChatFormPromptPickerArgumentForm.svelte | 2 +- .../ChatFormPromptPickerArgumentInput.svelte | 4 +- .../ChatFormPickerMention.svelte | 8 +- .../ChatMessageAssistant.svelte | 2 +- .../ChatMessageAssistantProcessingInfo.svelte | 2 +- .../ChatMessageAssistantRawOutput.svelte | 4 +- .../ChatMessage/ChatMessageCwdChange.svelte | 6 +- .../ChatMessageMcpPrompt.svelte | 4 +- .../ChatMessageMcpPromptContent.svelte | 12 +- .../ChatMessage/ChatMessageSynthetic.svelte | 2 +- .../ChatMessageSystem.svelte | 16 +- .../ChatMessageToolCallBlockDefault.svelte | 20 +- .../ChatMessageToolCallBlockEditFile.svelte | 24 +- ...essageToolCallBlockExecShellCommand.svelte | 14 +- ...tMessageToolCallBlockFileGlobSearch.svelte | 12 +- ...ChatMessageToolCallBlockGetDatetime.svelte | 12 +- .../ChatMessageToolCallBlockGetInfo.svelte | 12 +- .../ChatMessageToolCallBlockGrepSearch.svelte | 12 +- .../ChatMessageToolCallBlockReadFile.svelte | 2 +- .../ChatMessageToolCallBlockReadMedia.svelte | 8 +- ...atMessageToolCallBlockRunJavascript.svelte | 12 +- ...atMessageToolCallBlockSearchResults.svelte | 14 +- .../ChatMessageToolCallBlockWriteFile.svelte | 12 +- .../ChatMessageUser/ChatMessageUser.svelte | 6 +- .../ChatMessageUserBubble.svelte | 4 +- .../ChatMessageUserPending.svelte | 2 +- .../ChatMessageActionCard.svelte | 2 +- ...tMessageActionCardPermissionRequest.svelte | 2 +- .../ChatMessageActionIcons.svelte | 4 +- ...MessageActionIconsBranchingControls.svelte | 4 +- .../ChatMessageAgenticContent.svelte | 2 +- .../ChatMessages/ChatMessageEditForm.svelte | 10 +- .../ChatMessageReasoningBlock.svelte | 2 +- .../ChatMessageStatistics.svelte | 8 +- .../app/chat/ChatMessages/ChatMessages.svelte | 4 +- .../ChatScreen/ChatScreenDragOverlay.svelte | 4 +- .../chat/ChatScreen/ChatScreenGreeting.svelte | 6 +- .../ChatScreen/ChatScreenMobileHeader.svelte | 4 +- .../ChatScreen/ChatScreenServerError.svelte | 4 +- .../ChatScreenStreamResumeStatus.svelte | 2 +- .../app/chat/ChatTabs/ChatTabs.svelte | 4 +- .../content/CollapsibleContentBlock.svelte | 6 +- .../content/CollapsibleTerminalBlock.svelte | 6 +- .../MarkdownContent/markdown-content.css | 86 ++-- .../MarkdownEditor/MarkdownEditor.svelte | 16 +- .../app/content/MermaidPreviewControls.svelte | 2 +- .../DialogChatAttachmentsPreview.svelte | 2 +- .../app/dialogs/DialogChatError.svelte | 4 +- .../dialogs/DialogConversationRename.svelte | 2 +- .../app/dialogs/DialogEmptyFileAlert.svelte | 4 +- .../app/dialogs/DialogExportSettings.svelte | 2 +- .../app/dialogs/DialogFileUploadError.svelte | 16 +- .../app/dialogs/DialogGroupPicker.svelte | 6 +- .../dialogs/DialogMcpResourcePreview.svelte | 10 +- .../dialogs/DialogMcpResourcesBrowser.svelte | 14 +- .../app/dialogs/DialogMcpServerAddNew.svelte | 2 +- .../dialogs/DialogModelNotAvailable.svelte | 8 +- .../app/dialogs/DialogSearch.svelte | 14 +- .../app/forms/InputWithSuggestions.svelte | 4 +- .../components/app/forms/KeyValuePairs.svelte | 8 +- .../app/mcp/McpActiveServersAvatars.svelte | 2 +- .../app/mcp/McpCapabilitiesBadges.svelte | 18 +- .../app/mcp/McpConnectionLogs.svelte | 10 +- .../app/mcp/McpResourcePreview.svelte | 22 +- .../app/mcp/McpResourceTemplateForm.svelte | 4 +- .../McpResourcesBrowserEmptyState.svelte | 2 +- .../McpResourcesBrowserHeader.svelte | 2 +- .../McpResourcesBrowserServerItem.svelte | 20 +- .../mcp/McpServerCard/McpServerCard.svelte | 6 +- .../McpServerCard/McpServerCardCompact.svelte | 2 +- .../McpServerCard/McpServerCardHeader.svelte | 2 +- .../McpServerCardToolsList.svelte | 4 +- .../components/app/mcp/McpServerForm.svelte | 14 +- .../app/mcp/McpServerIdentity.svelte | 2 +- .../components/app/mcp/McpServerInfo.svelte | 4 +- .../app/misc/CollapsibleSection.svelte | 2 +- .../app/misc/ConversationSelection.svelte | 12 +- .../components/app/misc/TruncatedText.svelte | 2 +- .../components/app/models/ModelContext.svelte | 2 +- .../app/models/ModelDraftSubline.svelte | 8 +- .../app/models/ModelLoadControl.svelte | 4 +- .../ModelsManagerDownloadControl.svelte | 2 +- .../ModelsManagerModelConfiguration.svelte | 6 +- ...delsManagerModelConfigurationHeader.svelte | 2 +- ...anagerModelConfigurationInformation.svelte | 22 +- .../ModelsManagerModelDrawer.svelte | 2 +- .../ModelsManagerModelRow.svelte | 2 +- .../ModelsManagerModelsTable.svelte | 11 +- .../ModelsManagerQuantRow.svelte | 4 +- .../ModelsManager/ModelsManagerRepoRow.svelte | 2 +- .../ModelsManagerStatusCell.svelte | 2 +- .../app/models/ModelsSection.svelte | 4 +- .../ModelsSelector/ModelsSelector.svelte | 20 +- .../ModelsSelectorDownloadItem.svelte | 12 +- .../ModelsSelectorDropdown.svelte | 10 +- .../ModelsSelector/ModelsSelectorList.svelte | 6 +- .../ModelsSelectorOption.svelte | 2 +- .../ModelsSelectorReasoning.svelte | 8 +- .../app/models/discover/ModelsDiscover.svelte | 4 +- .../ModelsDiscoverChatTemplateDialog.svelte | 4 +- .../ModelsDiscoverDetails.svelte | 2 +- ...odelsDiscoverDetailsDownloadOptions.svelte | 6 +- ...tailsDownloadOptionsDownloadCommand.svelte | 6 +- ...sDownloadOptionsDraftDownloadButton.svelte | 4 +- ...sDownloadOptionsQuantDownloadButton.svelte | 24 +- ...lsDiscoverDetailsDownloadOptionsRow.svelte | 6 +- .../ModelsDiscoverDetailsHeader.svelte | 6 +- .../ModelsDiscoverDetailsHfHubStats.svelte | 2 +- .../ModelsDiscoverDetailsMetadata.svelte | 6 +- .../ModelsDiscoverDetailsMetadataItem.svelte | 2 +- .../ModelsDiscoverListItem.svelte | 2 +- .../app/navigation/ContextMenuActions.svelte | 2 +- .../app/navigation/DropdownMenuActions.svelte | 10 +- .../navigation/DropdownMenuSearchable.svelte | 2 +- .../app/navigation/MenuActionsList.svelte | 2 +- .../SidebarNavigation.svelte | 6 +- .../SidebarNavigationActions.svelte | 2 +- .../SidebarNavigationConversationItem.svelte | 4 +- .../SidebarNavigationConversationList.svelte | 4 +- .../SidebarNavigationGroupSection.svelte | 2 +- .../SidebarNavigationGroupSubmenu.svelte | 11 +- .../SidebarNavigationSearchResults.svelte | 6 +- .../SidebarNavigationSectionHeading.svelte | 2 +- .../SidebarNavigationSelectionBar.svelte | 2 +- .../SidebarNavigationShowMore.svelte | 2 +- .../app/servers/ServerErrorSplash.svelte | 18 +- .../app/servers/ServerLoadingSplash.svelte | 4 +- .../app/servers/ServerStatus.svelte | 6 +- .../settings/SettingsChat/SettingsChat.svelte | 4 +- .../SettingsChat/SettingsChatFields.svelte | 26 +- .../SettingsChatImportExportSection.svelte | 8 +- ...ettingsChatParameterSourceIndicator.svelte | 2 +- .../SettingsChat/SettingsChatToolsTab.svelte | 14 +- .../SettingsChatDesktopSidebar.svelte | 2 +- .../settings/SettingsChatMobileHeader.svelte | 2 +- .../app/settings/SettingsGroup.svelte | 2 +- .../lib/components/pwa/PwaRefreshAlert.svelte | 6 +- .../lib/constants/css-classes.constants.ts | 6 +- .../lib/constants/mention-badge.constants.ts | 2 +- .../lib/constants/models-manager.constants.ts | 2 +- ui/apps/chat/src/routes/+error.svelte | 2 +- ui/apps/chat/src/routes/+layout.svelte | 14 +- .../chat/src/routes/mcp-servers/+page.svelte | 4 +- ui/apps/chat/src/routes/models/+page.svelte | 6 +- ui/apps/chat/src/routes/settings/+page.svelte | 8 +- ui/apps/chat/tests/debug/ViewportProbe.svelte | 2 +- .../stories/actions/GlassKey.stories.svelte | 2 +- .../stories/brand/assets/OpticalCentre.svelte | 10 +- .../CollapsibleTerminalBlock.stories.svelte | 2 +- .../foundations/SafeAreas.stories.svelte | 12 +- .../stories/introduction/Principles.svelte | 16 +- .../stories/introduction/Products.svelte | 14 +- .../stories/introduction/Sections.svelte | 6 +- .../tests/stories/introduction/Stack.svelte | 10 +- .../tests/stories/introduction/Uses.svelte | 4 +- .../misc/CollapsibleSection.stories.svelte | 2 +- .../misc/ScrollCarousel.stories.svelte | 2 +- ui/apps/chat/tests/unit/token-roles.test.ts | 56 +++ ui/lib/ui/.storybook/docs.css | 18 +- ui/lib/ui/package-lock.json | 4 +- ui/lib/ui/package.json | 2 +- .../app/content/SyntaxHighlightedCode.svelte | 8 +- .../models/ModelCapabilityIcons.svelte | 4 +- .../lib/components/models/ModelCard.svelte | 2 +- .../src/lib/components/models/ModelId.svelte | 4 +- .../models/ModelMetadataItem.svelte | 2 +- .../components/models/ModelOrgAvatar.svelte | 4 +- .../components/models/ModelQuantChip.svelte | 22 +- .../models/ModelQuantOptions.svelte | 4 +- .../components/models/ModelQuantRow.svelte | 8 +- .../alert-dialog/alert-dialog-content.svelte | 4 +- .../alert-dialog-description.svelte | 2 +- .../alert-dialog/alert-dialog-overlay.svelte | 2 +- .../ui/alert-dialog/alert-dialog-title.svelte | 2 +- .../ui/alert/alert-description.svelte | 2 +- .../src/lib/components/ui/alert/alert.svelte | 2 +- .../src/lib/components/ui/badge/badge.svelte | 11 +- .../ui/button-group/button-group-root.svelte | 6 +- .../lib/components/ui/button/button.svelte | 18 +- .../ui/button/button.svelte.spec.ts | 2 +- .../ui/card/card-description.svelte | 2 +- .../ui/src/lib/components/ui/card/card.svelte | 2 +- .../components/ui/checkbox/checkbox.svelte | 2 +- .../context-menu/context-menu-content.svelte | 2 +- .../ui/context-menu/context-menu-item.svelte | 2 +- .../ui/context-menu/context-menu-label.svelte | 2 +- .../context-menu/context-menu-shortcut.svelte | 2 +- .../context-menu-sub-content.svelte | 2 +- .../context-menu-sub-trigger.svelte | 2 +- .../ui/dialog/dialog-content.svelte | 2 +- .../ui/dialog/dialog-description.svelte | 2 +- .../ui/dialog/dialog-overlay.svelte | 2 +- .../components/ui/dialog/dialog-title.svelte | 2 +- .../ui/drawer/drawer-content.svelte | 4 +- .../ui/drawer/drawer-description.svelte | 2 +- .../components/ui/drawer/drawer-title.svelte | 2 +- .../dropdown-menu-checkbox-item.svelte | 2 +- .../dropdown-menu-content.svelte | 2 +- .../dropdown-menu-group-heading.svelte | 2 +- .../dropdown-menu/dropdown-menu-item.svelte | 2 +- .../dropdown-menu/dropdown-menu-label.svelte | 2 +- .../dropdown-menu-radio-item.svelte | 2 +- .../dropdown-menu-shortcut.svelte | 2 +- .../dropdown-menu-sub-content.svelte | 2 +- .../dropdown-menu-sub-trigger.svelte | 2 +- .../components/ui/empty/empty-content.svelte | 2 +- .../ui/empty/empty-description.svelte | 2 +- .../components/ui/empty/empty-title.svelte | 2 +- .../ui/hover-card/hover-card-content.svelte | 2 +- .../src/lib/components/ui/input/input.svelte | 12 +- .../src/lib/components/ui/label/label.svelte | 2 +- .../ui/select/select-content.svelte | 2 +- .../ui/select/select-group-heading.svelte | 2 +- .../components/ui/select/select-item.svelte | 2 +- .../components/ui/select/select-label.svelte | 2 +- .../ui/select/select-trigger.svelte | 6 +- .../lib/components/ui/switch/switch.svelte | 4 +- .../components/ui/table/table-caption.svelte | 2 +- .../src/lib/components/ui/table/table.svelte | 2 +- .../lib/components/ui/tabs/tabs-list.svelte | 8 +- .../components/ui/tabs/tabs-trigger.svelte | 4 +- .../components/ui/textarea/textarea.svelte | 2 +- .../ui/toggle-group/toggle-group-item.svelte | 8 +- .../ui/toggle-group/toggle-group.svelte | 2 +- .../lib/components/ui/toggle/toggle.svelte | 9 +- .../ui/tooltip/tooltip-content.svelte | 4 +- ui/lib/ui/src/lib/components/ui/utils.ts | 8 +- .../lib/constants/css-classes.constants.ts | 2 +- ui/lib/ui/src/lib/models/constants.ts | 8 +- ui/lib/ui/src/lib/styles/surfaces.css | 99 ++--- ui/lib/ui/src/lib/styles/theme.css | 72 ++-- .../ui/src/lib/styles/tokens/components.css | 151 ++----- .../ui/src/lib/styles/tokens/primitives.css | 62 +-- ui/lib/ui/src/lib/styles/tokens/semantic.css | 293 ++++++------- .../components/display/Card.stories.svelte | 2 +- .../display/Collapsible.stories.svelte | 8 +- .../display/ScrollArea.stories.svelte | 4 +- .../display/Separator.stories.svelte | 2 +- .../components/navigation/Tabs.stories.svelte | 6 +- .../components/overlays/Drawer.stories.svelte | 2 +- .../overlays/HoverCard.stories.svelte | 6 +- .../overlays/Popover.stories.svelte | 2 +- .../overlays/Submenus.stories.svelte | 2 +- .../stories/foundations/Colors.stories.svelte | 6 +- .../foundations/Elevation.stories.svelte | 7 +- .../stories/foundations/Shapes.stories.svelte | 15 +- .../stories/foundations/Sizing.stories.svelte | 14 +- .../foundations/Surfaces.stories.svelte | 10 +- .../stories/foundations/TokenTier.svelte | 16 +- .../foundations/Typography.stories.svelte | 25 +- .../tests/stories/helpers/StateGallery.svelte | 2 +- .../stories/helpers/StateGalleryItem.svelte | 2 +- .../stories/mockups/AppMockups.stories.svelte | 2 +- .../stories/models/ModelCard.stories.svelte | 2 +- .../models/ModelQuantChip.stories.svelte | 2 +- 284 files changed, 1402 insertions(+), 1510 deletions(-) create mode 100644 ui/apps/chat/tests/unit/token-roles.test.ts diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index 971685e1bc51..f3a1eaf9896c 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -38,35 +38,21 @@ colors: art-night-sky: 'oklch(0.33 0.07 256)' art-cinder: 'oklch(0.68 0.18 46)' art-cinder-light: 'oklch(0.85 0.065 46)' - cool-gray-50: 'oklch(0.958 0.002 250)' cool-gray-100: 'oklch(0.938 0.004 250)' cool-gray-200: 'oklch(0.91 0.005 250)' - cool-gray-300: 'oklch(0.86 0.007 250)' cool-gray-400: 'oklch(0.81 0.01 250)' - red-400: 'oklch(0.69 0.2 27)' red-450: 'oklch(0.635 0.229 28)' - red-500: 'oklch(0.6 0.235 27)' red-550: 'oklch(0.588 0.236 28)' red-600: 'oklch(0.55 0.22 27)' - red-800: 'oklch(0.43 0.17 27)' - yellow-300: 'oklch(0.9 0.14 84)' - yellow-400: 'oklch(0.85 0.17 84)' - yellow-800: 'oklch(0.5 0.1 84)' - green-400: 'oklch(0.81 0.16 148)' green-450: 'oklch(0.756 0.197 147)' - green-500: 'oklch(0.73 0.2 148)' green-550: 'oklch(0.669 0.197 147)' green-650: 'oklch(0.52 0.17 147)' - green-800: 'oklch(0.45 0.14 148)' amber-250: 'oklch(0.842 0.165 84)' amber-400: 'oklch(0.752 0.157 78)' amber-650: 'oklch(0.547 0.116 74)' - blue-400: 'oklch(0.7 0.163 255)' blue-450: 'oklch(0.67 0.173 256)' - blue-500: 'oklch(0.62 0.15 255)' blue-550: 'oklch(0.587 0.177 256)' blue-650: 'oklch(0.535 0.177 256)' - blue-800: 'oklch(0.42 0.11 255)' white-a2: 'oklch(1 0 0 / 0.02)' white-a4: 'oklch(1 0 0 / 0.04)' white-a6: 'oklch(1 0 0 / 0.06)' @@ -75,7 +61,6 @@ colors: white-a18: 'oklch(1 0 0 / 0.18)' white-a20: 'oklch(1 0 0 / 0.2)' white-a30: 'oklch(1 0 0 / 0.3)' - white-a40: 'oklch(1 0 0 / 0.4)' white-a50: 'oklch(1 0 0 / 0.5)' white-a85: 'oklch(1 0 0 / 0.85)' black-a3: 'oklch(0 0 0 / 0.03)' @@ -83,15 +68,8 @@ colors: black-a5: 'oklch(0 0 0 / 0.05)' black-a6: 'oklch(0 0 0 / 0.06)' black-a8: 'oklch(0 0 0 / 0.08)' - black-a10: 'oklch(0 0 0 / 0.1)' - black-a12: 'oklch(0 0 0 / 0.12)' - black-a18: 'oklch(0 0 0 / 0.18)' - black-a25: 'oklch(0 0 0 / 0.25)' - black-a30: 'oklch(0 0 0 / 0.3)' - black-a35: 'oklch(0 0 0 / 0.35)' black-a40: 'oklch(0 0 0 / 0.4)' black-a55: 'oklch(0 0 0 / 0.55)' - black-a60: 'oklch(0 0 0 / 0.6)' surface-page: '{colors.neutral-25}' surface-muted: '{colors.neutral-100}' surface-emphasis: '{colors.neutral-150}' @@ -103,6 +81,7 @@ colors: surface-code: '{colors.neutral-100}' surface-overlay: '{colors.black-a40}' fg-default: '{colors.neutral-950}' + fg-soft: 'color-mix(in oklch, {colors.fg-default} 70%, transparent)' fg-muted: '{colors.neutral-500}' fg-on-action: '{colors.neutral-50}' fg-on-danger: '{colors.neutral-0}' @@ -128,39 +107,21 @@ colors: line-warning-soft: 'color-mix(in oklab, {colors.fill-warning} 34%, {colors.line-default})' line-danger-soft: 'color-mix(in oklab, {colors.fill-danger} 34%, {colors.line-default})' line-info-soft: 'color-mix(in oklab, {colors.fill-info} 34%, {colors.line-default})' - edge-rest-side: '{colors.cool-gray-200}' - edge-rest-mid: '{colors.cool-gray-100}' - edge-focus-side: '{colors.cool-gray-400}' - edge-focus-mid: '{colors.cool-gray-300}' - edge-ambient-side: '{colors.cool-gray-100}' - edge-ambient-mid: '{colors.cool-gray-50}' - edge-faint: '{colors.cool-gray-100}' + edge-rest: '{colors.cool-gray-200}' + edge-focus: '{colors.cool-gray-400}' + edge-ambient: '{colors.cool-gray-100}' edge-raised: '{colors.cool-gray-200}' action-primary: '{colors.neutral-900}' - action-primary-hover: 'oklch(0.205 0 0 / 0.9)' + action-primary-hover: 'color-mix(in oklch, {colors.action-primary} 90%, transparent)' action-danger: '{colors.fill-danger}' - action-danger-hover: 'color-mix(in oklch, {colors.fill-danger} 90%, transparent)' + action-danger-hover: 'color-mix(in oklch, {colors.action-danger} 90%, transparent)' action-quiet: 'oklch(0.97 0 0 / 0.3)' action-quiet-hover: '{colors.neutral-100}' action-ghost-hover: 'oklch(0.556 0 0 / 0.1)' field-background: '{colors.neutral-0}' - field-shade: '{colors.black-a6}' - status-danger: '{colors.fill-danger}' - status-danger-rim: '{colors.red-400}' - status-danger-glyph: '{colors.red-800}' - status-warning: '{colors.fill-warning}' - status-warning-rim: '{colors.yellow-300}' - status-warning-glyph: '{colors.yellow-800}' - status-success: '{colors.fill-success}' - status-success-rim: '{colors.green-400}' - status-success-glyph: '{colors.green-800}' - status-info: '{colors.fill-info}' - status-info-rim: '{colors.blue-400}' - status-info-glyph: '{colors.blue-800}' highlight-inner: '{colors.white-a50}' highlight-inverse: '{colors.white-a12}' sheen-start: '{colors.white-a20}' - sheen-end: 'transparent' elevation-ring: '{colors.black-a5}' surface-page-matte: '{colors.neutral-0}' surface-glass-matte: 'oklch(0.97 0 0 / 0.6)' @@ -180,13 +141,14 @@ colors: surface-glass-dark: 'oklch(0.269 0 0 / 0.75)' surface-code-dark: '{colors.neutral-900}' fg-default-dark: '{colors.neutral-50}' + fg-soft-dark: 'color-mix(in oklch, {colors.fg-default-dark} 70%, transparent)' fg-muted-dark: '{colors.neutral-400}' fg-on-action-dark: '{colors.neutral-900}' fg-code-dark: '{colors.neutral-300}' - fg-danger-dark: '{colors.red-450}' - fg-success-dark: '{colors.green-450}' - fg-warning-dark: '{colors.amber-250}' - fg-info-dark: '{colors.blue-400}' + fg-danger-dark: '{colors.fill-danger-dark}' + fg-success-dark: '{colors.fill-success-dark}' + fg-warning-dark: '{colors.fill-warning-dark}' + fg-info-dark: '{colors.fill-info-dark}' line-default-dark: '{colors.white-a30}' line-field-dark: '{colors.white-a30}' line-control-dark: '{colors.white-a12}' @@ -204,27 +166,18 @@ colors: line-warning-soft-dark: 'color-mix(in oklab, {colors.fill-warning-dark} 38%, {colors.line-default-dark})' line-danger-soft-dark: 'color-mix(in oklab, {colors.fill-danger-dark} 38%, {colors.line-default-dark})' line-info-soft-dark: 'color-mix(in oklab, {colors.fill-info-dark} 38%, {colors.line-default-dark})' - edge-rest-side-dark: '{colors.white-a6}' - edge-rest-mid-dark: '{colors.white-a4}' - edge-focus-side-dark: '{colors.white-a18}' - edge-focus-mid-dark: '{colors.white-a12}' - edge-ambient-side-dark: '{colors.white-a4}' - edge-ambient-mid-dark: '{colors.white-a2}' - edge-faint-dark: '{colors.white-a4}' + edge-rest-dark: '{colors.white-a6}' + edge-focus-dark: '{colors.white-a18}' + edge-ambient-dark: '{colors.white-a4}' edge-raised-dark: '{colors.white-a9}' action-primary-dark: '{colors.neutral-200}' - action-primary-hover-dark: 'oklch(0.922 0 0 / 0.9)' + action-primary-hover-dark: 'color-mix(in oklch, {colors.action-primary-dark} 90%, transparent)' action-danger-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 58%, transparent)' action-danger-hover-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 68%, transparent)' action-quiet-dark: 'oklch(0.708 0 0 / 0.15)' action-quiet-hover-dark: 'oklch(0.708 0 0 / 0.25)' action-ghost-hover-dark: 'oklch(0.708 0 0 / 0.1)' field-background-dark: '{colors.white-a9}' - field-shade-dark: '{colors.black-a30}' - status-danger-dark: '{colors.fill-danger-dark}' - status-warning-dark: '{colors.fill-warning-dark}' - status-success-dark: '{colors.fill-success-dark}' - status-info-dark: '{colors.fill-info-dark}' highlight-inner-dark: '{colors.white-a4}' sheen-start-dark: '{colors.white-a2}' elevation-ring-dark: '{colors.white-a18}' @@ -254,6 +207,11 @@ typography: fontSize: 0.75rem fontWeight: 400 lineHeight: 1rem + caption-sm: + fontFamily: 'Llama Sans' + fontSize: 0.625rem + fontWeight: 400 + lineHeight: 0.875rem title: fontFamily: 'Llama Sans' fontSize: 1.125rem @@ -264,18 +222,24 @@ typography: fontSize: 1.5rem fontWeight: 600 lineHeight: 2rem + display: + fontFamily: 'Llama Sans' + fontSize: 1.875rem + fontWeight: 600 + lineHeight: 2.25rem code: fontFamily: 'Llama Mono' fontSize: 0.875rem fontWeight: 400 lineHeight: 1.25rem rounded: - control: 0.5rem - panel: 0.625rem - card: 0.875rem - container: 1rem - surface: 1.5rem - surface-lg: 2rem + sm: 6px + md: 8px + lg: 10px + xl: 14px + 2xl: 16px + 3xl: 24px + 4xl: 32px full: 9999px spacing: xs: 4px @@ -288,7 +252,7 @@ components: chat-form: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.surface}' + rounded: '{rounded.3xl}' typography: '{typography.body}' chat-form-dark: backgroundColor: '#202020' @@ -298,47 +262,47 @@ components: chat-form-placeholder-dark: textColor: '{colors.fg-muted-dark}' chat-form-edge: - backgroundColor: '{colors.edge-rest-side}' + backgroundColor: '{colors.edge-rest}' chat-form-edge-dark: - backgroundColor: '{colors.edge-rest-side-dark}' + backgroundColor: '{colors.edge-rest-dark}' chat-form-edge-focus: - backgroundColor: '{colors.edge-focus-side}' + backgroundColor: '{colors.edge-focus}' chat-form-edge-focus-dark: - backgroundColor: '{colors.edge-focus-side-dark}' + backgroundColor: '{colors.edge-focus-dark}' card: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.card}' + rounded: '{rounded.xl}' padding: '24px' card-dark: backgroundColor: '#202020' textColor: '{colors.fg-default-dark}' card-edge: - backgroundColor: '{colors.edge-rest-side}' + backgroundColor: '{colors.edge-rest}' card-edge-dark: - backgroundColor: '{colors.edge-rest-side-dark}' + backgroundColor: '{colors.edge-rest-dark}' sidebar: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.container}' + rounded: '{rounded.2xl}' sidebar-dark: backgroundColor: '#1c1c1c' textColor: '{colors.fg-default-dark}' sidebar-edge: - backgroundColor: '{colors.edge-ambient-side}' + backgroundColor: '{colors.edge-ambient}' sidebar-edge-dark: - backgroundColor: '{colors.edge-ambient-side-dark}' + backgroundColor: '{colors.edge-ambient-dark}' inset-group: backgroundColor: 'oklch(1 0 0 / 0.85)' textColor: '{colors.fg-default}' - rounded: '{rounded.card}' + rounded: '{rounded.xl}' inset-group-dark: backgroundColor: 'oklch(0.985 0 0 / 0.03)' textColor: '{colors.fg-default-dark}' inset-group-edge: - backgroundColor: '{colors.edge-ambient-side}' + backgroundColor: '{colors.edge-ambient}' inset-group-edge-dark: - backgroundColor: '{colors.edge-ambient-side-dark}' + backgroundColor: '{colors.edge-ambient-dark}' selected-row: backgroundColor: 'oklch(0.145 0 0 / 0.05)' textColor: '{colors.fg-default}' @@ -348,19 +312,19 @@ components: user-bubble: backgroundColor: '#f3f3f3' textColor: '{colors.fg-default}' - rounded: '{rounded.surface}' + rounded: '{rounded.2xl}' typography: '{typography.body}' user-bubble-dark: backgroundColor: '#181818' textColor: '{colors.fg-default-dark}' user-bubble-edge: - backgroundColor: '{colors.edge-faint}' + backgroundColor: '{colors.edge-ambient}' user-bubble-edge-dark: - backgroundColor: '{colors.edge-faint-dark}' + backgroundColor: '{colors.edge-ambient-dark}' floating-panel: backgroundColor: '#ffffff' textColor: '{colors.fg-default}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' typography: '{typography.body-sm}' floating-panel-dark: backgroundColor: '#161616' @@ -376,14 +340,14 @@ components: dialog: backgroundColor: '#ffffff' textColor: '{colors.fg-default}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' dialog-dark: backgroundColor: '#0d0d0d' textColor: '{colors.fg-default-dark}' tooltip: backgroundColor: '{colors.action-primary}' textColor: '{colors.fg-on-action}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.caption}' tooltip-dark: backgroundColor: '{colors.action-primary-dark}' @@ -391,7 +355,7 @@ components: button-primary: backgroundColor: '{colors.action-primary}' textColor: '{colors.fg-on-action}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-primary-dark: @@ -406,7 +370,7 @@ components: button-secondary: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-secondary-dark: @@ -425,7 +389,7 @@ components: button-tertiary: backgroundColor: '#fcfcfc' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-tertiary-dark: @@ -444,7 +408,7 @@ components: button-outline: backgroundColor: '{colors.field-background}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-outline-dark: @@ -462,7 +426,7 @@ components: textColor: '{colors.fg-default-dark}' button-ghost: textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' button-ghost-dark: textColor: '{colors.fg-default-dark}' @@ -475,7 +439,7 @@ components: button-destructive: backgroundColor: '{colors.action-danger}' textColor: '{colors.fg-on-danger}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-destructive-dark: @@ -490,7 +454,7 @@ components: toggle-on: backgroundColor: '{colors.surface-selected}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' toggle-on-dark: @@ -505,7 +469,7 @@ components: toggle-group: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '32px' toggle-group-dark: @@ -533,7 +497,7 @@ components: textColor: '{colors.fg-default-dark}' tabs-list: backgroundColor: '{colors.surface-muted}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' height: '36px' padding: '2px' tabs-list-dark: @@ -541,7 +505,7 @@ components: tabs-trigger: backgroundColor: '{colors.surface-muted}' textColor: 'oklch(0.145 0 0 / 0.7)' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' tabs-trigger-dark: backgroundColor: '{colors.surface-muted-dark}' @@ -582,7 +546,7 @@ components: input: backgroundColor: '{colors.field-background}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.body-sm}' height: '36px' input-dark: @@ -607,7 +571,7 @@ components: badge-default: backgroundColor: '{colors.action-primary}' textColor: '{colors.fg-on-action}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' padding: '2px 8px' badge-default-dark: @@ -616,14 +580,14 @@ components: badge-secondary: backgroundColor: '#dadada' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-secondary-dark: backgroundColor: '#252525' textColor: '{colors.fg-default-dark}' badge-outline: textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-outline-dark: textColor: '{colors.fg-default-dark}' @@ -634,7 +598,7 @@ components: badge-destructive: backgroundColor: '{colors.action-danger}' textColor: '{colors.fg-on-danger}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-destructive-dark: backgroundColor: '#952420' @@ -642,7 +606,7 @@ components: badge-success: backgroundColor: '{colors.surface-success}' textColor: '{colors.fg-success}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-success-dark: backgroundColor: '{colors.surface-success-dark}' @@ -650,7 +614,7 @@ components: badge-warning: backgroundColor: '{colors.surface-warning}' textColor: '{colors.fg-warning}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-warning-dark: backgroundColor: '{colors.surface-warning-dark}' @@ -658,7 +622,7 @@ components: badge-danger: backgroundColor: '{colors.surface-danger}' textColor: '{colors.fg-danger}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-danger-dark: backgroundColor: '{colors.surface-danger-dark}' @@ -666,7 +630,7 @@ components: badge-info: backgroundColor: '{colors.surface-info}' textColor: '{colors.fg-info}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-info-dark: backgroundColor: '{colors.surface-info-dark}' @@ -674,7 +638,7 @@ components: code-block: backgroundColor: '{colors.surface-code}' textColor: '{colors.fg-code}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' typography: '{typography.code}' code-block-dark: backgroundColor: '{colors.surface-code-dark}' @@ -684,21 +648,21 @@ components: list-row-selected: backgroundColor: '{colors.surface-selected}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' list-row-selected-dark: backgroundColor: '{colors.surface-selected-dark}' textColor: '{colors.fg-default-dark}' panel-muted: backgroundColor: '{colors.surface-muted}' textColor: '{colors.fg-default}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' panel-muted-dark: backgroundColor: '{colors.surface-muted-dark}' textColor: '{colors.fg-default-dark}' chip-emphasis: backgroundColor: '{colors.surface-emphasis}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' chip-emphasis-dark: backgroundColor: '{colors.surface-emphasis-dark}' textColor: '{colors.fg-default-dark}' @@ -708,22 +672,6 @@ components: page-dark: backgroundColor: '{colors.surface-page-dark}' textColor: '{colors.fg-default-dark}' - chat-form-edge-mid: - backgroundColor: '{colors.edge-rest-mid}' - chat-form-edge-mid-dark: - backgroundColor: '{colors.edge-rest-mid-dark}' - chat-form-edge-mid-focus: - backgroundColor: '{colors.edge-focus-mid}' - chat-form-edge-mid-focus-dark: - backgroundColor: '{colors.edge-focus-mid-dark}' - sidebar-edge-mid: - backgroundColor: '{colors.edge-ambient-mid}' - sidebar-edge-mid-dark: - backgroundColor: '{colors.edge-ambient-mid-dark}' - inset-group-edge-mid: - backgroundColor: '{colors.edge-ambient-mid}' - inset-group-edge-mid-dark: - backgroundColor: '{colors.edge-ambient-mid-dark}' glass-highlight: backgroundColor: '{colors.highlight-inner}' glass-highlight-dark: @@ -734,33 +682,61 @@ components: backgroundColor: '{colors.sheen-start}' user-bubble-sheen-dark: backgroundColor: '{colors.sheen-start-dark}' - field-shade: - backgroundColor: '{colors.field-shade}' - field-shade-dark: - backgroundColor: '{colors.field-shade-dark}' - status-lamp-danger-rim: - backgroundColor: '{colors.status-danger-rim}' - status-lamp-warning-rim: - backgroundColor: '{colors.status-warning-rim}' - status-lamp-success-rim: - backgroundColor: '{colors.status-success-rim}' status-lamp-danger: - backgroundColor: '{colors.status-danger}' - textColor: '{colors.status-danger-glyph}' + backgroundColor: '{colors.fill-danger}' rounded: '{rounded.full}' size: '8px' status-lamp-warning: - backgroundColor: '{colors.status-warning}' - textColor: '{colors.status-warning-glyph}' + backgroundColor: '{colors.fill-warning}' rounded: '{rounded.full}' size: '8px' status-lamp-success: - backgroundColor: '{colors.status-success}' - textColor: '{colors.status-success-glyph}' + backgroundColor: '{colors.fill-success}' rounded: '{rounded.full}' size: '8px' --- +## In short + +The rules most changes need. The sections below hold the detail and the reasons, and they +win where this list is too short. Before adding a token, a size or a component, use what is +here; if something really is missing, add it here first. + +- **Components:** take base components from Llama UI (`@ggml-org/llama-ui/ui/`); do not + build a new one when an existing one fits. Style them through their variants + (`variant="outline"`, `size="sm"`), not by overriding classes. +- **Colour:** greys build the UI; colour is for meaning only (status, destructive actions, + focus). Neutral colours go by shadcn's utility names (`bg-background`, `bg-muted`, `bg-card`, + `text-foreground`, `text-muted-foreground`, `border-border`), status by `bg-surface-*`, + `bg-fill-*`, `text-fg-*` and `border-line-*-soft` of `success`, `warning`, `danger` and + `info`, and any other semantic token as `bg-(--surface-lifted)`. In CSS, read the semantic + token (`var(--surface-page)`). No Tailwind palette classes, no hex. +- **Type:** Llama Sans, and Llama Mono for code, through roles: `text-body` (16px) for chat + messages and the chat input, `text-body-sm` (14px) for most text, `text-label` (14px, medium) + for buttons and labels, `text-label-sm` and `text-caption` (12px) for badges and hints, + `text-caption-sm` (10px) for tags and counts, `text-title` (18px) and `text-heading` (24px) + for the rare heading, `text-display` (30px) for the biggest headline. Never Tailwind's own sizes (`text-sm`, `text-xs`) or a size in + brackets. +- **Shape:** one corner scale, `rounded-sm` to `rounded-4xl`: `rounded-md` (8px) for controls, + fields and badges, `rounded-lg` (10px) for menus and dialogs, `rounded-xl` (14px) for cards, + `rounded-2xl` (16px) and `rounded-3xl` (24px) for the larger surfaces, `rounded-full` for + pills, avatars and lamps. +- **Sizes:** Tailwind's 4px spacing scale. Icons are Lucide, `size-icon-md` (16px), or + `size-icon-sm` (14px) in compact controls. Controls are `h-control-sm`, `h-control-md` or + `h-control-lg` (32, 36, 40px). +- **Surfaces:** one surface utility per element (`card-surface`, `matte-float`, `matte-key`, + `matte-well`), never raw `shadow-*`, `border-*` and `backdrop-blur-*` combinations. +- **Tokens:** read a semantic token directly. A component token is only for a value the + component decides itself. A value that follows from another token is mixed from it, not + picked again. +- **No arbitrary values** (`text-[11px]`, `rounded-[1.125rem]`, `p-[7px]`, `z-[20]`): pick the + nearest from the scale (`z-20`, `max-w-4/5`, `min-w-32`). Brackets are for what no scale can + hold: a `calc()`, a grid template, a list of transition properties. +- **Motion:** `ease-out-quint` for what enters or answers a press, `ease-sheet` for a sheet + or a page that slides. +- **Phones:** every dialog is full screen; only alerts stay small and centred. +- **The conversation is the loudest thing on screen;** everything around it stays quiet. + ## Overview **Llama UI** is the design system and component library this file describes. **Llama Chat**, @@ -793,7 +769,7 @@ This file is the how, written for agents first. Its principles, as rules to appl - **Colour has one job.** Greys build everything; status colours show status and nothing else; art colours and cinder are for artwork and the odd brand detail, never for the UI's controls. - **Recognisable, easy to change.** Keep the character in the icon, the type and one - accent, so an app built on Llama UI can restyle it through component tokens alone. + accent, so an app built on Llama UI can restyle it through semantic and component tokens alone. - **Design lives in code.** The CSS is the source of truth; prefer what is generated or derived over hand-tuned values, and record the reason next to the value. Content pages are Markdown with Svelte components in them, as `.svx` (see `AGENTS.md`). @@ -802,18 +778,35 @@ This file is the how, written for agents first. Its principles, as rules to appl Design tokens come in three tiers, each in its own file under `ui/lib/ui/src/lib/styles/tokens/`: -1. **Primitives** (`primitives.css`): raw values named by what they are, such as - `neutral-900`, `cool-gray-200`, `red-500`, `white-a30`, `font-size-14` or `length-24`. - Only semantic tokens point at them. +1. **Primitives** (`primitives.css`): raw colours named by what they are, such as + `neutral-900`, `cool-gray-200`, `red-550` or `white-a30`. Only semantic tokens point at + them. Sizes are not primitives: a role holds its own value, and spacing is Tailwind's 4px + grid. 2. **Semantic tokens** (`semantic.css`): named by purpose, such as `surface-glass`, - `fg-muted`, `line-field`, `edge-focus-side`, `action-primary` or `status-warning`. They - point at primitives and are the only tier that changes between light and dark. The type, - corner, icon size and control height roles live here too and are Tailwind utilities: - `text-label`, `rounded-control`, `size-icon-md`, `h-control-md`. -3. **Component tokens** (`components.css`): one group per component, named - `[component]-[variant]-[property]-[state]`, such as `chat-form-edge-side-focus` or - `button-secondary-background-hover`. They point at semantic tokens, and components read - them as `bg-(--button-primary-background)` and similar. + `fg-muted`, `line-field`, `edge-focus`, `action-primary` or `fill-warning`, and the only + tier that changes between light and dark. Each is either a pick, which names a primitive + per theme, or a derivation, which is mixed from another semantic token by a fixed rule and + so follows it through every theme with a single declaration: + - soft text is the text colour at 70% (`fg-soft`); + - a hover fill is the fill at 90% (`action-primary-hover`); + - a status surface is its fill mixed into the page, and a status line its fill mixed into + the default line, by a share the theme sets (11% and 34% in light, 16% and 38% in dark); + - a dark shadow is the light one, `elevation-strength` (1 in light, 5 in dark) times as + dense; + - the middle of a matte edge is its side at two thirds, and a lamp's rim and glyph are + its fill mixed 30% towards white and towards black (both in `surfaces.css`). + + The type, icon size and control height roles live here too and are Tailwind utilities: + `text-label`, `size-icon-md`, `h-control-md`. Corners are Tailwind's own `rounded-sm` to + `rounded-4xl`, computed from `--radius` in `theme.css`. shadcn's + colour names (`background`, `muted-foreground`, `border` ...) exist as Tailwind utilities + only, each mapped to a semantic token in `theme.css`. + +3. **Component tokens** (`components.css`): only what a component decides itself, named + `[component]-[variant]-[property]-[state]`, such as `button-secondary-background-hover` or + `float-panel-background-modal`: a value no semantic token has, or one that only this + component changes between themes. A component that takes a semantic token as it is reads + the semantic token, as `bg-(--action-primary)` and similar, and gets no alias here. The front matter's `colors`, `typography` and `rounded` are generated from the primitives, the semantic tokens and the font stacks by `npm run design:tokens` in `ui/apps/chat`, and CI fails @@ -860,16 +853,18 @@ the Surface switch in Storybook's toolbar, and only its surface tokens differ: ` `surface-raised` for menus and dialogs, `surface-lifted` for a selection raised on a recessed track, `surface-pressed` for a key pressed in, `surface-glass` for the translucent matte fill, `surface-code` for code and `surface-overlay` behind dialogs. -- **Foreground:** `fg-default` and `fg-muted` for text and icons, `fg-on-action` and +- **Foreground:** `fg-default` and `fg-muted` for text and icons, `fg-soft` (the text colour + at 70%) for the label of an option that is not the picked one, `fg-on-action` and `fg-on-danger` on filled buttons, `fg-code` for code, `fg-danger` for errors, `fg-success` for confirmations such as a copied check, `fg-warning` for cautions and `fg-info` for neutral notices. - **Lines:** `line-default` for dividers, `line-control` for outlined controls (soft in dark mode), `line-field` for inputs, `line-focus` for focus and `line-danger` for invalid fields. -- **Edges:** the hairlines of matte surfaces, darker at the sides than in the middle. - `edge-rest-*` at rest, `edge-focus-*` when focus is inside, `edge-ambient-*` for large - quiet containers whose edge never changes, `edge-faint` for the user bubble and - `edge-raised` for floating panels. +- **Edges:** the hairlines of matte surfaces, darker at the sides than in the middle (the + token is the side; the surface fades it to two thirds in the middle). `edge-rest` at rest, + `edge-focus` when focus is inside, `edge-ambient` for large quiet containers whose edge + never changes and, kept even all round, for the user bubble, and `edge-raised` for floating + panels. - **Actions:** `action-primary` (near black in light mode, near white in dark mode) and its hover, `action-danger` and its hover, and `action-ghost-hover`. - **Status fills:** `fill-success`, `fill-warning`, `fill-danger` and `fill-info` are each @@ -880,9 +875,9 @@ the Surface switch in Storybook's toolbar, and only its surface tokens differ: ` `surface-info` are soft tints of each status fill for alerts and soft badges, with `line-*-soft` hairlines to match. They are mixed in oklab so the hue holds over the page. Soft status badges are pills with a small dot in the status fill before the label. -- **Status:** `status-danger`, `status-warning`, `status-success` and `status-info` are the - lamp fills for error or stopped, loading or warning, ready or connected, and informational. They take the status - fills, and each has a lighter `-rim` and a darker `-glyph`. Known gap: the glyph on the red lamp +- **Status:** `fill-danger`, `fill-warning`, `fill-success` and `fill-info` are the + lamp fills for error or stopped, loading or warning, ready or connected, and informational. A lamp adds + a lighter rim and a darker glyph, both mixed from its fill. Known gap: the glyph on the red lamp reaches only about 2:1 and on the green lamp about 3.2:1, below WCAG AA, so the lamp colour must never be the only signal; pair it with a label or tooltip. @@ -895,14 +890,21 @@ is one variable font with an optical size axis: the browser sets it from the fon looser Small one, with a blend in between. Nothing needs choosing per element; pin a point only to show it, with `font-variation-settings: 'opsz' 16` or `36`. Its line box is 1.25 at every size, centred on the cap height; large headings set `line-height: 1.15` themselves. Llama Mono keeps every character, -its coding ligatures included, in one cell, so code and numbers line up in columns. Type is set through roles that fix size, line height and weight together: +its coding ligatures included, in one cell, so code and numbers line up in columns. Type is set through roles that fix size and line height together, and for labels and headings the weight too: -- `body` (16/24, 400): chat messages and the chat input. -- `body-sm` (14/20, 400): most text, fields and lists. +- `body` (16/24): chat messages and the chat input. +- `body-sm` (14/20): most text, fields and lists. - `label` (14/20, 500): buttons and field labels. - `label-sm` (12/16, 500): badges and compact labels. -- `caption` (12/16, 400): tooltips, hints and metadata. -- `title` (18/28, 600) and `heading` (24/32, 600): rare headings; there is no display size. +- `caption` (12/16): tooltips, hints and metadata. +- `caption-sm` (10/14): the smallest text, for tags, compact badges and counts. +- `title` (18/28, 600) and `heading` (24/32, 600): rare headings. +- `display` (30/36, 600): the biggest headline, such as the greeting on a new chat. + +Body and caption text takes the weight around it, regular unless a parent says otherwise; add +a weight class for anything else (`text-body-sm font-semibold`). The roles are the whole +scale: no `text-sm` or `text-xs`, and no size in brackets. On a phone a row that needs larger +text takes the next role up (`text-body-sm max-md:text-body`). When a component lets callers override the size, keep an explicit weight class next to the role (`text-label font-medium`) so a size override does not drop the weight. Placeholders @@ -978,8 +980,8 @@ matches the role of the surface instead of combining raw shadows. - **`matte-float`** and **`matte-float-modal`:** menus, popovers, select lists, hover cards and drawers, and dialogs over the page colour. An 86% opaque panel with blur, a faint edge, a rim and a deeper shadow. The edge is a hairline ring baked into the shadow as its last - layer (`float-panel-edge`). The panel's 1px border is its rim, the inner highlight - (`float-panel-highlight`) right inside the ring; an inset shadow for the rim would sit inside + layer (`edge-raised`). The panel's 1px border is its rim, the inner highlight + (`highlight-inner`) right inside the ring; an inset shadow for the rim would sit inside the border instead, and the 1px between the two would draw a double edge. In light mode dialogs are solid white instead: over the dimmed page a translucent white turns grey. - **`matte-key`:** buttons, selects, toggles and tabs. The matte finish: on top of the @@ -991,12 +993,12 @@ matches the role of the surface instead of combining raw shadows. (`--key-sheen-solid`), the same blur, and an even 1px hairline in a shade of the fill drawn inside the button (`--key-edge`), so the width does not change. The danger key stays matte glass rather than metal: its sheen is almost none (`--button-danger-sheen`), and in dark mode - it is a frosted, translucent red (`red-500` at 58%) whose edge is a soft tint of the red, never + it is a frosted, translucent red (`fill-danger` at 58%) whose edge is a soft tint of the red, never a lighter rim. - **`elevated-control`**, **`elevated-surface`** and **`elevated-raised`:** cards, floating bars and thumbnails. An elevation token with a hairline ring baked in as its last layer, so the edge melts into the shadow and the shadow deepens in dark mode. The ring is - `--elevation-ring` (black 5%, white 18% in dark) at `--elevation-ring-width` (1px). They + `--elevation-ring` (black 5%, white 18% in dark), 1px wide. They replace a border plus a shadow; never add a border to them. - **`matte-well`:** inputs, textareas and checkboxes. A shallow inset shade so fields read as recessed. @@ -1007,16 +1009,16 @@ matches the role of the surface instead of combining raw shadows. an even hairline, with no glow. The elevation tokens are `elevation-surface`, `elevation-control`, `elevation-raised`, -`elevation-inset` and `elevation-tooltip`. The drop shadows are smooth stacks: a few soft +`elevation-inset` and `elevation-pressed`; a tooltip takes `elevation-surface`. The drop shadows are smooth stacks: a few soft layers instead of one hard one, the closest the darkest and smallest, each further layer about twice the offset and blur and fainter, the far ones pulled in with a negative spread, so the -shadow fades out instead of ending in a visible edge. They stay as close as upstream's -Tailwind shadows: `elevation-surface` reaches about 20px, like `shadow-lg`, `elevation-raised` -about 38px, like `shadow-xl`, and `elevation-control` is three tight layers reaching no further -than 4px, so buttons and other controls sit close to the page. Two softer steps sit below them: `elevation-soft` for the chat form, +shadow fades out instead of ending in a visible edge. They are the only shadows: Tailwind's +own `shadow-sm` to `shadow-2xl` do not follow the theme and are not used. `elevation-surface` +reaches about 20px, `elevation-raised` about 38px, and `elevation-control` is three tight +layers reaching no further than 4px, so buttons and other controls sit close to the page. Two softer steps sit below them: `elevation-soft` for the chat form, which floats only a little, and `elevation-faint` for the user message bubble, which barely -lifts. The keys inside the chat form, the add key and the model selector, take `elevation-key` -(`--chat-form-key-shadow`): a 0.5px hairline all round and a 1px drop, since the control elevation's soft +lifts. The keys inside the chat form, the add key and the model selector, take `elevation-key`: +a 0.5px hairline all round and a 1px drop, since the control elevation's soft spread blends into the white form; in dark it is the control elevation. Dark mode deepens the same stacks. Tailwind's own `shadow-xs` to `shadow-2xl` are built the same way (`tokens/semantic.css`), each reaching about as far as Tailwind's default for it. Every @@ -1025,11 +1027,12 @@ with a 2px blur. ## Shapes -Corners are soft and consistent, set through roles: `control` (8px) for buttons, fields and -badges, `panel` (10px) for menus and dialogs, `card` (14px) for cards, `container` (16px) for -the sidebar, and `surface` (24px) for the chat form and message bubbles, rising to -`surface-lg` (32px) for the chat form on small screens. Status lamps, avatars and the round -icon buttons in the chat form are fully round. +Corners are soft and consistent, on one scale that is computed from a single base radius +(`--radius`, 10px, in `theme.css`), so changing the base moves every corner with it: `sm` +(6px) for small marks and chips, `md` (8px) for buttons, fields and badges, `lg` (10px) for +menus and dialogs, `xl` (14px) for cards, `2xl` (16px) for the sidebar and message bubbles, +and `3xl` (24px) for the chat form, rising to `4xl` (32px) for the chat form on small +screens. Status lamps, avatars and the round icon buttons in the chat form are fully round. ## Brand @@ -1071,15 +1074,15 @@ icon buttons in the chat form are fully round. - **Toggles:** the same corners, type, heights, padding and icon size as buttons, with square `icon-sm`, `icon` and `icon-lg` sizes for icon-only toggles. `default` has no fill until hovered; `outline` borrows the outline button. Pressed toggles take - `toggle-background-on`. + `surface-selected`. - **Button groups:** joined buttons share one shadow, drawn by the group, and one border at each seam. A group separator replaces the seam border. Filled buttons draw a seam in their - own text colour (`button-primary-seam`, `button-danger-seam`) instead. + own text colour at 25% instead. - **Selection on a track:** a choice that moves along a track is a recessed track with the selection raised on it, never a row of outlined buttons. The track is `surface-muted` with the inset shade (`elevation-inset`); the selection is a `surface-lifted` chip with - `elevation-control`, and unselected options are softened text with no fill. Tabs use the - same track for their list, with the active tab raised (`tabs-*`); a `line` variant + `elevation-control`, and unselected options are softened text (`fg-soft`) with no fill. Tabs use the + same track for their list, with the active tab raised; a `line` variant underlines the active tab instead. The chip or underline slides between tabs in 300ms on a plain ease-out, with a stretch of at most 5% along the move that is gone by the time it lands; with reduced motion it jumps instead. The switch is the same track with a raised @@ -1095,7 +1098,7 @@ icon buttons in the chat form are fully round. - **Chat form:** one `chat-form-surface` holding the input, attachments and actions. Its fill is the muted grey at 60% in light mode and 75% in dark mode. - **User message bubble:** the primary colour at 5% with `matte-sheen` and the very faint - `edge-faint` hairline, so it separates from the page without a visible border. + `edge-ambient` hairline, so it separates from the page without a visible border. - **Sidebar:** `sidebar-surface`, the muted fill at 60% with no inner highlight and the ambient edge. On small screens it keeps a plain `shadow-md` instead. - **Inset groups:** `inset-group-surface` gathers rows inside a glass panel, like the @@ -1168,8 +1171,8 @@ icon buttons in the chat form are fully round. lifting the surface. - Do use the status colours only for status. Buttons keep their neutral colours, and the submit button stays black in light mode and white in dark mode. -- Do read component tokens in components, semantic tokens in shared styles, and primitives - only in semantic tokens. +- Do read a semantic token directly wherever a component takes it as it is. Add a component + token only for a value the component decides itself, never as an alias of a semantic token. - Do add a new colour as a primitive first, then give it a semantic name before any component uses it. - Do give motion a job: show where something went or what changed, like a selection sliding diff --git a/ui/apps/chat/scripts/design-md.js b/ui/apps/chat/scripts/design-md.js index 316bf9acdc2e..94c90b1f5452 100644 --- a/ui/apps/chat/scripts/design-md.js +++ b/ui/apps/chat/scripts/design-md.js @@ -34,9 +34,11 @@ const THEMES = [ ]; // the type roles, by the @theme names Tailwind turns into text-body, text-label-sm, ...: a size with a line height const TYPE_ROLE = /^--text-([a-z]+(?:-[a-z]+)*)$/; +// body and caption text takes the weight around it, which is regular unless a parent says otherwise +const DEFAULT_WEIGHT = '400'; // code takes the body-sm role in the mono stack (see `:where(code, pre, kbd, samp)` in theme.css) const CODE_ROLE = 'body-sm'; -// Tailwind's own `rounded-full`, for lamps, avatars and round buttons; the other corners are roles in semantic.css +// Tailwind's own `rounded-full`, for lamps, avatars and round buttons; the other corners are the scale in theme.css const ROUNDED_FULL = '9999px'; // the sections this script owns, in the order they appear in the front matter; the next one is written by hand const SECTIONS = ['colors', 'typography', 'rounded']; @@ -104,6 +106,8 @@ const isColorLiteral = (value) => /^(oklch|oklab|rgb|hsl)\([^()]*\)$/.test(value); /** @param {string} value */ const isColorMix = (value) => /^color-mix\(.*\)$/.test(value) && !/\)\s*,/.test(value); +/** a share a theme sets for a derivation, e.g. `--status-surface-share: 11%` @param {string} value */ +const isShare = (value) => /^\d+(?:\.\d+)?%$/.test(value); /** @param {string} value */ const varName = (value) => /^var\(--([\w-]+)\)$/.exec(value)?.[1]; @@ -136,7 +140,19 @@ function build() { return next !== undefined && isColor(next, scope); }; - const semanticColors = [...semantic].filter(([, value]) => isColor(value, semantic)); + /** + * A value with the shares it reads written out, as the theme whose declarations are `scope` sets them, so a + * derivation reads as the mix it is: `color-mix(in oklab, var(--fill-danger) 11%, var(--surface-page))`. + * @param {string} value + * @param {Map} [scope] + */ + const withShares = (value, scope) => + value.replace(/var\((--[\w-]+)\)/g, (reference, name) => { + const share = scope?.get(name) ?? semantic.get(name) ?? ''; + + return isShare(share) ? share : reference; + }); + const semanticColors = [...semantic].filter(([, value]) => isColor(withShares(value), semantic)); const semanticNames = new Set(semanticColors.map(([name]) => name.slice(2))); /** * A token's value as the front matter writes it: a reference to another token, a literal, or a mix of them. A @@ -166,7 +182,7 @@ function build() { const base = new Map(); for (const [name, value] of semanticColors) { - const rendered = render(value, (n) => n); + const rendered = render(withShares(value), (n) => n); base.set(name, rendered); colors.push([name.slice(2), rendered]); @@ -190,7 +206,9 @@ function build() { if (semanticNames.has(ref)) resolve(`--${ref}`); } - const result = render(value, (n) => (twins.has(n) ? `${n}${suffix}` : n)); + const result = render(withShares(value, overrides), (n) => + twins.has(n) ? `${n}${suffix}` : n + ); rendered.set(name, result); @@ -217,6 +235,13 @@ function build() { return (name && primitives.get(`--${name}`)) ?? value ?? ''; }; + // a line height is written as the line over the size, `calc(1.25 / 0.875)`: the line, in rem + /** @param {string | undefined} value */ + const lineHeight = (value) => { + const ratio = /^calc\(([\d.]+) \/ [\d.]+\)$/.exec(value ?? ''); + + return ratio ? `${ratio[1]}rem` : length(value); + }; /** @type {[string, Record][]} */ const typography = []; @@ -230,8 +255,8 @@ function build() { { fontFamily: sans, fontSize: length(value), - fontWeight: length(inline.get(`${name}--font-weight`)), - lineHeight: length(inline.get(`${name}--line-height`)) + fontWeight: inline.get(`${name}--font-weight`) ?? DEFAULT_WEIGHT, + lineHeight: lineHeight(inline.get(`${name}--line-height`)) } ]); } @@ -242,11 +267,17 @@ function build() { /** @type {[string, string][]} */ const rounded = []; + // the corner scale is computed from --radius: `calc(var(--radius) + 4px)`, with 1rem as 16px + const baseRadius = parseFloat(theme.get(':root')?.get('--radius') ?? '') * 16; - for (const [name, value] of inline) { - const role = /^--radius-([a-z-]+)$/.exec(name)?.[1]; + for (const [name, value] of theme.get('@theme inline') ?? []) { + const step = /^--radius-([a-z0-9]+)$/.exec(name)?.[1]; + const offset = /^calc\(var\(--radius\) ([+-]) ([\d.]+)px\)$/.exec(value); + + if (!step) continue; - if (role) rounded.push([role, length(value)]); + if (offset) rounded.push([step, `${baseRadius + Number(offset[1] + offset[2])}px`]); + else if (value === 'var(--radius)') rounded.push([step, `${baseRadius}px`]); } rounded.push(['full', ROUNDED_FULL]); diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index cca440844162..24ba6cec44bb 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -30,7 +30,7 @@ /* phone sidebar width, which the page slides aside to reveal */ --sidebar-reveal: min(80dvw, 20rem); /* the desktop sidebar's muted/60 over the page, made opaque so the slid page's corners can match it */ - --sidebar-reveal-tint: color-mix(in oklab, var(--muted) 60%, var(--background)); + --sidebar-reveal-tint: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); /* how far the phone sidebar is open, 0 to 1, stepped every frame by useSidebarReveal */ --sidebar-reveal-progress: 0; /* the same on a log curve: the sidebar's contents hold on until the page nearly covers them */ @@ -39,7 +39,7 @@ --sidebar-reveal-bg: color-mix( in oklab, var(--sidebar-reveal-tint) calc(var(--sidebar-reveal-progress) * 100%), - var(--background) + var(--surface-page) ); --layer-popover: 1000000; @@ -63,7 +63,7 @@ /* the chat form's corners while its text and actions share one row */ --chat-form-single-row-radius: 1.25rem; /* the card's translucent fill over the page, made opaque: the phone sheet, and the page and Safari's bars around it */ - --chat-form-sheet-fill: color-mix(in oklab, var(--muted) 60%, var(--background)); + --chat-form-sheet-fill: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); --max-message-height: max(24rem, min(80dvh, calc(100dvh - var(--chat-form-area-height) - 12rem))); } @@ -91,7 +91,7 @@ } .dark { - --chat-form-sheet-fill: color-mix(in oklab, var(--muted) 75%, var(--background)); + --chat-form-sheet-fill: color-mix(in oklab, var(--surface-muted) 75%, var(--surface-page)); } @layer base { @@ -202,9 +202,9 @@ .chat-top-fade { background: linear-gradient( to bottom, - color-mix(in srgb, var(--background) 100%, transparent) 25%, - color-mix(in srgb, var(--background) 80%, transparent) 50%, - color-mix(in srgb, var(--background) 40%, transparent) 75%, + color-mix(in srgb, var(--surface-page) 100%, transparent) 25%, + color-mix(in srgb, var(--surface-page) 80%, transparent) 50%, + color-mix(in srgb, var(--surface-page) 40%, transparent) 75%, transparent 100% ); } @@ -219,8 +219,8 @@ height: var(--page-top); background: linear-gradient( to bottom, - var(--background) calc(var(--corner-control-top) + 1.25rem), - color-mix(in srgb, var(--background) 55%, transparent) + var(--surface-page) calc(var(--corner-control-top) + 1.25rem), + color-mix(in srgb, var(--surface-page) 55%, transparent) calc(var(--corner-control-top) + 2.5rem), transparent 100% ); @@ -234,14 +234,14 @@ 10px Safari ignores; what it covers sits under the fade's solid part anyway */ .status-bar-edge { height: 0.75rem; - background-color: var(--background); + background-color: var(--surface-page); } /* The bottom edge's counterpart, which Safari takes for its bottom toolbar the same way: without it, it finds the chat form there and takes the form's colour */ .screen-bottom-edge { height: 0.75rem; - background-color: var(--background); + background-color: var(--surface-page); } /* The same fade at the bottom of a phone's screen: solid behind the home indicator and @@ -251,8 +251,9 @@ height: calc(var(--safe-area-bottom) + 3rem); background: linear-gradient( to top, - var(--background) var(--safe-area-bottom), - color-mix(in srgb, var(--background) 60%, transparent) calc(var(--safe-area-bottom) + 1.5rem), + var(--surface-page) var(--safe-area-bottom), + color-mix(in srgb, var(--surface-page) 60%, transparent) + calc(var(--safe-area-bottom) + 1.5rem), transparent 100% ); } @@ -261,7 +262,7 @@ panel's translucent muted tint, and a fade above it, like the one under the tab bar, so the rows scrolling beneath end softly */ .sidebar-show-more { - --sidebar-surface: color-mix(in oklab, var(--muted) 60%, var(--background)); + --sidebar-surface: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); background: var(--sidebar-surface); &::before { @@ -284,14 +285,14 @@ over the other sections while dragged */ .sidebar-drag-surface, .sidebar-drag-overlay { - background: color-mix(in oklab, var(--muted) 60%, var(--background)); + background: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); } /* the copy of a chat row that follows the pointer, raised above the page */ .sidebar-drag-overlay { box-shadow: 0 10px 30px -10px rgb(0 0 0 / 0.35), - 0 0 0 1px color-mix(in srgb, var(--foreground) 12%, transparent); + 0 0 0 1px color-mix(in srgb, var(--fg-default) 12%, transparent); } /* While something is dragged, what it passes over takes no hover: only the @@ -329,12 +330,7 @@ } .shimmer-text { - background: linear-gradient( - 90deg, - var(--muted-foreground), - var(--foreground), - var(--muted-foreground) - ); + background: linear-gradient(90deg, var(--fg-muted), var(--fg-default), var(--fg-muted)); background-size: 200% 100%; background-clip: text; -webkit-background-clip: text; @@ -361,16 +357,16 @@ * so the svg also inherits them inside the preview dialog's shadow root, and follow the theme. */ :root { - --pele-bg: var(--code-background); - --pele-fg: var(--code-foreground); - --pele-muted: var(--muted-foreground); - --pele-line: var(--muted-foreground); - --pele-surface: var(--background); - --pele-surface-alt: var(--muted); - --pele-border: var(--border); - --pele-accent: var(--primary); - --pele-critical: var(--destructive); - --pele-error: var(--destructive); + --pele-bg: var(--surface-code); + --pele-fg: var(--fg-code); + --pele-muted: var(--fg-muted); + --pele-line: var(--fg-muted); + --pele-surface: var(--surface-page); + --pele-surface-alt: var(--surface-muted); + --pele-border: var(--line-default); + --pele-accent: var(--action-primary); + --pele-critical: var(--fg-danger); + --pele-error: var(--fg-danger); --pele-radius: calc(var(--radius) - 4px); } diff --git a/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte b/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte index 7c921732de6a..87cc59093779 100644 --- a/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte +++ b/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte @@ -18,7 +18,7 @@ {@const ModalityIcon = MODALITY_ICONS[modality]} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte index 5bb7a47d71ea..d7284aa615b6 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte @@ -77,7 +77,7 @@ : null} {#if mcpPrompt} onFileRemove(item.id) : undefined} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemMcpResource.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemMcpResource.svelte index 6fb3c294fcd2..34f142eea943 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemMcpResource.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemMcpResource.svelte @@ -35,7 +35,7 @@
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte index d27d54a4bae2..e51429a143fd 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte @@ -7,10 +7,10 @@ let { displayName, fileSize }: Props = $props(); -
+

{displayName}

{#if fileSize} -

{fileSize}

+

{fileSize}

{/if}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte index 513d97a124d6..2fa421520d3a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte @@ -61,7 +61,9 @@ {/if} - {getFileExtension(item.name)} + {getFileExtension(item.name)}
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index 0c44d125fb9c..e99c1eac32f0 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -678,9 +678,7 @@ bind:this={cardEl} class={[ 'chat-form-surface group/chat-form relative flex shrink flex-col overflow-hidden outline-none transition-[min-height,padding,border-radius,border-color,background-color] duration-400 ease-[var(--chat-form-resize-ease,cubic-bezier(0.3,1.12,0.5,1))] motion-reduce:transition-none', - isSingleRow - ? 'rounded-(--chat-form-single-row-radius)' - : 'rounded-(--chat-form-radius-compact) md:rounded-(--chat-form-radius)', + isSingleRow ? 'rounded-(--chat-form-single-row-radius)' : 'rounded-4xl md:rounded-3xl', // on a phone the sheet's animation moves it (see useChatFormExpansion): only its // border, hidden on the sheet, fades back in after 'max-md:transition-[border-color] max-md:duration-200', @@ -702,7 +700,7 @@ 'max-md:pt-safe', // no rim, ring or visible border along the screen's edges; the border stays // transparent so nothing inside shifts by its width - 'max-md:[--glass-edge-side:transparent] max-md:[--glass-edge-mid:transparent] max-md:[--glass-edge-side-focus:transparent] max-md:[--glass-edge-mid-focus:transparent] max-md:[--glass-highlight:transparent]', + 'max-md:[--glass-edge:transparent] max-md:[--glass-edge-focus:transparent] max-md:[--glass-highlight:transparent]', 'max-md:border-transparent max-md:focus-within:border-transparent max-md:dark:border-transparent max-md:dark:focus-within:border-transparent', EXPANDED_SHEET_FILL ], @@ -734,7 +732,7 @@
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte index 04fd275fd590..91d4b7de03cf 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte @@ -46,7 +46,7 @@
{#if subtitle} -
+
{subtitle}
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte index f57dcc636e2d..34d22dfd6716 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte @@ -33,13 +33,13 @@
-

Token usage details

+

Token usage details

-
+
{#if hasCumulative}

Across all turns

@@ -68,7 +68,7 @@ {#if hasCurrent}

This turn · KV cache

diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte index 3627c74197d3..d2dd96f79aa3 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte @@ -12,13 +12,17 @@ {#if modelId !== null && !isLoading} -
+
Available context size is only visible once the model is loaded.
{:else if isLoading} -
+
Loading model... diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte index 802dd7e8d081..fbd645720665 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte @@ -120,7 +120,7 @@ >
-
+
{gauge.contextPercent}% used @@ -130,7 +130,7 @@
{:else} -
No context info available
+
No context info available
{/if} {#if gauge.hasAnyUsage} @@ -172,7 +172,7 @@ {:else if gaugePopup.open}
{#if !fileSearchEnabled} -
{searchUnavailableMessage}
+
{searchUnavailableMessage}
{:else if query.trim() && (search.isSearching || queryResults.length > 0 || searchError)}
- + Searching in: diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte index ef69d0f5aced..bc368ac74a14 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte @@ -38,18 +38,18 @@ class="max-h-48 overflow-y-auto py-2" > {#if isSearching && results.length === 0} -
Searching...
+
Searching...
{:else if error} -
{error}
+
{error}
{:else if results.length === 0} -
No matching folders
+
No matching folders
{:else} {#each results as path, index (path)}
- +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte index c37b0447fd29..72679c8f1238 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte @@ -199,7 +199,7 @@ {#if displayedModel}
-
+
- + {modelLoadingText ?? processingState.getPromptProgressText() ?? processingState.getProcessingMessage() ?? diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte index e5119ae358f8..f0afdc4b072c 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte @@ -24,8 +24,8 @@ margin-top: 1.5rem; padding: 1rem 1.25rem; border-radius: 1rem; - background: hsl(var(--muted) / 0.3); - color: var(--foreground); + background: hsl(var(--surface-muted) / 0.3); + color: var(--fg-default); font-size: 0.875rem; line-height: 1.6; white-space: pre-wrap; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte index 959016a26538..b70fe2244cd5 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte @@ -20,13 +20,13 @@ {#if info.path === null} - Working directory cleared + Working directory cleared {:else} - Set working directory to  + Set working directory to  - + {info.display} {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte index 32f5cceab6a8..2caaf6e4369a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte @@ -29,13 +29,13 @@ {:else} {#if message.timestamp} -
+
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte index 27af803f0ccb..d1303379a391 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte @@ -82,7 +82,7 @@ let showArgBadges = $derived(hasArguments && !isLoading && !loadError); let isAttachment = $derived(variant === McpPromptVariant.ATTACHMENT); - let textSizeClass = $derived(isAttachment ? 'text-xs' : 'text-md'); + let textSizeClass = $derived(isAttachment ? 'text-caption' : 'text-md'); let paddingClass = $derived(isAttachment ? 'px-3 py-2' : 'px-3.75 py-2.5'); let maxHeightStyle = $derived( isAttachment ? 'max-height: 6rem;' : 'max-height: var(--max-message-height);' @@ -94,7 +94,7 @@
-
+
{#if serverFavicon} @@ -124,7 +124,7 @@
{:else if isLoading}
{:else if hasContent}
{:else} - {message.content} + {message.content} {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte index df2097b5a7d9..2770f96d83dc 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte @@ -81,10 +81,10 @@ role="group" > {#if editCtx.isEditing} -
+
x
'); + + for (const el of host.querySelectorAll('input, textarea, [contenteditable]')) { + el.focus(); + expect(shouldTypeToFocus(key('a'))).toBe(false); + } + }); + + it('leaves keys inside dialogs and menus', () => { + const host = mount( + '
' + ); + + for (const button of host.querySelectorAll('button')) { + button.focus(); + expect(shouldTypeToFocus(key('r'))).toBe(false); + } + }); +}); From 36cd3aff409ae2b511c311954ed9236c1916978d Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Fri, 20 Nov 2026 14:10:06 +0100 Subject: [PATCH 32/88] server: add --ui-mcp-proxy-allow-private-urls (#32633) --- common/arg.cpp | 10 +++++++++- common/common.h | 1 + tools/server/README.md | 5 +++-- tools/server/server-cors-proxy.h | 17 +++++++---------- tools/server/server.cpp | 8 +++++--- tools/server/tests/unit/test_proxy.py | 6 +++--- tools/server/tests/unit/test_security.py | 2 +- tools/server/tests/utils.py | 6 +++--- 8 files changed, 32 insertions(+), 23 deletions(-) diff --git a/common/arg.cpp b/common/arg.cpp index 192f70607f1e..a638237672bd 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -3420,12 +3420,20 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--ui-mcp-proxy", "--webui-mcp-proxy"}, {"--no-ui-mcp-proxy", "--no-webui-mcp-proxy"}, - "experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)\n" + "experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused unless --ui-mcp-proxy-allow-private-urls is set - do not enable in untrusted environments (default: disabled)\n" "note: for security reasons, this will limit --cors-origins to localhost by default", [](common_params & params, bool value) { params.ui_mcp_proxy = value; } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY")); + add_opt(common_arg( + {"--ui-mcp-proxy-allow-private-urls"}, + "allow the MCP CORS proxy to reach local or private addresses (e.g. MCP servers on localhost or LAN) - anyone who can reach the proxy can then reach your local network (default: disabled, only public addresses)\n" + "note: only has effect with --ui-mcp-proxy", + [](common_params & params) { + params.ui_mcp_proxy_allow_private_urls = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY_ALLOW_PRIVATE_URLS")); add_opt(common_arg( {"--tools"}, "TOOL1,TOOL2,...", "experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)\n" diff --git a/common/common.h b/common/common.h index e16bee7c1629..a8e89ed2dd65 100644 --- a/common/common.h +++ b/common/common.h @@ -702,6 +702,7 @@ struct common_params { // UI configs bool ui = true; bool ui_mcp_proxy = false; + bool ui_mcp_proxy_allow_private_urls = false; // allow the MCP CORS proxy to reach local or private addresses std::string ui_config_json; // "advanced" endpoints are disabled by default for better security diff --git a/tools/server/README.md b/tools/server/README.md index 278518dce75c..1f6553389d61 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -202,7 +202,8 @@ For the full list of features, please refer to [server's changelog](https://gith | `--api-prefix PREFIX` | prefix path the server serves from, without the trailing slash (default: )
(env: LLAMA_ARG_API_PREFIX) | | `--ui-config, --webui-config JSON` | JSON that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG) | | `--ui-config-file, --webui-config-file PATH` | JSON file that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG_FILE) | -| `--ui-mcp-proxy, --webui-mcp-proxy, --no-ui-mcp-proxy, --no-webui-mcp-proxy` | experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_UI_MCP_PROXY) | +| `--ui-mcp-proxy, --webui-mcp-proxy, --no-ui-mcp-proxy, --no-webui-mcp-proxy` | experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused unless --ui-mcp-proxy-allow-private-urls is set - do not enable in untrusted environments (default: disabled)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_UI_MCP_PROXY) | +| `--ui-mcp-proxy-allow-private-urls` | allow the MCP CORS proxy to reach local or private addresses (e.g. MCP servers on localhost or LAN) - anyone who can reach the proxy can then reach your local network (default: disabled, only public addresses)
note: only has effect with --ui-mcp-proxy
(env: LLAMA_ARG_UI_MCP_PROXY_ALLOW_PRIVATE_URLS) | | `--tools TOOL1,TOOL2,...` | experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)
specify "all" to enable all tools
available tools: read_file, file_glob_search, grep_search, exec_shell_command, write_file, edit_file, get_info
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_TOOLS) | | `--tools-runtime OPTION` | experimental: run tools in a separate runtime environment (default: none, use host environment)
available options:
'docker:', 'podman:': spin up a new container and reuse it for all invocations, clean up on server exit
'docker-container:', 'podman-container:': use an existing container by ID, won't stop on server exit
'ssh:': run tools on a remote POSIX host over SSH, key-based auth and a trusted host key are required

(env: LLAMA_ARG_TOOLS_RUNTIME) | | `--allow-unauthenticated-tools` | allow server tools, MCP servers or MCP proxy on a non-loopback address without an API key - only for trusted networks (default: disabled)
(env: LLAMA_ARG_ALLOW_UNAUTHENTICATED_TOOLS) | @@ -393,7 +394,7 @@ Every server is spawned once at startup to list its tools, then stopped, and res The child process runs with the same privileges as the server, so only declare commands you trust. As with `--tools`, `--cors-origins` then defaults to `localhost`. -Note: `--ui-mcp-proxy` is unrelated, it only lets Llama Chat reach public MCP servers that do not send CORS headers. It refuses local and private addresses (loopback, LAN, link-local); connect to those from Llama Chat directly. +Note: `--ui-mcp-proxy` is unrelated, it only lets Llama Chat reach public MCP servers that do not send CORS headers. By default it refuses local and private addresses (loopback, LAN, link-local); either connect to those from Llama Chat directly (the MCP server must send CORS headers), or add `--ui-mcp-proxy-allow-private-urls`. Any server written against the [MCP specification](https://modelcontextprotocol.io) works as is, whether it uses an official SDK or not: the transport is one JSON-RPC message per line on stdio, so a script wrapping an existing program is a valid server too. diff --git a/tools/server/server-cors-proxy.h b/tools/server/server-cors-proxy.h index 41d00740416f..7fc87c6676f8 100644 --- a/tools/server/server-cors-proxy.h +++ b/tools/server/server-cors-proxy.h @@ -20,7 +20,7 @@ static std::string proxy_header_to_lower(std::string header) { return header; } -static server_http_res_ptr proxy_request(const server_http_req & req, std::string method) { +static server_http_res_ptr proxy_request(const server_http_req & req, std::string method, bool allow_private_urls) { std::string target_url = req.get_param("url"); common_http_url parsed_url = common_http_parse_url(target_url); @@ -70,8 +70,7 @@ static server_http_res_ptr proxy_request(const server_http_req & req, std::strin req.should_stop, 600, // timeout_read (default to 10 minutes) 600, // timeout_write (default to 10 minutes) - // test-only escape hatch - server_resolve_public_addr(parsed_url.host, !common_get_env("LLAMA_SERVER_DEBUG_PROXY_ALLOW_PRIVATE").empty()) + server_resolve_public_addr(parsed_url.host, allow_private_urls) ); // route redirects back through the proxy, so each hop is checked @@ -86,10 +85,8 @@ static server_http_res_ptr proxy_request(const server_http_req & req, std::strin return proxy; } -static server_http_context::handler_t proxy_handler_post = [](const server_http_req & req) -> server_http_res_ptr { - return proxy_request(req, "POST"); -}; - -static server_http_context::handler_t proxy_handler_get = [](const server_http_req & req) -> server_http_res_ptr { - return proxy_request(req, "GET"); -}; +static server_http_context::handler_t proxy_make_handler(const std::string & method, bool allow_private_urls) { + return [method, allow_private_urls](const server_http_req & req) -> server_http_res_ptr { + return proxy_request(req, method, allow_private_urls); + }; +} diff --git a/tools/server/server.cpp b/tools/server/server.cpp index d14978286224..fabf0a0413c8 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -281,9 +281,11 @@ static bool server_setup_features( // CORS proxy (EXPERIMENTAL, only used by Llama Chat for MCP) if (params.ui_mcp_proxy) { - ctx_http.get ("/cors-proxy", ex_wrapper(proxy_handler_get)); - ctx_http.post("/cors-proxy", ex_wrapper(proxy_handler_post)); - warn_names.push_back("MCP proxy (experimental)"); + ctx_http.get ("/cors-proxy", ex_wrapper(proxy_make_handler("GET", params.ui_mcp_proxy_allow_private_urls))); + ctx_http.post("/cors-proxy", ex_wrapper(proxy_make_handler("POST", params.ui_mcp_proxy_allow_private_urls))); + warn_names.push_back(params.ui_mcp_proxy_allow_private_urls + ? "MCP proxy (experimental, local and private addresses allowed)" + : "MCP proxy (experimental)"); } else { ctx_http.get ("/cors-proxy", ex_wrapper(res_403)); ctx_http.post("/cors-proxy", ex_wrapper(res_403)); diff --git a/tools/server/tests/unit/test_proxy.py b/tools/server/tests/unit/test_proxy.py index 58fd8c824826..24d9aeacc7c3 100644 --- a/tools/server/tests/unit/test_proxy.py +++ b/tools/server/tests/unit/test_proxy.py @@ -35,7 +35,7 @@ def test_mcp_proxy(): def test_mcp_proxy_custom_port(): global server server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() # try getting the server's models API via the proxy @@ -61,7 +61,7 @@ def log_message(self, format, *args): try: global server server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() res = server.make_request("POST", f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/", data={}) @@ -116,7 +116,7 @@ def log_message(self, format, *args): try: global server server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() url = server.make_url(f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/start") diff --git a/tools/server/tests/unit/test_security.py b/tools/server/tests/unit/test_security.py index 31082cc70c2d..242a8957aab8 100644 --- a/tools/server/tests/unit/test_security.py +++ b/tools/server/tests/unit/test_security.py @@ -314,7 +314,7 @@ def log_message(self, format, *args): server = ServerPreset.tinyllama2() server.api_key = TEST_API_KEY server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() res = server.make_request("GET", f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/capture", headers={ diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index f18b566aa879..6a30e02d1247 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -126,7 +126,7 @@ class ServerProcess: no_cache_idle_slots: bool = False log_path: str | None = None ui_mcp_proxy: bool = False - debug_proxy_allow_private: bool = False # test-only: lets the CORS proxy reach local servers + ui_mcp_proxy_allow_private_urls: bool = False media_allow_private_urls: bool = False allow_unauthenticated_tools: bool = False backend_sampling: bool = False @@ -155,8 +155,6 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: **os.environ, "LLAMA_SERVER_DEBUG_FAKE_TIMING": "1", } - if self.debug_proxy_allow_private: - env["LLAMA_SERVER_DEBUG_PROXY_ALLOW_PRIVATE"] = "1" if self.llama_cache is not None: env["LLAMA_CACHE"] = self.llama_cache elif "LLAMA_CACHE" not in os.environ: @@ -313,6 +311,8 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.append("--no-cache-idle-slots") if self.ui_mcp_proxy: server_args.append("--ui-mcp-proxy") + if self.ui_mcp_proxy_allow_private_urls: + server_args.append("--ui-mcp-proxy-allow-private-urls") if self.media_allow_private_urls: server_args.append("--media-allow-private-urls") if self.allow_unauthenticated_tools: From 5f837145d86ecc62333f3b83835c64275fdaa90e Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Fri, 20 Nov 2026 14:21:58 +0100 Subject: [PATCH 33/88] server: add more audio tests (#32579) --- tools/server/tests/requirements.txt | 1 + .../tests/unit/test_compat_oai_speech.py | 76 ++++ .../unit/test_compat_oai_transcription.py | 144 ++++++ tools/server/tests/unit/test_realtime.py | 410 ++++++++++++++++++ tools/server/tests/utils.py | 50 +++ 5 files changed, 681 insertions(+) create mode 100644 tools/server/tests/unit/test_compat_oai_transcription.py create mode 100644 tools/server/tests/unit/test_realtime.py diff --git a/tools/server/tests/requirements.txt b/tools/server/tests/requirements.txt index 1a490b5cc236..52c3f6249572 100644 --- a/tools/server/tests/requirements.txt +++ b/tools/server/tests/requirements.txt @@ -6,4 +6,5 @@ numpy~=2.5.4; python_version >= "3.14" openai~=2.14.0 prometheus-client~=0.20.0 requests~=2.32.3 +websockets~=15.0 wget~=3.2 diff --git a/tools/server/tests/unit/test_compat_oai_speech.py b/tools/server/tests/unit/test_compat_oai_speech.py index 888942f02ba9..e5b578c894f0 100644 --- a/tools/server/tests/unit/test_compat_oai_speech.py +++ b/tools/server/tests/unit/test_compat_oai_speech.py @@ -1,3 +1,4 @@ +import base64 import pytest import requests import struct @@ -135,3 +136,78 @@ def test_speech_router(): server = ServerPreset.router() server.start() assert_wav(post_audio("/v1/audio/speech", model=model)) + + +# +# tts only model, with voice cloning +# + +def pocket_tts(path: str = "/v1/audio/speech", **extra) -> requests.Response: + body = {"input": "Hello there.", "seed": 42, "n_predict": 8, **extra} + return requests.post(server.make_url(path), json=body, timeout=DEFAULT_REQUEST_TIMEOUT) + + +def test_tts_only(): + global server + server = ServerPreset.tinypockettts() + server.start() + res = server.make_request("GET", "/props") + assert not res.body.get("voices") # this slice has no predefined voices + res = server.make_request("GET", "/v1/models") + assert res.body["data"][0]["architecture"]["output_modalities"] == ["audio"] + res = pocket_tts() + assert_wav(res) + assert res.content == pocket_tts().content + + +def test_tts_only_speaker_ref(): + global server + server = ServerPreset.tinypockettts() + server.start() + ref_a = make_wav(seconds=2.0, rate=24000, freq=220) + ref_b = make_wav(seconds=2.0, rate=24000, freq=440) + res = pocket_tts("/tts", speaker_ref_b64=base64.b64encode(ref_a).decode()) + assert_wav(res) + assert res.content != pocket_tts("/tts").content + assert res.content != pocket_tts("/tts", speaker_ref_b64=base64.b64encode(ref_b).decode()).content + # the same reference as an uploaded file + fields = {"input": (None, "Hello there."), "seed": (None, "42"), "n_predict": (None, "8"), "speaker_ref": ("ref.wav", ref_a)} + res_file = requests.post(server.make_url("/tts"), files=fields, timeout=DEFAULT_REQUEST_TIMEOUT) + assert res_file.content == res.content + # /v1/audio/speech passes it through + assert pocket_tts(speaker_ref_b64=base64.b64encode(ref_a).decode()).content == res.content + + +@pytest.mark.parametrize("speaker_ref_b64,message", [ + ("!!!", "not valid base64"), + (base64.b64encode(b"not an audio file").decode(), "failed to decode"), +]) +def test_tts_only_invalid_speaker_ref(speaker_ref_b64: str, message: str): + global server + server = ServerPreset.tinypockettts() + server.start() + res = pocket_tts("/tts", speaker_ref_b64=speaker_ref_b64) + assert res.status_code == 400 + assert message in res.json()["error"]["message"] + + +def test_tts_only_end_of_speech(): + global server + server = ServerPreset.tinypockettts() + server.start() + # the end-of-speech head stops the generation before n_predict + res = pocket_tts(n_predict=16) + assert_wav(res) + assert res.content == pocket_tts(n_predict=1000).content + + +@pytest.mark.parametrize("path", ["/v1/chat/completions", "/v1/audio/transcriptions"]) +def test_tts_only_no_text_output(path: str): + global server + server = ServerPreset.tinypockettts() + server.start() + if path == "/v1/audio/transcriptions": + res = requests.post(server.make_url(path), files={"file": ("audio.wav", make_wav())}, timeout=DEFAULT_REQUEST_TIMEOUT) + else: + res = requests.post(server.make_url(path), json={"messages": [{"role": "user", "content": "hello"}]}, timeout=DEFAULT_REQUEST_TIMEOUT) + assert res.status_code == 501 diff --git a/tools/server/tests/unit/test_compat_oai_transcription.py b/tools/server/tests/unit/test_compat_oai_transcription.py new file mode 100644 index 000000000000..eb3954282288 --- /dev/null +++ b/tools/server/tests/unit/test_compat_oai_transcription.py @@ -0,0 +1,144 @@ +import base64 +import json +import pytest +import requests +from utils import * + +server: ServerProcess + +MP3_PATH = os.path.join(os.path.dirname(__file__), "../../../mtmd/test-2.mp3") + +# full random sampling, so that the output depends on the audio +SAMPLING_RANDOM = {"temperature": 1.0, "top_k": 0, "top_p": 1.0, "min_p": 0.0, "seed": 42} + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinylfm3omni() + server.jinja = True + server.reasoning = "off" + + +def post_transcription(path: str = "/v1/audio/transcriptions", audio: bytes | None = None, filename: str = "audio.wav", **fields) -> requests.Response: + data = {"max_tokens": "8", **fields} + files = {"file": (filename, make_wav() if audio is None else audio)} + return requests.post(server.make_url(path), data=data, files=files, timeout=DEFAULT_REQUEST_TIMEOUT) + + +def chat_with_audio(audio: bytes, fmt: str = "wav", extra: dict | None = None) -> str: + res = server.make_request("POST", "/v1/chat/completions", data={ + "max_tokens": 8, + "messages": [{"role": "user", "content": [ + {"type": "input_audio", "input_audio": {"data": base64.b64encode(audio).decode(), "format": fmt}}, + ]}], + **(extra or {}), + }) + assert res.status_code == 200, res.body + return res.body["choices"][0]["message"]["content"] + + +@pytest.mark.parametrize("path", ["/v1/audio/transcriptions", "/audio/transcriptions"]) +def test_transcription(path: str): + server.start() + res = post_transcription(path) + assert res.status_code == 200 + body = res.json() + assert body["type"] == "transcript.text.done" + assert len(body["text"]) > 0 + assert 0 < body["usage"]["output_tokens"] <= 8 + assert body["usage"]["input_tokens"] > 0 + + +def test_transcription_mp3(): + server.start() + with open(MP3_PATH, "rb") as f: + res = post_transcription(audio=f.read(), filename="audio.mp3") + assert res.status_code == 200 + assert len(res.json()["text"]) > 0 + + +def test_transcription_stream(): + server.start() + res = post_transcription(stream="true") + assert res.status_code == 200 + lines = [line[len("data: "):] for line in res.text.splitlines() if line.startswith("data: ")] + assert lines[-1] == "[DONE]" + events = [json.loads(line) for line in lines[:-1]] + assert len(events) > 1 + assert all(ev["type"] == "transcript.text.delta" for ev in events[:-1]) + assert events[-1]["type"] == "transcript.text.done" + text = "".join(ev["delta"] for ev in events[:-1]) + assert text == events[-1]["text"] + assert text == post_transcription().json()["text"] + + +def test_transcription_language(): + server.start() + # the LFM3 template puts the language in the system prompt + n_default = post_transcription().json()["usage"]["input_tokens"] + n_fr = post_transcription(language="fr").json()["usage"]["input_tokens"] + assert n_fr > n_default + + +@pytest.mark.parametrize("fields,files,message", [ + ({"response_format": "text"}, None, "response_format"), + ({}, {"file": ("audio.wav", b"not an audio file")}, None), + ({}, {"other": ("audio.wav", b"")}, None), +]) +def test_transcription_invalid_request(fields: dict, files: dict | None, message: str | None): + server.start() + res = requests.post(server.make_url("/v1/audio/transcriptions"), data={"max_tokens": "8", **fields}, + files=files or {"file": ("audio.wav", make_wav())}, timeout=DEFAULT_REQUEST_TIMEOUT) + assert res.status_code == 400 + if message: + assert message in res.json()["error"]["message"] + + +@pytest.mark.parametrize("preset", [ + "tinyllama2", # no audio input + "tinyvoxtralrt", # live transcription only +]) +def test_transcription_not_supported(preset: str): + global server + server = getattr(ServerPreset, preset)() + server.start() + assert post_transcription().status_code == 501 # ERROR_TYPE_NOT_SUPPORTED + + +def test_transcription_router(): + global server + model = server.model_hf_repo + server = ServerPreset.router() + server.start() + res = post_transcription(model=model) + assert res.status_code == 200 + assert res.json()["type"] == "transcript.text.done" + + +def test_chat_input_audio(): + server.start() + a = make_wav(freq=220) + b = make_wav(freq=880) + assert chat_with_audio(a, extra=SAMPLING_RANDOM) == chat_with_audio(a, extra=SAMPLING_RANDOM) + assert chat_with_audio(a, extra=SAMPLING_RANDOM) != chat_with_audio(b, extra=SAMPLING_RANDOM) + + +def test_chat_input_audio_mp3(): + server.start() + with open(MP3_PATH, "rb") as f: + assert len(chat_with_audio(f.read(), fmt="mp3")) > 0 + + +def test_chat_input_audio_no_audio_model(): + global server + server = ServerPreset.tinyllama2() + server.start() + res = server.make_request("POST", "/v1/chat/completions", data={ + "max_tokens": 8, + "messages": [{"role": "user", "content": [ + {"type": "input_audio", "input_audio": {"data": base64.b64encode(make_wav()).decode(), "format": "wav"}}, + ]}], + }) + assert res.status_code != 200 + assert "audio input is not supported" in res.body["error"]["message"] diff --git a/tools/server/tests/unit/test_realtime.py b/tools/server/tests/unit/test_realtime.py new file mode 100644 index 000000000000..5af63a98e27d --- /dev/null +++ b/tools/server/tests/unit/test_realtime.py @@ -0,0 +1,410 @@ +import base64 +import json +import time +import pytest +from websockets.exceptions import ConnectionClosed +from websockets.sync.client import connect, ClientConnection +from websockets.sync.connection import Connection +from utils import * + +server: ServerProcess + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinylfm3omni() + server.jinja = True + server.reasoning = "off" + + +def ws_connect(path: str = "/v1/realtime") -> ClientConnection: + return connect(server.make_url(path).replace("http://", "ws://", 1), max_size=None, open_timeout=DEFAULT_REQUEST_TIMEOUT) + + +def send(ws: Connection, type: str, **fields): + ws.send(json.dumps({"type": type, **fields})) + + +def send_audio(ws: Connection, pcm: bytes): + send(ws, "input_audio_buffer.append", audio=base64.b64encode(pcm).decode()) + + +def send_text(ws: Connection, text: str): + send(ws, "conversation.item.create", item={"type": "message", "role": "user", "content": [{"type": "input_text", "text": text}]}) + + +def recv(ws: Connection) -> dict: + return json.loads(ws.recv(timeout=DEFAULT_REQUEST_TIMEOUT)) + + +def recv_until(ws: Connection, type: str) -> list[dict]: + events = [] + while True: + ev = recv(ws) + events.append(ev) + if ev["type"] == type: + return events + assert ev["type"] != "error", ev + + +def recv_all(ws: Connection) -> list[dict]: + """ read events until the server closes the socket """ + events = [] + try: + while True: + events.append(recv(ws)) + except ConnectionClosed: + return events + + +def get_transcripts(events: list[dict]) -> list[tuple[str, str]]: + """ (item_id, transcript) of each completed item, checked against its deltas """ + deltas: dict[str, str] = {} + out = [] + for ev in events: + assert ev["type"] != "error", ev + if ev["type"] == "conversation.item.input_audio_transcription.delta": + deltas[ev["item_id"]] = deltas.get(ev["item_id"], "") + ev["delta"] + elif ev["type"] == "conversation.item.input_audio_transcription.completed": + assert ev["transcript"] == deltas.get(ev["item_id"], "") + out.append((ev["item_id"], ev["transcript"])) + return out + + +def session_update(ws: Connection, **session) -> dict: + send(ws, "session.update", session=session) + return recv_until(ws, "session.updated")[-1]["session"] + + +# +# live transcription +# + +LIVE_ASR = [ + # a chat model with an "asr" chat template, live only in sessions opened with ?intent=transcription + ("tinylfm3omni", "/v1/realtime?intent=transcription"), + # no chat, the text follows the audio by a few tokens + ("tinyvoxtralrt", "/v1/realtime"), +] + + +def start_live_asr(preset: str): + global server + if preset != "tinylfm3omni": + server = getattr(ServerPreset, preset)() + server.start() + + +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr(preset: str, path: str): + start_live_asr(preset) + with ws_connect(path) as ws: + session = recv(ws) + assert session["type"] == "session.created" + assert session["session"]["object"] == "realtime.transcription_session" + assert session["session"]["audio"]["input"]["format"] == {"type": "audio/pcm", "rate": 16000} + send_audio(ws, make_pcm16()) + send(ws, "input_audio_buffer.commit") + send_audio(ws, make_pcm16(freq=880)) + send(ws, "input_audio_buffer.commit", final=True) + events = recv_all(ws) + committed = [ev for ev in events if ev["type"] == "input_audio_buffer.committed"] + assert len(committed) == 1 + assert committed[0]["previous_item_id"] is None + transcripts = get_transcripts(events) + assert len(transcripts) == 2 + assert transcripts[0][0] == committed[0]["item_id"] + assert transcripts[1][0] != transcripts[0][0] + assert all(len(text) > 0 for _, text in transcripts) + + +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr_chunked_audio(preset: str, path: str): + start_live_asr(preset) + pcm = make_pcm16() + results = [] + for n_chunks in [1, 7]: + size = len(pcm) // n_chunks // 2 * 2 + with ws_connect(path) as ws: + recv(ws) + for i in range(0, len(pcm), size): + send_audio(ws, pcm[i:i + size]) + send(ws, "input_audio_buffer.commit", final=True) + results.append([text for _, text in get_transcripts(recv_all(ws))]) + assert results[0] == results[1] + + +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr_input_rate(preset: str, path: str): + start_live_asr(preset) + with ws_connect(path) as ws: + recv(ws) + send(ws, "session.update", session={"audio": {"input": {"format": {"type": "audio/pcm", "rate": 4000}}}}) + assert "between 8000 and 192000" in recv_until(ws, "error")[-1]["error"]["message"] + send(ws, "session.update", session={"audio": {"input": {"format": {"type": "audio/pcm", "rate": 24000}}}}) + assert recv_until(ws, "session.updated")[-1]["session"]["audio"]["input"]["format"]["rate"] == 24000 + send_audio(ws, make_pcm16(rate=24000)) + send(ws, "input_audio_buffer.commit", final=True) + transcripts = get_transcripts(recv_all(ws)) + assert len(transcripts) == 1 + assert len(transcripts[0][1]) > 0 + + +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr_invalid_events(preset: str, path: str): + start_live_asr(preset) + with ws_connect(path) as ws: + recv(ws) + ws.send("not json") + assert recv_until(ws, "error")[-1]["error"]["message"] == "invalid JSON" + send(ws, "response.create") + assert "unknown event type" in recv_until(ws, "error")[-1]["error"]["message"] + send(ws, "input_audio_buffer.clear") + recv_until(ws, "input_audio_buffer.cleared") + # the session still works + send_audio(ws, make_pcm16()) + send(ws, "input_audio_buffer.commit", final=True) + assert len(get_transcripts(recv_all(ws))) == 1 + + +def test_live_asr_depends_on_audio(): + # the random weights of this model give a different text for each input + start_live_asr("tinyvoxtralrt") + results = [] + for freq in [220, 880, 220]: + with ws_connect() as ws: + recv(ws) + send_audio(ws, make_pcm16(freq=freq)) + send(ws, "input_audio_buffer.commit", final=True) + results.append(get_transcripts(recv_all(ws))[0][1]) + assert results[0] != results[1] + assert results[0] == results[2] + + +@pytest.mark.parametrize("preset", ["tinypockettts", "tinyllama2"]) +def test_realtime_not_supported(preset: str): + global server + server = getattr(ServerPreset, preset)() + server.start() + with ws_connect() as ws: + events = recv_all(ws) + assert len(events) == 1 + assert events[0]["type"] == "error" + assert "does not support realtime" in events[0]["error"]["message"] + + +# +# realtime conversation +# + +def test_conversation_text(): + server.start() + with ws_connect() as ws: + session = recv(ws) + assert session["type"] == "session.created" + assert session["session"]["object"] == "realtime.session" + assert session["session"]["audio"]["output"]["format"]["rate"] > 0 + session_update(ws, output_modalities=["text"], max_output_tokens=8) + send_text(ws, "hello") + user_item = recv_until(ws, "conversation.item.done")[-1]["item"] + assert user_item["role"] == "user" + assert user_item["content"] == [{"type": "input_text", "text": "hello"}] + send(ws, "response.create") + events = recv_until(ws, "response.done") + + types = [ev["type"] for ev in events] + n_deltas = types.count("response.output_text.delta") + assert n_deltas == 8 + assert types == [ + "response.created", + "response.output_item.added", + "response.content_part.added", + *["response.output_text.delta"] * n_deltas, + "response.output_text.done", + "response.content_part.done", + "response.output_item.done", + "response.done", + ] + response = events[-1]["response"] + assert response["status"] == "completed" + assert response["id"] == events[0]["response"]["id"] + assert response["usage"]["output_tokens"] == 8 + text = "".join(ev["delta"] for ev in events if ev["type"] == "response.output_text.delta") + assert response["output"][0]["role"] == "assistant" + assert response["output"][0]["content"] == [{"type": "output_text", "text": text}] + + +def test_conversation_audio(): + server.start() + with ws_connect() as ws: + recv(ws) + session_update(ws, output_modalities=["audio"], max_output_tokens=8) + send_audio(ws, make_pcm16()) + # response.create commits the pending audio + send(ws, "response.create") + events = recv_until(ws, "response.done") + types = [ev["type"] for ev in events] + assert types[:3] == ["input_audio_buffer.committed", "conversation.item.added", "conversation.item.done"] + assert events[2]["item"]["content"] == [{"type": "input_audio"}] + assert "response.output_text.delta" not in types + audio = b"".join(base64.b64decode(ev["delta"]) for ev in events if ev["type"] == "response.output_audio.delta") + assert len(audio) > 0 and len(audio) % 2 == 0 + response = events[-1]["response"] + assert response["status"] == "completed" + assert response["output"][0]["content"][0]["type"] == "output_audio" + + +def test_conversation_multi_turn(): + server.start() + with ws_connect() as ws: + recv(ws) + session_update(ws, output_modalities=["text"], max_output_tokens=4) + send_text(ws, "hello") + recv_until(ws, "conversation.item.done") + send(ws, "response.create") + first = recv_until(ws, "response.done")[-1]["response"] + send_audio(ws, make_pcm16()) + send(ws, "input_audio_buffer.commit") + committed = recv_until(ws, "input_audio_buffer.committed")[-1] + assert committed["previous_item_id"] == first["output"][0]["id"] + send(ws, "response.create") + second = recv_until(ws, "response.done")[-1]["response"] + assert second["status"] == "completed" + assert second["id"] != first["id"] + + +def test_conversation_cancel(): + server.start() + with ws_connect() as ws: + recv(ws) + session_update(ws, output_modalities=["text"]) + send_text(ws, "hello") + send(ws, "response.create") + recv_until(ws, "response.output_text.delta") + send(ws, "response.cancel") + assert recv_until(ws, "response.done")[-1]["response"]["status"] == "cancelled" + # the session still works + send_text(ws, "hello again") + send(ws, "response.create", response={"max_output_tokens": 4}) + response = recv_until(ws, "response.done")[-1]["response"] + assert response["status"] == "completed" + assert response["usage"]["output_tokens"] == 4 + + +def test_conversation_session_update(): + server.start() + tools = [{"type": "function", "name": "get_weather", "description": "Get the weather", + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}] + with ws_connect() as ws: + recv(ws) + session = session_update(ws, instructions="Be brief.", tools=tools, tool_choice="none", max_output_tokens=16, + audio={"output": {"voice": {"id": "male"}}}) + assert session["instructions"] == "Be brief." + assert session["tools"] == tools + assert session["tool_choice"] == "none" + assert session["max_output_tokens"] == 16 + assert session["audio"]["output"]["voice"] == "male" + session = session_update(ws, max_output_tokens="inf", output_modalities=["text", "audio"]) + assert session["max_output_tokens"] == "inf" + assert session["output_modalities"] == ["text", "audio"] + + +@pytest.mark.parametrize("events,message", [ + ([{"type": "response.create"}], "commit audio or create a message first"), + ([{"type": "input_audio_buffer.commit"}], "the buffer is empty"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "assistant", "content": []}}], "only user messages"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "user", "content": [{"type": "input_image"}]}}], "unsupported content type"), + ([{"type": "conversation.item.create", "item": {"type": "function_call_output", "call_id": "x", "output": "{}"}}], "must follow the response"), + ([{"type": "session.update", "session": {"type": "foo"}}], "unknown session type"), + ([{"type": "session.update", "session": {"output_modalities": []}}], "non-empty array"), + ([{"type": "session.update", "session": {"output_modalities": ["video"]}}], "unknown modality"), + ([{"type": "session.update", "session": {"max_output_tokens": 0}}], "max_output_tokens"), + ([{"type": "session.update", "session": {"tool_choice": "maybe"}}], "tool_choice"), + ([{"type": "session.update", "session": {"audio": {"output": {"voice": "alloy"}}}}], "unknown voice"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "hi"}]}}, + {"type": "session.update", "session": {"instructions": "Be brief."}}], "cannot change after"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "hi"}]}}, + {"type": "session.update", "session": {"type": "transcription"}}], "cannot change after"), +]) +def test_conversation_invalid_events(events: list[dict], message: str): + server.start() + with ws_connect() as ws: + recv(ws) + for ev in events: + ws.send(json.dumps(ev)) + err = recv_until(ws, "error")[-1] + assert message in err["error"]["message"] + + +def test_transcription_session(): + server.start() + with ws_connect() as ws: + recv(ws) + session = session_update(ws, type="transcription", max_output_tokens=8, + audio={"input": {"transcription": {"language": "fr"}}}) + assert session["object"] == "realtime.transcription_session" + assert session["audio"]["input"]["transcription"]["language"] == "fr" + send_text(ws, "hello") + assert "not supported in a transcription session" in recv_until(ws, "error")[-1]["error"]["message"] + transcripts = [] + for freq in [440, 880]: + send_audio(ws, make_pcm16(freq=freq)) + send(ws, "input_audio_buffer.commit") + committed = recv_until(ws, "input_audio_buffer.committed")[-1] + events = recv_until(ws, "conversation.item.input_audio_transcription.completed") + transcripts += get_transcripts(events) + assert transcripts[-1][0] == committed["item_id"] + assert len(transcripts) == 2 + assert all(len(text) > 0 for _, text in transcripts) + + +# +# slot and server state +# + +@pytest.mark.parametrize("path", ["/v1/realtime", "/v1/realtime?intent=transcription"]) +def test_realtime_disconnect_frees_slot(path: str): + server.n_slots = 1 + server.start() + with ws_connect(path) as ws: + recv(ws) + send_audio(ws, make_pcm16()) + if path == "/v1/realtime": + send(ws, "response.create") + recv_until(ws, "response.output_item.added") + # the socket is closed in the middle of the session + res = server.make_request("POST", "/v1/chat/completions", data={ + "max_tokens": 4, + "messages": [{"role": "user", "content": "hello"}], + }) + assert res.status_code == 200 + + +def test_realtime_router(): + global server + model = server.model_hf_repo + server = ServerPreset.router() + server.start() + with ws_connect(f"/v1/realtime?model={model}") as ws: + assert recv(ws)["type"] == "session.created" + session_update(ws, output_modalities=["text"], max_output_tokens=4) + send_text(ws, "hello") + send(ws, "response.create") + assert recv_until(ws, "response.done")[-1]["response"]["status"] == "completed" + + +def test_realtime_sleep(): + server.sleep_idle_seconds = 1 + server.start() + start = time.time() + while not server.make_request("GET", "/props").body["is_sleeping"]: + assert time.time() - start < 10, "server did not go to sleep" + time.sleep(0.1) + # the session wakes the server up + with ws_connect() as ws: + assert recv(ws)["type"] == "session.created" + session_update(ws, output_modalities=["text"], max_output_tokens=4) + send_text(ws, "hello") + send(ws, "response.create") + assert recv_until(ws, "response.done")[-1]["response"]["status"] == "completed" diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index 6a30e02d1247..4d936aa2f495 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -5,6 +5,10 @@ import subprocess import os +import io +import math +import struct +import wave TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp") import re @@ -726,6 +730,36 @@ def tinylfm3omni() -> ServerProcess: server.seed = 42 return server + @staticmethod + def tinypockettts() -> ServerProcess: + # tts only, with voice cloning + server = ServerProcess() + server.offline = True # will be downloaded by load_all() + # mmproj is already provided by HF registry API + server.model_hf_file = None + server.model_hf_repo = "ggml-org-dev/tinyPocketTTS-for-testing-gguf:Q8_0" + server.model_alias = "tinypockettts" + server.n_ctx = 1024 + server.n_batch = 512 + server.n_slots = 1 + server.seed = 42 + return server + + @staticmethod + def tinyvoxtralrt() -> ServerProcess: + # live transcription only, no chat + server = ServerProcess() + server.offline = True # will be downloaded by load_all() + # mmproj is already provided by HF registry API + server.model_hf_file = None + server.model_hf_repo = "ggml-org-dev/tinyVoxtral-Realtime-for-testing-gguf:Q8_0" + server.model_alias = "tinyvoxtralrt" + server.n_ctx = 1024 + server.n_batch = 512 + server.n_slots = 1 + server.seed = 42 + return server + @staticmethod def router() -> ServerProcess: server = ServerProcess() @@ -832,3 +866,19 @@ def get_lan_ip(server: ServerProcess) -> str | None: def is_slow_test_allowed(): return os.environ.get("SLOW_TESTS") == "1" or os.environ.get("SLOW_TESTS") == "ON" + + +def make_pcm16(seconds: float = 1.0, rate: int = 16000, freq: float = 440.0) -> bytes: + """ sine tone as raw PCM16 mono samples """ + n = int(seconds * rate) + return struct.pack(f"<{n}h", *(int(0.3 * 32767 * math.sin(2 * math.pi * freq * i / rate)) for i in range(n))) + + +def make_wav(seconds: float = 1.0, rate: int = 16000, freq: float = 440.0) -> bytes: + buf = io.BytesIO() + with wave.open(buf, "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(rate) + w.writeframes(make_pcm16(seconds, rate, freq)) + return buf.getvalue() From c6a25fc622d322b9ad6e079e97009f7892543a4c Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 20 Nov 2026 15:06:10 +0100 Subject: [PATCH 34/88] ui: load highlight.js languages on demand (#32661) * ui: load highlight.js on first use highlight.js and every lowlight language (~900 KB raw) moved out of Llama Chat's first load into a chunk that loads with the first code block. - @ggml-org/llama-ui/code: highlightCode stays synchronous. Until highlight.js has loaded it returns the code escaped as plain text and starts the load; a $derived or $effect that called it runs again once it has loaded. New loadHighlighter() and isHighlighterLoaded(). - Markdown: rehype-highlight runs through a lazy rehype step, like KaTeX's: the first message with a code block waits for it, every other one renders in the same pass. First-load JS of the chat page: 3.47 -> 2.56 MB raw, 1.05 -> 0.75 MB gzip, 0.84 -> 0.60 MB brotli. Assisted-by: Claude (Opus 5.5 Medium) * ui: load each highlight.js language on first use highlight.js now loads one language at a time instead of all ~190 at once with the first code block: every language is its own chunk, and the core loads with the first one. - @ggml-org/llama-ui/code: highlightCode looks a language or alias up in a generated table (scripts/generate-highlight-languages.mjs), loads it with the languages it embeds (CSS and JavaScript inside HTML, say) and returns plain text until then; a $derived or $effect that called it runs again once it has loaded. Auto-detection picks among lowlight's 37 common languages, loaded the first time something auto-detects. New loadHighlightLanguages(), isHighlightLanguageLoaded(), resolveHighlightLanguage() and getLoadedHighlightLanguages() replace loadHighlighter() and isHighlighterLoaded(). - Markdown: rehypeLazyHighlight highlights with lowlight's core and the languages a message uses, waiting only for one it is the first to use. rehype-highlight is no longer in the pipeline, since it bundles lowlight's common languages. First-load JS of the chat page stays at 2.58 MB raw, 0.76 MB gzip, 0.61 MB brotli: no highlight.js code, only the 14 KB language table. The first code block now loads its language (1-12 KB for most) and the 20 KB core instead of 900 KB. Assisted-by: Claude (Opus 5.5 Medium) * ui: name the code-block class names and shell language as constants Assisted-by: Claude (Opus 5.5 Medium) --- .../MarkdownContent/markdown-processor.ts | 10 +- .../plugins/rehype/code-block-utils.ts | 5 +- .../plugins/rehype/enhance-code-blocks.ts | 6 +- .../plugins/rehype/lazy-highlight.ts | 149 ++++++ .../plugins/rehype/lowlight-core.ts | 3 + .../plugins/rehype/pre-transform.ts | 3 +- ui/apps/chat/src/lib/utils/code.ts | 9 +- ui/apps/chat/src/lib/utils/index.ts | 2 + .../chat/tests/unit/agentic-hotpath.bench.ts | 9 +- ui/apps/chat/tests/unit/code.test.ts | 11 +- .../chat/tests/unit/lazy-highlight.test.ts | 117 +++++ ui/lib/ui/README.md | 8 +- .../scripts/generate-highlight-languages.mjs | 98 ++++ .../src/lib/constants/code-block.constants.ts | 10 + ui/lib/ui/src/lib/index.ts | 2 +- ui/lib/ui/src/lib/utils/code.ts | 192 +++++-- .../ui/src/lib/utils/highlight-languages.ts | 474 ++++++++++++++++++ ui/lib/ui/src/lib/utils/index.ts | 9 +- 18 files changed, 1069 insertions(+), 48 deletions(-) create mode 100644 ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lazy-highlight.ts create mode 100644 ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lowlight-core.ts create mode 100644 ui/apps/chat/tests/unit/lazy-highlight.test.ts create mode 100644 ui/lib/ui/scripts/generate-highlight-languages.mjs create mode 100644 ui/lib/ui/src/lib/utils/highlight-languages.ts diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts index aed4b93e50d0..3f329baa6978 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts @@ -13,6 +13,7 @@ import { rehypeEnhanceMermaidBlocks } from './plugins/rehype/enhance-mermaid-blo import { rehypeEnhanceSvgBlocks } from './plugins/rehype/enhance-svg-blocks'; import { rehypeEnhanceTables } from './plugins/rehype/enhance-tables'; import { rehypeFileBadge } from './plugins/rehype/file-badge'; +import { rehypeLazyHighlight } from './plugins/rehype/lazy-highlight'; import { rehypeLazyKatex } from './plugins/rehype/lazy-katex'; import { rehypeMermaidPre } from './plugins/rehype/mermaid-pre'; import { rehypeRtlSupport } from './plugins/rehype/rehype-rtl-support'; @@ -23,9 +24,7 @@ import { remarkLiteralHtml } from './plugins/remark/literal-html'; import { FileTypeText } from '#lib/enums/files.enums.ts'; import type { DatabaseMessageExtra } from '#lib/types/database.js'; import type { Root as HastRoot } from 'hast'; -import { all as lowlightAll } from 'lowlight'; import type { Root as MdastRoot } from 'mdast'; -import rehypeHighlight from 'rehype-highlight'; import rehypeStringify from 'rehype-stringify'; import { remark } from 'remark'; import remarkBreaks from 'remark-breaks'; @@ -75,10 +74,9 @@ function buildPipeline({ } const pipeline = proc - .use(rehypeHighlight, { - aliases: { [FileTypeText.XML]: [FileTypeText.SVELTE, FileTypeText.VUE] }, - languages: lowlightAll - }) // Add syntax highlighting + .use(rehypeLazyHighlight, { + aliases: { [FileTypeText.XML]: [FileTypeText.SVELTE, FileTypeText.VUE] } + }) // Add syntax highlighting, loading highlight.js with the first message that has a code block .use(rehypeRestoreTableHtml) // Restore limited HTML (e.g.
,
    ) inside Markdown tables .use(rehypeEnhanceTables) // Wrap tables in a horizontal scroll container .use(rehypeEnhanceLinks) // Add target="_blank" to links diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/code-block-utils.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/code-block-utils.ts index 771235089d87..2070b9fd533c 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/code-block-utils.ts +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/code-block-utils.ts @@ -4,6 +4,7 @@ */ import { + CODE_BLOCK, CODE_BLOCK_CLASS, CODE_ICON_SVG, COPY_ICON_SVG, @@ -100,7 +101,9 @@ export function createSourceView( ): Element { const code: Element = codeElement ?? { children: [{ type: 'text', value: source }], - properties: { className: ['hljs', `language-${language}`] }, + properties: { + className: [CODE_BLOCK_CLASS.HLJS, `${CODE_BLOCK.LANGUAGE_CLASS_PREFIX}${language}`] + }, tagName: 'code', type: 'element' }; diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/enhance-code-blocks.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/enhance-code-blocks.ts index 5c1b2094f34b..60932a246f70 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/enhance-code-blocks.ts +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/enhance-code-blocks.ts @@ -17,7 +17,7 @@ import { createWrapper, generateBlockId } from './code-block-utils'; -import { CODE_BLOCK_CLASS, MARKDOWN_DATA_ATTRS } from '#lib/constants/index.ts'; +import { CODE_BLOCK, CODE_BLOCK_CLASS, MARKDOWN_DATA_ATTRS } from '#lib/constants/index.ts'; import type { Element, ElementContent, Root } from 'hast'; import type { Plugin } from 'unified'; import { visit } from 'unist-util-visit'; @@ -34,8 +34,8 @@ function extractLanguage(codeElement: Element): string { if (!Array.isArray(className)) return 'text'; for (const cls of className) { - if (typeof cls === 'string' && cls.startsWith('language-')) { - return cls.replace('language-', ''); + if (typeof cls === 'string' && cls.startsWith(CODE_BLOCK.LANGUAGE_CLASS_PREFIX)) { + return cls.slice(CODE_BLOCK.LANGUAGE_CLASS_PREFIX.length); } } diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lazy-highlight.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lazy-highlight.ts new file mode 100644 index 000000000000..fa79294b2b55 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lazy-highlight.ts @@ -0,0 +1,149 @@ +/** + * Rehype plugin that highlights code blocks like rehype-highlight, loading highlight.js and each language only when a + * message has a block in it. + * + * Only `
    ` blocks with a language class (`language-ts`, `lang-ts`) are highlighted; `no-highlight` opts a
    + * block out, and a language highlight.js lacks is left plain. rehype-highlight itself is not used: it bundles
    + * lowlight's common languages, which would load all at once.
    + */
    +
    +import { CODE_BLOCK, CODE_BLOCK_CLASS } from '#lib/constants/index.ts';
    +import {
    +	getLoadedHighlightLanguages,
    +	loadHighlightLanguages,
    +	resolveHighlightLanguage
    +} from '#lib/utils/code.ts';
    +import type { Element, ElementContent, Root } from 'hast';
    +import type { Plugin } from 'unified';
    +import { visit } from 'unist-util-visit';
    +
    +type Lowlight = ReturnType<(typeof import('./lowlight-core'))['createLowlight']>;
    +
    +export interface LazyHighlightOptions {
    +	/** Extra aliases per language, as rehype-highlight takes them: `{ xml: ['svelte', 'vue'] }`. */
    +	aliases?: Record;
    +}
    +
    +interface CodeBlock {
    +	node: Element;
    +	/** The highlight.js language to use, or undefined for one it lacks. */
    +	name: string | undefined;
    +}
    +
    +let lowlight: Lowlight | undefined;
    +let lowlightLoading: Promise | undefined;
    +
    +const registered = new Set();
    +
    +// the language a code element's class names, false for `no-highlight`, as rehype-highlight reads it
    +function classLanguage(node: Element): string | false | undefined {
    +	const list = node.properties?.className;
    +
    +	if (!Array.isArray(list)) return undefined;
    +
    +	let name: string | undefined;
    +
    +	for (const item of list) {
    +		const value = String(item);
    +
    +		if ((CODE_BLOCK.NO_HIGHLIGHT_CLASSES as readonly string[]).includes(value)) return false;
    +
    +		for (const prefix of [CODE_BLOCK.LANG_CLASS_PREFIX, CODE_BLOCK.LANGUAGE_CLASS_PREFIX]) {
    +			if (!name && value.startsWith(prefix)) name = value.slice(prefix.length);
    +		}
    +	}
    +
    +	return name;
    +}
    +
    +function textContent(node: ElementContent | Element): string {
    +	if (node.type === 'text') return node.value;
    +
    +	if (node.type !== 'element') return '';
    +
    +	return node.children.map(textContent).join('');
    +}
    +
    +function loadLowlight(): Promise {
    +	lowlightLoading ??= import('./lowlight-core').then(
    +		({ createLowlight }) => (lowlight = createLowlight()),
    +		(error) => {
    +			lowlightLoading = undefined;
    +
    +			throw error;
    +		}
    +	);
    +
    +	return lowlightLoading;
    +}
    +
    +// registers the languages highlightCode's loader has loaded with lowlight, as highlight.js ships them
    +function registerLoadedLanguages(target: Lowlight): void {
    +	for (const [name, definition] of Object.entries(getLoadedHighlightLanguages())) {
    +		if (registered.has(name)) continue;
    +
    +		target.register(name, definition);
    +		registered.add(name);
    +	}
    +}
    +
    +function highlightBlocks(target: Lowlight, blocks: CodeBlock[]): void {
    +	for (const { name, node } of blocks) {
    +		const className = Array.isArray(node.properties.className)
    +			? node.properties.className
    +			: (node.properties.className = []);
    +
    +		if (!className.includes(CODE_BLOCK_CLASS.HLJS)) className.unshift(CODE_BLOCK_CLASS.HLJS);
    +
    +		if (!name || !registered.has(name)) continue;
    +
    +		const result = target.highlight(name, textContent(node));
    +
    +		if (result.children.length > 0) node.children = result.children as ElementContent[];
    +	}
    +}
    +
    +// synchronous when there is no code block or its languages have loaded, so a message waits only for a language it
    +// is the first to use, and every other one renders in the same pass as before
    +export const rehypeLazyHighlight: Plugin<[LazyHighlightOptions?], Root> = (options = {}) => {
    +	const extraAliases = new Map();
    +
    +	for (const [language, aliases] of Object.entries(options.aliases ?? {})) {
    +		for (const alias of [aliases].flat()) extraAliases.set(alias.toLowerCase(), language);
    +	}
    +
    +	return (tree) => {
    +		const blocks: CodeBlock[] = [];
    +
    +		visit(tree, 'element', (node: Element, _, parent) => {
    +			if (node.tagName !== 'code' || parent?.type !== 'element' || parent.tagName !== 'pre') {
    +				return;
    +			}
    +
    +			const language = classLanguage(node);
    +
    +			if (!language) return;
    +
    +			const key = language.toLowerCase();
    +
    +			blocks.push({ name: resolveHighlightLanguage(extraAliases.get(key) ?? key), node });
    +		});
    +
    +		if (!blocks.length) return;
    +
    +		const names = [
    +			...new Set(blocks.map((block) => block.name).filter((name) => name !== undefined))
    +		];
    +
    +		if (lowlight && names.every((name) => registered.has(name))) {
    +			highlightBlocks(lowlight, blocks);
    +
    +			return;
    +		}
    +
    +		return Promise.all([loadLowlight(), loadHighlightLanguages(names)]).then(([target]) => {
    +			registerLoadedLanguages(target);
    +			highlightBlocks(target, blocks);
    +		});
    +	};
    +};
    diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lowlight-core.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lowlight-core.ts
    new file mode 100644
    index 000000000000..86a9bdf08306
    --- /dev/null
    +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lowlight-core.ts
    @@ -0,0 +1,3 @@
    +// lowlight without its bundled language sets, for lazy-highlight.ts to load with the first code block: a static
    +// re-export of createLowlight alone lets the build drop lowlight's `common` and `all`
    +export { createLowlight } from 'lowlight';
    diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/pre-transform.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/pre-transform.ts
    index af45ff0aa082..309ad9bd936d 100644
    --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/pre-transform.ts
    +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/pre-transform.ts
    @@ -1,3 +1,4 @@
    +import { CODE_BLOCK } from '#lib/constants/index.ts';
     import type { Element, ElementContent, Root, Text } from 'hast';
     import type { Plugin } from 'unified';
     import { visit } from 'unist-util-visit';
    @@ -50,7 +51,7 @@ export function createPreTransform(
     	contentGuard?: (text: string) => boolean
     ): Plugin<[], Root> {
     	const codeClasses = (Array.isArray(languages) ? languages : [languages]).map(
    -		(language) => `language-${language}`
    +		(language) => `${CODE_BLOCK.LANGUAGE_CLASS_PREFIX}${language}`
     	);
     
     	return () => {
    diff --git a/ui/apps/chat/src/lib/utils/code.ts b/ui/apps/chat/src/lib/utils/code.ts
    index cc9eba2d3f23..be556c3fcc73 100644
    --- a/ui/apps/chat/src/lib/utils/code.ts
    +++ b/ui/apps/chat/src/lib/utils/code.ts
    @@ -1,6 +1,13 @@
     import { CODE_BLOCK, NEWLINE } from '#lib/constants/index.ts';
     
    -export { highlightCode, trimCodePadding } from '@ggml-org/llama-ui/code';
    +export {
    +	getLoadedHighlightLanguages,
    +	highlightCode,
    +	isHighlightLanguageLoaded,
    +	loadHighlightLanguages,
    +	resolveHighlightLanguage,
    +	trimCodePadding
    +} from '@ggml-org/llama-ui/code';
     
     export interface IncompleteCodeBlock {
     	language: string;
    diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts
    index 61c202ab0c06..1f1d46844f1b 100644
    --- a/ui/apps/chat/src/lib/utils/index.ts
    +++ b/ui/apps/chat/src/lib/utils/index.ts
    @@ -33,6 +33,8 @@ export {
     // Code
     export {
     	highlightCode,
    +	isHighlightLanguageLoaded,
    +	loadHighlightLanguages,
     	detectIncompleteCodeBlock,
     	splitGluedClosingCodeFences,
     	trimCodePadding,
    diff --git a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts
    index 685ccdf686ea..c46f3fe4bf68 100644
    --- a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts
    +++ b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts
    @@ -7,7 +7,11 @@
     // Run: npx vitest bench --project=unit tests/unit/agentic-hotpath.bench.ts
     
     import { classifyToolResult, parseToolResultWithMedia } from '#lib/utils/agentic.ts';
    -import { detectIncompleteCodeBlock, highlightCode } from '#lib/utils/code.ts';
    +import {
    +	detectIncompleteCodeBlock,
    +	highlightCode,
    +	loadHighlightLanguages
    +} from '#lib/utils/code.ts';
     import { computeLineDiff } from '#lib/utils/compute-line-diff.ts';
     import { preprocessLaTeX } from '#lib/utils/latex-protection.ts';
     import { parsePartialJsonArgs } from '#lib/utils/parse-partial-json-args.ts';
    @@ -228,6 +232,9 @@ describe('parsePartialJsonArgs', () => {
     
     // --- F / I: highlight.js ---------------------------------------------------
     
    +// highlightCode returns plain text until highlight.js has loaded
    +await loadHighlightLanguages();
    +
     describe('highlightCode', () => {
     	bench('short bash command (title row, per token)', () => {
     		highlightCode('grep -rn "foo" src/ | head -50', 'bash');
    diff --git a/ui/apps/chat/tests/unit/code.test.ts b/ui/apps/chat/tests/unit/code.test.ts
    index 2ecaf69f018e..31f0c1846379 100644
    --- a/ui/apps/chat/tests/unit/code.test.ts
    +++ b/ui/apps/chat/tests/unit/code.test.ts
    @@ -1,5 +1,12 @@
    -import { highlightCode, splitGluedClosingCodeFences, trimCodePadding } from '#lib/utils/code.ts';
    -import { describe, expect, it } from 'vitest';
    +import {
    +	highlightCode,
    +	loadHighlightLanguages,
    +	splitGluedClosingCodeFences,
    +	trimCodePadding
    +} from '#lib/utils/code.ts';
    +import { beforeAll, describe, expect, it } from 'vitest';
    +
    +beforeAll(() => loadHighlightLanguages());
     
     describe('trimCodePadding', () => {
     	it('removes a single leading newline', () => {
    diff --git a/ui/apps/chat/tests/unit/lazy-highlight.test.ts b/ui/apps/chat/tests/unit/lazy-highlight.test.ts
    new file mode 100644
    index 000000000000..f766706c2387
    --- /dev/null
    +++ b/ui/apps/chat/tests/unit/lazy-highlight.test.ts
    @@ -0,0 +1,117 @@
    +import { rehypeLazyHighlight } from '#lib/components/app/content/MarkdownContent/plugins/rehype/lazy-highlight.ts';
    +import {
    +	highlightCode,
    +	isHighlightLanguageLoaded,
    +	loadHighlightLanguages,
    +	resolveHighlightLanguage
    +} from '#lib/utils/code.ts';
    +import type { Root } from 'hast';
    +import rehypeStringify from 'rehype-stringify';
    +import { remark } from 'remark';
    +import remarkRehype from 'remark-rehype';
    +import { describe, expect, it } from 'vitest';
    +
    +// one file, so these run in order against one fresh loader: nothing has loaded when it starts
    +describe('highlightCode before its language loads', () => {
    +	it('resolves aliases to highlight.js names', () => {
    +		expect(resolveHighlightLanguage('ts')).toBe('typescript');
    +		expect(resolveHighlightLanguage('SH')).toBe('bash');
    +		expect(resolveHighlightLanguage('yml')).toBe('yaml');
    +		expect(resolveHighlightLanguage('python')).toBe('python');
    +		expect(resolveHighlightLanguage('constructor')).toBeUndefined();
    +		expect(resolveHighlightLanguage('not-a-language')).toBeUndefined();
    +	});
    +
    +	it('returns plain text, then highlights once that language (and only it) has loaded', async () => {
    +		expect(highlightCode('\nconst x = 1;\n', 'ts')).toBe('const x = 1;');
    +
    +		await loadHighlightLanguages(['ts']);
    +
    +		expect(isHighlightLanguageLoaded('typescript')).toBe(true);
    +		expect(highlightCode('const x = 1;', 'ts')).toContain('hljs-keyword');
    +		expect(isHighlightLanguageLoaded('python')).toBe(false);
    +	});
    +
    +	it('loads the languages a language embeds with it', async () => {
    +		await loadHighlightLanguages(['html']);
    +
    +		expect(isHighlightLanguageLoaded('css')).toBe(true);
    +		expect(highlightCode('', 'html')).toContain('hljs-attribute');
    +	});
    +
    +	it('leaves an unknown language plain without auto-detection', () => {
    +		expect(highlightCode('a && b', 'not-a-language', false)).toBe(
    +			'<b>a && b</b>'
    +		);
    +	});
    +
    +	it('auto-detects an unknown language among the common languages once they load', async () => {
    +		const code = 'def greet(name):\n    return f"hi {name}"';
    +
    +		expect(highlightCode(code, 'not-a-language')).toBe(code);
    +
    +		// that call started loading every common language
    +		const html = await waitForHighlight(() => highlightCode(code, 'not-a-language'));
    +
    +		expect(html).toContain('hljs-');
    +	});
    +});
    +
    +async function waitForHighlight(highlight: () => string): Promise {
    +	for (let i = 0; i < 50; i++) {
    +		const html = highlight();
    +
    +		if (html.includes('hljs-')) return html;
    +
    +		await new Promise((resolve) => setTimeout(resolve, 20));
    +	}
    +
    +	return highlight();
    +}
    +
    +const processor = remark()
    +	.use(remarkRehype)
    +	.use(rehypeLazyHighlight, { aliases: { xml: ['svelte'] } })
    +	.use(rehypeStringify);
    +
    +async function render(markdown: string): Promise {
    +	return processor.stringify((await processor.run(processor.parse(markdown))) as Root);
    +}
    +
    +describe('rehypeLazyHighlight', () => {
    +	it('leaves a message without a code block as it is, in the same pass', () => {
    +		const tree = processor.runSync(processor.parse('Just *text* and `code`')) as Root;
    +
    +		expect(processor.stringify(tree)).toBe('

    Just text and code

    '); + }); + + it('loads a block language, then highlights it in the same pass', async () => { + const markdown = '```rust\nfn main() {}\n```'; + const first = await render(markdown); + + expect(first).toContain(''); + expect(first).toContain('hljs-keyword'); + + const second = processor.stringify(processor.runSync(processor.parse(markdown)) as Root); + + expect(second).toBe(first); + }); + + it('uses highlight.js definitions, not highlightCode bash changes', async () => { + const html = await render('```sh\ncurl -LsSf https://example.com\n```'); + + expect(html).toContain(''); + expect(html).not.toContain('hljs-built_in">curl'); + }); + + it('takes extra aliases', async () => { + expect(await render('```svelte\n
    {x}
    \n```')).toContain('hljs-tag'); + }); + + it('leaves unknown languages, no-highlight and blocks without a language plain', async () => { + expect(await render('```not-a-language\nx = 1\n```')).toBe( + '
    x = 1\n
    ' + ); + expect(await render('```\nx = 1\n```')).toBe('
    x = 1\n
    '); + }); +}); diff --git a/ui/lib/ui/README.md b/ui/lib/ui/README.md index 2c701d8a6331..9fd1c350c8b8 100644 --- a/ui/lib/ui/README.md +++ b/ui/lib/ui/README.md @@ -49,7 +49,13 @@ Next: llama.app's model page. The constants, enums and code helpers the components use are entry points too, for an app that shows the same things: `@ggml-org/llama-ui/constants` (the shared classes and code-block constants), `@ggml-org/llama-ui/enums` (`ColorMode`, -`TooltipSide`, `BooleanString`) and `@ggml-org/llama-ui/code` (`highlightCode`, `trimCodePadding`). The model data +`TooltipSide`, `BooleanString`) and `@ggml-org/llama-ui/code` (`highlightCode`, `trimCodePadding`, +`loadHighlightLanguages`, `isHighlightLanguageLoaded`, `resolveHighlightLanguage`, `getLoadedHighlightLanguages`). +highlight.js loads one language at a time, each its own chunk, so none is in an app's first load: until a language +has loaded, `highlightCode` returns the code escaped as plain text, and a `$derived` or `$effect` that called it runs +again once it has. A language loads with the ones it embeds (CSS and JavaScript inside HTML); auto-detection picks +among lowlight's common languages. Await `loadHighlightLanguages([...])` where highlighted output is needed at once. +`scripts/generate-highlight-languages.mjs` regenerates the language table after a highlight.js or lowlight update. The model data (constants, enums, formatters and types) comes with the Model UI at `@ggml-org/llama-ui/models`. ## How the apps in this repo use it diff --git a/ui/lib/ui/scripts/generate-highlight-languages.mjs b/ui/lib/ui/scripts/generate-highlight-languages.mjs new file mode 100644 index 000000000000..38ca8551d06b --- /dev/null +++ b/ui/lib/ui/scripts/generate-highlight-languages.mjs @@ -0,0 +1,98 @@ +// Writes src/lib/utils/highlight-languages.ts: one loader per highlight.js language lowlight ships (each its own chunk +// in an app's build), the aliases that name them, and lowlight's common languages, which auto-detection picks from. +// Run it after updating highlight.js or lowlight: node scripts/generate-highlight-languages.mjs +import { execFileSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import hljs from "highlight.js/lib/core"; +import { all, common } from "lowlight"; + +const OUTPUT = new URL( + "../src/lib/utils/highlight-languages.ts", + import.meta.url, +); + +const names = Object.keys(all).sort(); +const aliases = {}; +const subLanguages = {}; + +// the languages a definition embeds (`subLanguage`: CSS and JavaScript inside HTML, say), which highlight.js leaves +// plain unless they are registered too +function collectSubLanguages(mode, found, seen = new Set()) { + if (!mode || typeof mode !== "object" || seen.has(mode)) return found; + + seen.add(mode); + + for (const sub of [mode.subLanguage ?? []].flat()) + found.add(sub.toLowerCase()); + + for (const value of Object.values(mode)) { + if (Array.isArray(value)) + for (const item of value) collectSubLanguages(item, found, seen); + else if (value && typeof value === "object") + collectSubLanguages(value, found, seen); + } + + return found; +} + +// register in lowlight's order, so an alias two languages claim names the same one it does in lowlight +for (const name of names) { + const highlighter = hljs.newInstance(); + + highlighter.registerLanguage(name, all[name]); + + for (const alias of highlighter.getLanguage(name)?.aliases ?? []) { + const key = alias.toLowerCase(); + + if (key !== name && !(key in all)) aliases[key] = name; + } +} + +for (const name of names) { + const definition = all[name](hljs); + const found = [...collectSubLanguages(definition, new Set())] + .map((sub) => (sub in all ? sub : aliases[sub])) + .filter((sub) => sub && sub !== name); + + if (found.length) subLanguages[name] = [...new Set(found)].sort(); +} + +const quote = (s) => `'${s}'`; +const key = (s) => (/^[a-z_$][\w$]*$/i.test(s) ? s : quote(s)); + +const source = `// Generated by scripts/generate-highlight-languages.mjs from lowlight's languages; do not edit by hand. +import type { LanguageFn } from 'highlight.js'; + +/** Loads one highlight.js language, by its name. */ +export const HIGHLIGHT_LANGUAGE_LOADERS: Record Promise<{ default: LanguageFn }>> = { +${names.map((n) => `\t${key(n)}: () => import('highlight.js/lib/languages/${n}')`).join(",\n")} +}; + +/** The language each alias names (\`js\` -> \`javascript\`), as highlight.js resolves it. */ +export const HIGHLIGHT_LANGUAGE_ALIASES: Record = { +${Object.keys(aliases) + .sort() + .map((a) => `\t${key(a)}: ${quote(aliases[a])}`) + .join(",\n")} +}; + +/** The languages each language embeds, to load with it so its embedded code is highlighted too. */ +export const HIGHLIGHT_SUB_LANGUAGES: Record = { +${Object.keys(subLanguages) + .map((n) => `\t${key(n)}: [${subLanguages[n].map(quote).join(", ")}]`) + .join(",\n")} +}; + +/** lowlight's common languages: the ones auto-detection picks from. */ +export const HIGHLIGHT_AUTO_DETECT_LANGUAGES: readonly string[] = [ +${Object.keys(common) + .sort() + .map((n) => `\t${quote(n)}`) + .join(",\n")} +]; +`; + +writeFileSync(OUTPUT, source); +execFileSync("npx", ["prettier", "--write", OUTPUT.pathname], { + stdio: "inherit", +}); diff --git a/ui/lib/ui/src/lib/constants/code-block.constants.ts b/ui/lib/ui/src/lib/constants/code-block.constants.ts index d395f861ee83..836d619d319a 100644 --- a/ui/lib/ui/src/lib/constants/code-block.constants.ts +++ b/ui/lib/ui/src/lib/constants/code-block.constants.ts @@ -8,9 +8,15 @@ export const CODE_BLOCK = { /** Matches opening/closing markdown code fences. */ FENCE_PATTERN: /^```|\n```/g, GT_REGEX: />/g, + /** Short form of the class prefix that names a code element's language (`lang-ts`). */ + LANG_CLASS_PREFIX: "lang-", + /** Class prefix that names a code element's language (`language-ts`). */ + LANGUAGE_CLASS_PREFIX: "language-", /** Matches the language specifier at the start of a code fence. */ LANG_PATTERN: /^(\w*)\n?/, LT_REGEX: / | undefined; +const languageLoading = new Map>(); +/** Languages loaded together with every language they embed, so highlightCode can use them. */ +const readyLanguages = new Set(); +/** Each loaded language's definition as highlight.js ships it, without this module's bash changes. */ +const languageDefinitions = new Map(); +const loadListeners = new Set<() => void>(); + +// lets a $derived or $effect that called highlightCode before its language loaded run again once it has +const subscribeToLoad = createSubscriber((update) => { + loadListeners.add(update); + + return () => loadListeners.delete(update); +}); // highlight.js's bash marks strings, variables and keywords but leaves a command's name and its flags plain, so a // command (`curl -H … -d …`) reads as one colour. Mark them too: the name as a built-in, the flags as attributes. -hljs.registerLanguage("bash", (api) => { - const base = bash(api); - - return { - ...base, - contains: [ - { match: CODE_BLOCK.SHELL_COMMAND_REGEX, scope: "built_in" }, - { match: CODE_BLOCK.SHELL_FLAG_REGEX, scope: "attr" }, - ...(base.contains ?? []), - ], +function withShellCommands(bash: LanguageFn): LanguageFn { + return (api) => { + const base = bash(api); + + return { + ...base, + contains: [ + { match: CODE_BLOCK.SHELL_COMMAND_REGEX, scope: "built_in" }, + { match: CODE_BLOCK.SHELL_FLAG_REGEX, scope: "attr" }, + ...(base.contains ?? []), + ], + }; }; -}); +} + +/** The highlight.js name of a language or one of its aliases (`ts` -> `typescript`), or undefined for one it lacks. */ +export function resolveHighlightLanguage(language: string): string | undefined { + const key = language.toLowerCase(); + + if (Object.hasOwn(HIGHLIGHT_LANGUAGE_LOADERS, key)) return key; + + return Object.hasOwn(HIGHLIGHT_LANGUAGE_ALIASES, key) + ? HIGHLIGHT_LANGUAGE_ALIASES[key] + : undefined; +} + +/** Whether a language (or alias) has loaded, so highlightCode highlights it rather than returning plain text. */ +export function isHighlightLanguageLoaded(language: string): boolean { + const name = resolveHighlightLanguage(language); + + return name !== undefined && readyLanguages.has(name); +} + +/** The definitions of every loaded language, as highlight.js ships them, to register with another highlighter. */ +export function getLoadedHighlightLanguages(): Record { + return Object.fromEntries( + [...readyLanguages].map((name) => [name, languageDefinitions.get(name)!]), + ); +} + +function loadCore(): Promise { + coreLoading ??= import("highlight.js/lib/core").then( + (module) => (hljs = module.default.newInstance()), + (error) => { + coreLoading = undefined; + + throw error; + }, + ); + + return coreLoading; +} + +function loadLanguage(name: string): Promise { + let loading = languageLoading.get(name); + + if (!loading) { + loading = Promise.all([ + loadCore(), + HIGHLIGHT_LANGUAGE_LOADERS[name](), + ]).then(([core, module]) => { + languageDefinitions.set(name, module.default); + core.registerLanguage( + name, + name === CODE_BLOCK.SHELL_LANGUAGE + ? withShellCommands(module.default) + : module.default, + ); + }); + // let a later call try again + loading.catch(() => languageLoading.delete(name)); + languageLoading.set(name, loading); + } + + return loading; +} + +/** + * Loads languages (names or aliases; unknown ones are skipped) with every language they embed, or every language + * when called without any. highlightCode loads what it needs itself; await this where highlighted output is needed + * right away, as in tests or a server render. + */ +export async function loadHighlightLanguages( + languages?: readonly string[], +): Promise { + const names = new Set(); + const queue = languages + ? languages + .map(resolveHighlightLanguage) + .filter((name) => name !== undefined) + : Object.keys(HIGHLIGHT_LANGUAGE_LOADERS); + + while (queue.length) { + const name = queue.pop()!; + + if (names.has(name)) continue; + + names.add(name); + queue.push(...(HIGHLIGHT_SUB_LANGUAGES[name] ?? [])); + } + + const missing = [...names].filter((name) => !readyLanguages.has(name)); + + if (!missing.length) return; + + await Promise.all(missing.map(loadLanguage)); + + for (const name of missing) readyLanguages.add(name); + for (const update of [...loadListeners]) update(); +} /** * Strips empty lines (whitespace-only) from the start and end of code, so hljs emits no phantom row before or after @@ -42,7 +159,13 @@ function escapeCode(code: string): string { const HIGHLIGHT_CACHE_MAX_SIZE = 64; const highlightCache = new Map(); -/** Highlights code with highlight.js in the given language, auto-detecting one it doesn't know. */ +/** + * Highlights code with highlight.js in the given language (a name or an alias). For a language highlight.js lacks it + * auto-detects one among lowlight's common languages, unless autoDetect is false. + * + * Each language loads on first use: until it has, this returns the code escaped as plain text, and a Svelte $derived + * or $effect that called it runs again once it has loaded. Await loadHighlightLanguages() first to skip that. + */ export function highlightCode( code: string, language: string, @@ -50,25 +173,34 @@ export function highlightCode( ): string { if (!code) return ""; - const cacheKey = `${language}:${autoDetect}:${code}`; + const name = resolveHighlightLanguage(language); + const needed = name + ? [name] + : autoDetect + ? HIGHLIGHT_AUTO_DETECT_LANGUAGES + : []; + const trimmed = trimCodePadding(code); + + if (!needed.length) return escapeCode(trimmed); + + if (!hljs || !needed.every((n) => readyLanguages.has(n))) { + subscribeToLoad(); + loadHighlightLanguages(needed).catch(() => {}); + + return escapeCode(trimmed); + } + + const cacheKey = `${name ?? ""}:${code}`; const cached = highlightCache.get(cacheKey); if (cached) return cached; - const trimmed = trimCodePadding(code); - let result: string; try { - const lang = language.toLowerCase(); - - if (hljs.getLanguage(lang)) { - result = hljs.highlight(trimmed, { language: lang }).value; - } else if (autoDetect) { - result = hljs.highlightAuto(trimmed).value; - } else { - result = escapeCode(trimmed); - } + result = name + ? hljs.highlight(trimmed, { language: name }).value + : hljs.highlightAuto(trimmed, [...HIGHLIGHT_AUTO_DETECT_LANGUAGES]).value; } catch { result = escapeCode(trimmed); } diff --git a/ui/lib/ui/src/lib/utils/highlight-languages.ts b/ui/lib/ui/src/lib/utils/highlight-languages.ts new file mode 100644 index 000000000000..e52bcc6ec625 --- /dev/null +++ b/ui/lib/ui/src/lib/utils/highlight-languages.ts @@ -0,0 +1,474 @@ +// Generated by scripts/generate-highlight-languages.mjs from lowlight's languages; do not edit by hand. +import type { LanguageFn } from "highlight.js"; + +/** Loads one highlight.js language, by its name. */ +export const HIGHLIGHT_LANGUAGE_LOADERS: Record< + string, + () => Promise<{ default: LanguageFn }> +> = { + "1c": () => import("highlight.js/lib/languages/1c"), + abnf: () => import("highlight.js/lib/languages/abnf"), + accesslog: () => import("highlight.js/lib/languages/accesslog"), + actionscript: () => import("highlight.js/lib/languages/actionscript"), + ada: () => import("highlight.js/lib/languages/ada"), + angelscript: () => import("highlight.js/lib/languages/angelscript"), + apache: () => import("highlight.js/lib/languages/apache"), + applescript: () => import("highlight.js/lib/languages/applescript"), + arcade: () => import("highlight.js/lib/languages/arcade"), + arduino: () => import("highlight.js/lib/languages/arduino"), + armasm: () => import("highlight.js/lib/languages/armasm"), + asciidoc: () => import("highlight.js/lib/languages/asciidoc"), + aspectj: () => import("highlight.js/lib/languages/aspectj"), + autohotkey: () => import("highlight.js/lib/languages/autohotkey"), + autoit: () => import("highlight.js/lib/languages/autoit"), + avrasm: () => import("highlight.js/lib/languages/avrasm"), + awk: () => import("highlight.js/lib/languages/awk"), + axapta: () => import("highlight.js/lib/languages/axapta"), + bash: () => import("highlight.js/lib/languages/bash"), + basic: () => import("highlight.js/lib/languages/basic"), + bnf: () => import("highlight.js/lib/languages/bnf"), + brainfuck: () => import("highlight.js/lib/languages/brainfuck"), + c: () => import("highlight.js/lib/languages/c"), + cal: () => import("highlight.js/lib/languages/cal"), + capnproto: () => import("highlight.js/lib/languages/capnproto"), + ceylon: () => import("highlight.js/lib/languages/ceylon"), + clean: () => import("highlight.js/lib/languages/clean"), + clojure: () => import("highlight.js/lib/languages/clojure"), + "clojure-repl": () => import("highlight.js/lib/languages/clojure-repl"), + cmake: () => import("highlight.js/lib/languages/cmake"), + coffeescript: () => import("highlight.js/lib/languages/coffeescript"), + coq: () => import("highlight.js/lib/languages/coq"), + cos: () => import("highlight.js/lib/languages/cos"), + cpp: () => import("highlight.js/lib/languages/cpp"), + crmsh: () => import("highlight.js/lib/languages/crmsh"), + crystal: () => import("highlight.js/lib/languages/crystal"), + csharp: () => import("highlight.js/lib/languages/csharp"), + csp: () => import("highlight.js/lib/languages/csp"), + css: () => import("highlight.js/lib/languages/css"), + d: () => import("highlight.js/lib/languages/d"), + dart: () => import("highlight.js/lib/languages/dart"), + delphi: () => import("highlight.js/lib/languages/delphi"), + diff: () => import("highlight.js/lib/languages/diff"), + django: () => import("highlight.js/lib/languages/django"), + dns: () => import("highlight.js/lib/languages/dns"), + dockerfile: () => import("highlight.js/lib/languages/dockerfile"), + dos: () => import("highlight.js/lib/languages/dos"), + dsconfig: () => import("highlight.js/lib/languages/dsconfig"), + dts: () => import("highlight.js/lib/languages/dts"), + dust: () => import("highlight.js/lib/languages/dust"), + ebnf: () => import("highlight.js/lib/languages/ebnf"), + elixir: () => import("highlight.js/lib/languages/elixir"), + elm: () => import("highlight.js/lib/languages/elm"), + erb: () => import("highlight.js/lib/languages/erb"), + erlang: () => import("highlight.js/lib/languages/erlang"), + "erlang-repl": () => import("highlight.js/lib/languages/erlang-repl"), + excel: () => import("highlight.js/lib/languages/excel"), + fix: () => import("highlight.js/lib/languages/fix"), + flix: () => import("highlight.js/lib/languages/flix"), + fortran: () => import("highlight.js/lib/languages/fortran"), + fsharp: () => import("highlight.js/lib/languages/fsharp"), + gams: () => import("highlight.js/lib/languages/gams"), + gauss: () => import("highlight.js/lib/languages/gauss"), + gcode: () => import("highlight.js/lib/languages/gcode"), + gherkin: () => import("highlight.js/lib/languages/gherkin"), + glsl: () => import("highlight.js/lib/languages/glsl"), + gml: () => import("highlight.js/lib/languages/gml"), + go: () => import("highlight.js/lib/languages/go"), + golo: () => import("highlight.js/lib/languages/golo"), + gradle: () => import("highlight.js/lib/languages/gradle"), + graphql: () => import("highlight.js/lib/languages/graphql"), + groovy: () => import("highlight.js/lib/languages/groovy"), + haml: () => import("highlight.js/lib/languages/haml"), + handlebars: () => import("highlight.js/lib/languages/handlebars"), + haskell: () => import("highlight.js/lib/languages/haskell"), + haxe: () => import("highlight.js/lib/languages/haxe"), + hsp: () => import("highlight.js/lib/languages/hsp"), + http: () => import("highlight.js/lib/languages/http"), + hy: () => import("highlight.js/lib/languages/hy"), + inform7: () => import("highlight.js/lib/languages/inform7"), + ini: () => import("highlight.js/lib/languages/ini"), + irpf90: () => import("highlight.js/lib/languages/irpf90"), + isbl: () => import("highlight.js/lib/languages/isbl"), + java: () => import("highlight.js/lib/languages/java"), + javascript: () => import("highlight.js/lib/languages/javascript"), + "jboss-cli": () => import("highlight.js/lib/languages/jboss-cli"), + json: () => import("highlight.js/lib/languages/json"), + julia: () => import("highlight.js/lib/languages/julia"), + "julia-repl": () => import("highlight.js/lib/languages/julia-repl"), + kotlin: () => import("highlight.js/lib/languages/kotlin"), + lasso: () => import("highlight.js/lib/languages/lasso"), + latex: () => import("highlight.js/lib/languages/latex"), + ldif: () => import("highlight.js/lib/languages/ldif"), + leaf: () => import("highlight.js/lib/languages/leaf"), + less: () => import("highlight.js/lib/languages/less"), + lisp: () => import("highlight.js/lib/languages/lisp"), + livecodeserver: () => import("highlight.js/lib/languages/livecodeserver"), + livescript: () => import("highlight.js/lib/languages/livescript"), + llvm: () => import("highlight.js/lib/languages/llvm"), + lsl: () => import("highlight.js/lib/languages/lsl"), + lua: () => import("highlight.js/lib/languages/lua"), + makefile: () => import("highlight.js/lib/languages/makefile"), + markdown: () => import("highlight.js/lib/languages/markdown"), + mathematica: () => import("highlight.js/lib/languages/mathematica"), + matlab: () => import("highlight.js/lib/languages/matlab"), + maxima: () => import("highlight.js/lib/languages/maxima"), + mel: () => import("highlight.js/lib/languages/mel"), + mercury: () => import("highlight.js/lib/languages/mercury"), + mipsasm: () => import("highlight.js/lib/languages/mipsasm"), + mizar: () => import("highlight.js/lib/languages/mizar"), + mojolicious: () => import("highlight.js/lib/languages/mojolicious"), + monkey: () => import("highlight.js/lib/languages/monkey"), + moonscript: () => import("highlight.js/lib/languages/moonscript"), + n1ql: () => import("highlight.js/lib/languages/n1ql"), + nestedtext: () => import("highlight.js/lib/languages/nestedtext"), + nginx: () => import("highlight.js/lib/languages/nginx"), + nim: () => import("highlight.js/lib/languages/nim"), + nix: () => import("highlight.js/lib/languages/nix"), + "node-repl": () => import("highlight.js/lib/languages/node-repl"), + nsis: () => import("highlight.js/lib/languages/nsis"), + objectivec: () => import("highlight.js/lib/languages/objectivec"), + ocaml: () => import("highlight.js/lib/languages/ocaml"), + openscad: () => import("highlight.js/lib/languages/openscad"), + oxygene: () => import("highlight.js/lib/languages/oxygene"), + parser3: () => import("highlight.js/lib/languages/parser3"), + perl: () => import("highlight.js/lib/languages/perl"), + pf: () => import("highlight.js/lib/languages/pf"), + pgsql: () => import("highlight.js/lib/languages/pgsql"), + php: () => import("highlight.js/lib/languages/php"), + "php-template": () => import("highlight.js/lib/languages/php-template"), + plaintext: () => import("highlight.js/lib/languages/plaintext"), + pony: () => import("highlight.js/lib/languages/pony"), + powershell: () => import("highlight.js/lib/languages/powershell"), + processing: () => import("highlight.js/lib/languages/processing"), + profile: () => import("highlight.js/lib/languages/profile"), + prolog: () => import("highlight.js/lib/languages/prolog"), + properties: () => import("highlight.js/lib/languages/properties"), + protobuf: () => import("highlight.js/lib/languages/protobuf"), + puppet: () => import("highlight.js/lib/languages/puppet"), + purebasic: () => import("highlight.js/lib/languages/purebasic"), + python: () => import("highlight.js/lib/languages/python"), + "python-repl": () => import("highlight.js/lib/languages/python-repl"), + q: () => import("highlight.js/lib/languages/q"), + qml: () => import("highlight.js/lib/languages/qml"), + r: () => import("highlight.js/lib/languages/r"), + reasonml: () => import("highlight.js/lib/languages/reasonml"), + rib: () => import("highlight.js/lib/languages/rib"), + roboconf: () => import("highlight.js/lib/languages/roboconf"), + routeros: () => import("highlight.js/lib/languages/routeros"), + rsl: () => import("highlight.js/lib/languages/rsl"), + ruby: () => import("highlight.js/lib/languages/ruby"), + ruleslanguage: () => import("highlight.js/lib/languages/ruleslanguage"), + rust: () => import("highlight.js/lib/languages/rust"), + sas: () => import("highlight.js/lib/languages/sas"), + scala: () => import("highlight.js/lib/languages/scala"), + scheme: () => import("highlight.js/lib/languages/scheme"), + scilab: () => import("highlight.js/lib/languages/scilab"), + scss: () => import("highlight.js/lib/languages/scss"), + shell: () => import("highlight.js/lib/languages/shell"), + smali: () => import("highlight.js/lib/languages/smali"), + smalltalk: () => import("highlight.js/lib/languages/smalltalk"), + sml: () => import("highlight.js/lib/languages/sml"), + sqf: () => import("highlight.js/lib/languages/sqf"), + sql: () => import("highlight.js/lib/languages/sql"), + stan: () => import("highlight.js/lib/languages/stan"), + stata: () => import("highlight.js/lib/languages/stata"), + step21: () => import("highlight.js/lib/languages/step21"), + stylus: () => import("highlight.js/lib/languages/stylus"), + subunit: () => import("highlight.js/lib/languages/subunit"), + swift: () => import("highlight.js/lib/languages/swift"), + taggerscript: () => import("highlight.js/lib/languages/taggerscript"), + tap: () => import("highlight.js/lib/languages/tap"), + tcl: () => import("highlight.js/lib/languages/tcl"), + thrift: () => import("highlight.js/lib/languages/thrift"), + tp: () => import("highlight.js/lib/languages/tp"), + twig: () => import("highlight.js/lib/languages/twig"), + typescript: () => import("highlight.js/lib/languages/typescript"), + vala: () => import("highlight.js/lib/languages/vala"), + vbnet: () => import("highlight.js/lib/languages/vbnet"), + vbscript: () => import("highlight.js/lib/languages/vbscript"), + "vbscript-html": () => import("highlight.js/lib/languages/vbscript-html"), + verilog: () => import("highlight.js/lib/languages/verilog"), + vhdl: () => import("highlight.js/lib/languages/vhdl"), + vim: () => import("highlight.js/lib/languages/vim"), + wasm: () => import("highlight.js/lib/languages/wasm"), + wren: () => import("highlight.js/lib/languages/wren"), + x86asm: () => import("highlight.js/lib/languages/x86asm"), + xl: () => import("highlight.js/lib/languages/xl"), + xml: () => import("highlight.js/lib/languages/xml"), + xquery: () => import("highlight.js/lib/languages/xquery"), + yaml: () => import("highlight.js/lib/languages/yaml"), + zephir: () => import("highlight.js/lib/languages/zephir"), +}; + +/** The language each alias names (`js` -> `javascript`), as highlight.js resolves it. */ +export const HIGHLIGHT_LANGUAGE_ALIASES: Record = { + ado: "stata", + adoc: "asciidoc", + ahk: "autohotkey", + apacheconf: "apache", + arm: "armasm", + as: "actionscript", + asc: "angelscript", + atom: "xml", + bat: "dos", + bf: "brainfuck", + bind: "dns", + "c#": "csharp", + "c++": "cpp", + capnp: "capnproto", + cc: "cpp", + cjs: "javascript", + clj: "clojure", + cls: "cos", + "cmake.in": "cmake", + cmd: "dos", + coffee: "coffeescript", + console: "shell", + cr: "crystal", + craftcms: "twig", + crm: "crmsh", + cs: "csharp", + cson: "coffeescript", + cts: "typescript", + cxx: "cpp", + dcl: "clean", + dfm: "delphi", + do: "stata", + docker: "dockerfile", + dpr: "delphi", + dst: "dust", + edn: "clojure", + erl: "erlang", + ex: "elixir", + exs: "elixir", + "f#": "fsharp", + f90: "fortran", + f95: "fortran", + feature: "gherkin", + fs: "fsharp", + gemspec: "ruby", + gms: "gams", + golang: "go", + gql: "graphql", + graph: "roboconf", + gss: "gauss", + gyp: "python", + h: "c", + "h++": "cpp", + hbs: "handlebars", + hh: "cpp", + hpp: "cpp", + hs: "haskell", + html: "xml", + "html.handlebars": "handlebars", + "html.hbs": "handlebars", + htmlbars: "handlebars", + https: "http", + hx: "haxe", + hxx: "cpp", + hylang: "hy", + i7: "inform7", + iced: "coffeescript", + icl: "clean", + ino: "arduino", + instances: "roboconf", + ipython: "python", + irb: "ruby", + jinja: "django", + jldoctest: "julia-repl", + js: "javascript", + jsonc: "json", + jsp: "java", + jsx: "javascript", + k: "q", + kdb: "q", + kt: "kotlin", + kts: "kotlin", + lassoscript: "lasso", + ls: "livescript", + m: "mercury", + mak: "makefile", + make: "makefile", + md: "markdown", + mikrotik: "routeros", + mips: "mipsasm", + mjs: "javascript", + mk: "makefile", + mkd: "markdown", + mkdown: "markdown", + ml: "sml", + mm: "objectivec", + mma: "mathematica", + moo: "mercury", + moon: "moonscript", + mts: "typescript", + nc: "gcode", + nginxconf: "nginx", + nixos: "nix", + nt: "nestedtext", + "obj-c": "objectivec", + "obj-c++": "objectivec", + objc: "objectivec", + "objective-c++": "objectivec", + osascript: "applescript", + p21: "step21", + pas: "delphi", + pascal: "delphi", + patch: "diff", + pb: "purebasic", + pbi: "purebasic", + pcmk: "crmsh", + pde: "processing", + "pf.conf": "pf", + pl: "perl", + plist: "xml", + pluto: "lua", + pm: "perl", + podspec: "ruby", + postgres: "pgsql", + postgresql: "pgsql", + pp: "puppet", + proto: "protobuf", + ps: "powershell", + ps1: "powershell", + pwsh: "powershell", + py: "python", + pycon: "python-repl", + qt: "qml", + rb: "ruby", + re: "reasonml", + rs: "rust", + rss: "xml", + scad: "openscad", + sci: "scilab", + scm: "scheme", + sh: "bash", + shellsession: "shell", + st: "smalltalk", + stanfuncs: "stan", + step: "step21", + stp: "step21", + styl: "stylus", + sv: "verilog", + svg: "xml", + svh: "verilog", + tao: "xl", + tex: "latex", + text: "plaintext", + thor: "ruby", + tk: "tcl", + toml: "ini", + ts: "typescript", + tsx: "typescript", + txt: "plaintext", + v: "verilog", + vb: "vbnet", + vbs: "vbscript", + "wildfly-cli": "jboss-cli", + wl: "mathematica", + wsf: "xml", + "x++": "axapta", + xhtml: "xml", + xjb: "xml", + xls: "excel", + xlsx: "excel", + xpath: "xquery", + xq: "xquery", + xqm: "xquery", + xsd: "xml", + xsl: "xml", + yml: "yaml", + zep: "zephir", + zone: "dns", + zsh: "bash", +}; + +/** The languages each language embeds, to load with it so its embedded code is highlighted too. */ +export const HIGHLIGHT_SUB_LANGUAGES: Record = { + asciidoc: ["xml"], + "clojure-repl": ["clojure"], + coffeescript: ["javascript"], + cos: ["javascript", "sql", "xml"], + dart: ["markdown"], + django: ["xml"], + dockerfile: ["bash"], + dust: ["xml"], + erb: ["ruby", "xml"], + haml: ["ruby"], + handlebars: ["xml"], + javascript: ["css", "graphql", "xml"], + "julia-repl": ["julia"], + livescript: ["javascript"], + markdown: ["xml"], + mojolicious: ["perl", "xml"], + nix: ["markdown"], + "node-repl": ["javascript"], + parser3: ["xml"], + perl: ["mojolicious"], + pgsql: [ + "bash", + "java", + "json", + "lua", + "perl", + "php", + "python", + "r", + "ruby", + "scheme", + "tcl", + "xml", + ], + "php-template": ["php", "xml"], + "python-repl": ["python"], + qml: ["xml"], + shell: ["bash"], + tap: ["yaml"], + twig: ["xml"], + typescript: ["css", "graphql", "xml"], + "vbscript-html": ["vbscript", "xml"], + xml: ["css", "handlebars", "javascript"], + xquery: ["xml"], + yaml: ["ruby"], +}; + +/** lowlight's common languages: the ones auto-detection picks from. */ +export const HIGHLIGHT_AUTO_DETECT_LANGUAGES: readonly string[] = [ + "arduino", + "bash", + "c", + "cpp", + "csharp", + "css", + "diff", + "go", + "graphql", + "ini", + "java", + "javascript", + "json", + "kotlin", + "less", + "lua", + "makefile", + "markdown", + "objectivec", + "perl", + "php", + "php-template", + "plaintext", + "python", + "python-repl", + "r", + "ruby", + "rust", + "scss", + "shell", + "sql", + "swift", + "typescript", + "vbnet", + "wasm", + "xml", + "yaml", +]; diff --git a/ui/lib/ui/src/lib/utils/index.ts b/ui/lib/ui/src/lib/utils/index.ts index 3e3c1fdeff65..3eb11e2306bf 100644 --- a/ui/lib/ui/src/lib/utils/index.ts +++ b/ui/lib/ui/src/lib/utils/index.ts @@ -1 +1,8 @@ -export { highlightCode, trimCodePadding } from './code'; +export { + getLoadedHighlightLanguages, + highlightCode, + isHighlightLanguageLoaded, + loadHighlightLanguages, + resolveHighlightLanguage, + trimCodePadding, +} from "./code"; From e626db7caadee98c6174b1c2dc69f3f43075faa0 Mon Sep 17 00:00:00 2001 From: Xuejun Zhai Date: Fri, 20 Nov 2026 22:16:52 +0800 Subject: [PATCH 35/88] server-bench : fix TypeError in histogram generation (#32518) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(server-bench): prevent float bin-count TypeError in histogram generation Symptom: benchmark crashes while generating gen_rate histogram. Root cause: np.ceil(...) returns numpy.float64, and that value was used where an integer count/shape argument is required. Fix: cast ceil result to int before +1, ensuring bin count is an integer. Result: histogram path completes and gen_rate.png is generated reliably. * Update scripts/server-bench.py Co-authored-by: Sigbjørn Skjæret --------- Co-authored-by: Sigbjørn Skjæret --- scripts/server-bench.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/server-bench.py b/scripts/server-bench.py index f0984026c862..dca157302213 100755 --- a/scripts/server-bench.py +++ b/scripts/server-bench.py @@ -264,7 +264,7 @@ def benchmark( bin_max = np.ceil(token_t_last) + 1 plt.figure() - plt.hist(token_t, np.linspace(0, bin_max, bin_max, endpoint=False).tolist()) + plt.hist(token_t, np.linspace(0, bin_max, int(bin_max), endpoint=False).tolist()) plt.xlim(0, bin_max + 1) plt.title(name or "") plt.xlabel("Time [s]") From 8e7862411da14d8cc342611f37e15ee05d97bfd3 Mon Sep 17 00:00:00 2001 From: yoch Date: Fri, 20 Nov 2026 16:34:58 +0200 Subject: [PATCH 36/88] tts : forward -t to the mtmd context (#32664) llama-tts built the mtmd context from mtmd_context_params_default(), which hardcodes 4 threads, and never copied n_threads over, so -t never reach the mtmd side. Copy params.cpuparams.n_threads into mtmd_params.n_threads, as mtmd-cli and the server do; with no -t this now follows the resolved default. Verified: -t 1 now runs single-threaded, -t 4 is unchanged, and the produced WAV is identical. Assisted-by: Claude --- tools/tts/tts.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/tts/tts.cpp b/tools/tts/tts.cpp index dbf618ac22f5..238cc828b097 100644 --- a/tools/tts/tts.cpp +++ b/tools/tts/tts.cpp @@ -86,8 +86,9 @@ int main(int argc, char ** argv) { } mtmd_context_params mtmd_params = mtmd_context_params_default(); - mtmd_params.use_gpu = params.mmproj_use_gpu; - mtmd_params.device = params.mmproj_device; + mtmd_params.use_gpu = params.mmproj_use_gpu; + mtmd_params.device = params.mmproj_device; + mtmd_params.n_threads = params.cpuparams.n_threads; mtmd::context_ptr mctx(mtmd_init_from_file(params.mmproj.path.c_str(), model, mtmd_params)); if (!mctx) { LOG_ERR("failed to load mmproj %s\n", params.mmproj.path.c_str()); From cf4153a9baeebddd02935b54abfbd4da5bd65854 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 20 Nov 2026 15:46:18 +0100 Subject: [PATCH 37/88] ui: publish llama-ui as an alias of @ggml-org/llama-ui (#32667) The unscoped llama-ui on npm is a 0.0.1 placeholder. After the scoped publish, the workflow renames the same build and publishes it again at the same version, with a readme note pointing at the scoped package. Assisted-by: Claude (Opus 5.5 Medium) --- .github/workflows/ui-lib-publish.yml | 50 ++++++++++++++++++++++++++++ ui/lib/ui/scripts/alias-package.mjs | 43 ++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 ui/lib/ui/scripts/alias-package.mjs diff --git a/.github/workflows/ui-lib-publish.yml b/.github/workflows/ui-lib-publish.yml index 00afed3ab0ea..a1258cda4549 100644 --- a/.github/workflows/ui-lib-publish.yml +++ b/.github/workflows/ui-lib-publish.yml @@ -18,6 +18,10 @@ name: UI Lib Publish # ui-lib-publish.yml, and Environment left blank - this job names no environment, since creating # one needs repository admin. Merging this workflow before that exists leaves the publish step # red on master: the release is late rather than wrong, and re-running the job publishes it. +# +# The unscoped llama-ui is an alias: once the scoped package is out, the same build is renamed +# and published again at the same version, so the two never drift. It is a package of its own +# on npm, and needs the same trusted publisher set on it. on: workflow_dispatch: @@ -128,6 +132,30 @@ jobs: npm publish --access public --provenance --ignore-scripts --tag "$TAG" working-directory: ${{ env.LIB_DIR }} + - name: Rename the build to the unscoped alias + # after the scoped publish, so nothing above sees the changed name. Not on a PR: the + # advisory check there is about the version, which the alias shares. + if: github.event_name != 'pull_request' + run: node scripts/alias-package.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Compare the alias with npm + id: alias + if: github.event_name != 'pull_request' + run: node scripts/npm-version-check.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Publish the alias + # its own verdict rather than the scoped one's, so an alias that fell behind catches up + # on the next run instead of waiting for a bump + if: github.ref == 'refs/heads/master' && steps.alias.outputs.should_publish == 'true' && inputs.dry_run != true + env: + TAG: ${{ steps.alias.outputs.tag }} + run: | + test -d dist || { echo "dist/ is missing: nothing was built, so nothing is published"; exit 1; } + npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.LIB_DIR }} + - name: Report if: always() # every value reaches the shell through env, not through the script, so a package name @@ -140,6 +168,11 @@ jobs: NOTE: ${{ steps.version.outputs.note }} SHOULD: ${{ steps.version.outputs.should_publish }} DRY: ${{ inputs.dry_run }} + ALIAS_LATEST: ${{ steps.alias.outputs.latest }} + ALIAS_VERDICT: ${{ steps.alias.outputs.verdict || 'not reached' }} + ALIAS_NOTE: ${{ steps.alias.outputs.note }} + ALIAS_SHOULD: ${{ steps.alias.outputs.should_publish }} + EVENT: ${{ github.event_name }} run: | if [ "$DRY" = "true" ]; then published="no (dry run)" elif [ "$SHOULD" = "true" ]; then published=yes @@ -156,6 +189,23 @@ jobs: echo echo "> $NOTE" } >> "$GITHUB_STEP_SUMMARY" + [ "$EVENT" = "pull_request" ] && exit 0 + if [ "$DRY" = "true" ]; then published="no (dry run)" + elif [ "$ALIAS_SHOULD" = "true" ]; then published=yes + else published=no + fi + { + echo + echo "### llama-ui (alias) $VERSION" + echo + echo "| | |" + echo "| --- | --- |" + echo "| npm latest was | ${ALIAS_LATEST:-nothing published yet} |" + echo "| verdict | \`$ALIAS_VERDICT\` |" + echo "| published | $published |" + echo + echo "> $ALIAS_NOTE" + } >> "$GITHUB_STEP_SUMMARY" - name: Mind the verdict if: always() && github.event_name != 'pull_request' && steps.version.outcome == 'success' diff --git a/ui/lib/ui/scripts/alias-package.mjs b/ui/lib/ui/scripts/alias-package.mjs new file mode 100644 index 000000000000..f3e94131edf0 --- /dev/null +++ b/ui/lib/ui/scripts/alias-package.mjs @@ -0,0 +1,43 @@ +#!/usr/bin/env node +// Turns this checkout of the library into its unscoped alias, llama-ui, for +// .github/workflows/ui-lib-publish.yml: the same build, published a second time under the +// name people type first. Only the name in package.json changes, and the readme gains a note +// saying which package is the real one. Run it after the scoped publish and never commit the +// result. + +import { readFileSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const ALIAS = 'llama-ui'; + +const pkgPath = fileURLToPath(new URL('../package.json', import.meta.url)); +const readmePath = fileURLToPath(new URL('../README.md', import.meta.url)); + +const raw = readFileSync(pkgPath, 'utf8'); +const pkg = JSON.parse(raw); +const scoped = pkg.name; + +if (scoped === ALIAS) { + console.log(`package.json is already named ${ALIAS}`); + process.exit(0); +} +if (!scoped?.endsWith(`/${ALIAS}`)) { + console.error(`expected a scoped ${ALIAS} package to alias, got ${scoped}`); + process.exit(1); +} + +pkg.name = ALIAS; +// keep the file's own indentation so the diff is the name alone +const indent = raw.match(/^[ \t]+/m)?.[0] ?? '\t'; +writeFileSync(pkgPath, JSON.stringify(pkg, null, indent) + '\n'); + +const note = [ + `> \`${ALIAS}\` is an alias of [\`${scoped}\`](https://www.npmjs.com/package/${scoped}): the same`, + `> build at the same version, published under both names. Prefer \`${scoped}\`; the examples`, + `> below use it, and work with \`${ALIAS}\` in its place.`, + '', + '', +].join('\n'); +writeFileSync(readmePath, note + readFileSync(readmePath, 'utf8')); + +console.log(`${scoped}@${pkg.version} is now named ${ALIAS}`); From 059cac2848cfa564f9657e09045ee75ebee9d6f8 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 20 Nov 2026 16:20:00 +0100 Subject: [PATCH 38/88] ui: search message content and Discover models from the search dialog (#32670) * ui: search message content and Discover models from the search dialog The search dialog matched chat titles only. It now also scans what was said in each chat (content, reasoning, tool calls and results, attachment names and text), newest chat first, stopping at the first match per chat and after 20 chats, and shows a snippet around the match. Ids, timestamps and base64 payloads are not searched. With Discover on, it also lists matching catalog models and, once typing settles, Hugging Face repos; picking one opens Discover on that repo. Assisted-by: Claude (Opus 5.5 Medium) * ui: keep the search dialog one width whatever it lists The shared dialog sizes itself to its content from md up, so the search was narrow while empty and widened as results came in. It now takes the full max-w-2xl there, less a margin on narrower windows. Assisted-by: Claude (Opus 5.5 Medium) --- .../app/dialogs/DialogSearch.svelte | 267 ++++++++++++++++-- .../conversation-search.constants.ts | 28 ++ ui/apps/chat/src/lib/constants/index.ts | 1 + .../services/conversation-search.service.ts | 70 +++++ ui/apps/chat/src/lib/services/index.ts | 4 + .../stores/models-discover/index.svelte.ts | 47 +-- .../chat/src/lib/utils/conversation-search.ts | 116 ++++++++ ...conversation-search.service.svelte.test.ts | 92 ++++++ .../tests/unit/conversation-search.test.ts | 91 ++++++ 9 files changed, 667 insertions(+), 49 deletions(-) create mode 100644 ui/apps/chat/src/lib/constants/conversation-search.constants.ts create mode 100644 ui/apps/chat/src/lib/services/conversation-search.service.ts create mode 100644 ui/apps/chat/src/lib/utils/conversation-search.ts create mode 100644 ui/apps/chat/tests/client/conversation-search.service.svelte.test.ts create mode 100644 ui/apps/chat/tests/unit/conversation-search.test.ts diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte index 077a6583e13f..9a241af2835b 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte @@ -1,8 +1,23 @@ + +
    + {#key collapsed} + + + + {/key} + + {#if !source.voice} +

    {source.name}

    + {/if} + + {#if !readonly && onRemove} +
    + onRemove?.(item.id)} + stopPropagationOnClick + tooltip="Remove" + /> +
    + {/if} +
    diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte index f1d6a46cc584..2d2ee228b19f 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte @@ -1,12 +1,23 @@
    @@ -21,6 +32,19 @@

    Audio preview not available

    {/if} -

    {currentItem?.name || 'Audio'}

    +

    + {source?.voice ? VOICE_MESSAGE_LABEL : currentItem?.name || 'Audio'} +

    + + {#if transcript} +

    + Transcript: {transcript} +

    + {:else if transcribing} +

    Transcribing...

    + {/if}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index e99c1eac32f0..727ceccd7894 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -1,10 +1,13 @@ + +
{ event.preventDefault(); - - if (!canSubmit || disabled || hasLoadingAttachments) return; - - onSubmit?.(); + void submit(); }} > @@ -753,13 +807,14 @@ {disabled} expanded={isExpanded} onInput={() => { + voice.handleUserInput(); expansion.handleInput(); pickers.handleInput(); onValueChange?.(value); }} onKeydown={handleKeydown} onPaste={handlePaste} - {placeholder} + placeholder={voicePlaceholder ?? placeholder} /> {#if mcpStore.resources.hasAttachments} @@ -774,29 +829,55 @@
- - onSystemPromptClick?.({ files: uploadedFiles, message: value })} - onWorkingDirectoryClick={isWorkingDirectoryInAddMenu - ? pickers.handleWorkingDirectoryOpen - : undefined} - {showAddButton} - {showModelSelector} - {uploadedFiles} - workingDirectory={cwd} - /> + {#if voice.isActive} + void handleStopAndSend()} + onStop={() => void voice.stop()} + quiet={voice.quiet} + state={voice.state} + /> + {/if} + + +
+ + onSystemPromptClick?.({ files: uploadedFiles, message: value })} + onWorkingDirectoryClick={isWorkingDirectoryInAddMenu + ? pickers.handleWorkingDirectoryOpen + : undefined} + {showAddButton} + {showModelSelector} + voice={{ + action: voice.label, + hint: voice.hint, + prepare: () => void voice.prepare(), + show: voice.showButton, + unavailableReason: voice.unavailableReason, + unprepare: voice.unprepare + }} + workingDirectory={cwd} + /> +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte index 8664af6b2ea7..33d52171d7e0 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte @@ -2,34 +2,95 @@ import { Button } from '@ggml-org/llama-ui/ui/button'; import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip'; import { Mic, MicOff, Square } from '@lucide/svelte'; - import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; + import { + ICON_CLASS_DEFAULT, + VOICE_MODE_MESSAGE, + VOICE_PRESS_CLICK_MS + } from '#lib/constants/index.ts'; + import { MouseButton, PointerType } from '#lib/enums/index.ts'; interface Props { + /** What a press does: send a voice message or dictate. */ + action?: string; class?: string; disabled?: boolean; - hasAudioModality?: boolean; + /** Said after the action in the tooltip, e.g. that another model may be loaded. */ + hint?: string | null; isLoading?: boolean; isRecording?: boolean; /** Why the microphone can't record (no HTTPS, access denied...), shown on the button. */ micWarning?: string | null; + /** Why no model can take the recording; disables the button. */ + unavailableReason?: string | null; + /** A quieter (tertiary) button, beside the main one: send or stop. */ + secondary?: boolean; + /** With `secondary`: filled like the stop button it stands beside, not bare. */ + filled?: boolean; onMicClick?: () => void; + /** A mouse or the focus came to the button: a press may follow, the microphone can open. */ + onPrepare?: () => void; + /** It left again without a press. */ + onPrepareEnd?: () => void; } let { + action = VOICE_MODE_MESSAGE.voiceMessage, class: className = '', disabled = false, - hasAudioModality = false, + filled = false, + hint = null, isLoading = false, isRecording = false, micWarning = null, - onMicClick + onMicClick, + onPrepare, + onPrepareEnd, + secondary = false, + unavailableReason = null }: Props = $props(); - // a model without audio input disables the button; a microphone that can't record keeps it + // no model to take the recording disables the button; a microphone that can't record keeps it // tappable, so a tap can say why - const showWarning = $derived(hasAudioModality && !isRecording && !!micWarning); + const showWarning = $derived(!unavailableReason && !isRecording && !!micWarning); + // a mouse starts recording on press, not on release, so the first words are not lost; + // a touch or a key goes through the click, which is when the browser allows it + let pressedAt = -Infinity; + + function handlePointerDown(event: PointerEvent) { + if (isRecording || disabled || isLoading || unavailableReason) return; + + if (event.pointerType !== PointerType.MOUSE || event.button !== MouseButton.PRIMARY) return; + + pressedAt = performance.now(); + onMicClick?.(); + } + + // a touch presses at once, so only a mouse, a pen or the keyboard come ahead of the press + function handlePointerEnter(event: PointerEvent) { + if (event.pointerType !== PointerType.TOUCH && !isRecording) onPrepare?.(); + } + + function handlePointerLeave(event: PointerEvent) { + if (event.pointerType !== PointerType.TOUCH) onPrepareEnd?.(); + } + + function handleClick() { + // the click that ends the press that already started it; the recording bar may have + // taken the button's place meanwhile, so this one can also never come + if (performance.now() - pressedAt < VOICE_PRESS_CLICK_MS) { + pressedAt = -Infinity; + + return; + } + + onMicClick?.(); + } + const tooltip = $derived( - !hasAudioModality ? 'Current model does not support audio' : showWarning ? micWarning : null + isRecording + ? null + : (unavailableReason ?? + (showWarning ? micWarning : [action, hint].filter(Boolean).join('. '))) ); @@ -37,28 +98,41 @@ {/snippet} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte index d71a8da5d891..c895ef0c34b7 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -1,6 +1,6 @@ + + + {#snippet stop({ disabled })} + + {/snippet} + diff --git a/ui/apps/chat/src/lib/components/app/chat/index.ts b/ui/apps/chat/src/lib/components/app/chat/index.ts index fce3962c4fe4..f7626c73a4f5 100644 --- a/ui/apps/chat/src/lib/components/app/chat/index.ts +++ b/ui/apps/chat/src/lib/components/app/chat/index.ts @@ -79,6 +79,14 @@ export { default as ChatAttachmentsListItemMcpResource } from './ChatAttachments */ export { default as ChatAttachmentsListItemThumbnailFile } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte'; +/** + * An audio attachment drawn as a clip: a playable waveform (peaks computed from + * the audio when it was stored without them) and, for a voice message, its + * transcript under it on hover, focus or a tap, with the transcribing and failed + * states. `sm` in the chat form, removable; `md` in a sent message. + */ +export { default as ChatAttachmentsListItemVoice } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemVoice.svelte'; + /** * Thumbnail for image attachments with lazy loading and error fallback. * Displays image preview with configurable dimensions. Falls back to placeholder @@ -170,12 +178,20 @@ export { default as ChatForm } from './ChatForm/ChatForm.svelte'; export { default as ChatFormActionsAdd } from './ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte'; /** - * Audio recording button with real-time recording indicator. Records audio - * and converts to WAV format for upload. Only visible when the active model - * supports audio modality and setting for automatic audio input is enabled. Shows recording duration while active. + * Microphone button: starts a voice message or a dictation (its label says which), + * or, disabled, says why no model can take a recording; while recording it is the + * stop button. Shown on an empty message when voice input is available and the + * setting for the microphone on empty input is on. */ export { default as ChatFormActionRecord } from './ChatForm/ChatFormActions/ChatFormActionRecord.svelte'; +/** + * The actions row while the chat form records: cancel, the live waveform and the + * elapsed time, and stop, with a voice message's streaming text under the waveform + * and a waiting state while dictated text is transcribed after recording. + */ +export { default as ChatFormActionsRecording } from './ChatForm/ChatFormActions/ChatFormActionsRecording.svelte'; + /** * Container for chat form action buttons. Arranges file attachment, audio record, * and submit/stop buttons in a horizontal layout. Handles conditional visibility diff --git a/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte index 33be4c624d35..071b71000e92 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte @@ -1,7 +1,8 @@ @@ -35,6 +48,26 @@ /> + {#if canDictate} + + + voiceStore.toggleDictation(option.model)} + tooltip={dictationLabel} + tooltipAsTitle + /> + + {/if} + {#if isFav} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelVoiceRole.svelte b/ui/apps/chat/src/lib/components/app/models/ModelVoiceRole.svelte new file mode 100644 index 000000000000..cabc881390d4 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelVoiceRole.svelte @@ -0,0 +1,60 @@ + + + +{#if role} + {@const Icon = ICONS[role]} + + + + {#snippet child({ props })} + + + {/snippet} + + + +

{description}

+
+
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte index 2c25dddd1b68..9f8913451c92 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte @@ -4,15 +4,20 @@ import ModelContext from '../ModelContext.svelte'; import ModelDraftSubline from '../ModelDraftSubline.svelte'; import ModelId from '../ModelId.svelte'; + import ModelVoiceRole from '../ModelVoiceRole.svelte'; import ModelsManagerStatusCell from './ModelsManagerStatusCell.svelte'; import { modelRowActions } from './row-actions'; import { configuredContext, downloadProgressFor, isRowControlClick } from './utils'; import { ModelDownloadProgressBar } from '@ggml-org/llama-ui/models'; - import { Heart, MoreHorizontal } from '@lucide/svelte'; + import { Heart, Mic, MoreHorizontal } from '@lucide/svelte'; import { ContextMenuActions, DropdownMenuActions } from '#lib/components/app/index.ts'; - import { MODEL_ROW_GRID_CLASS, MODEL_ROW_TRAILING_CELL_CLASS } from '#lib/constants/index.ts'; + import { + MODEL_ROW_GRID_CLASS, + MODEL_ROW_TRAILING_CELL_CLASS, + VOICE_DICTATION_MODEL_LABEL + } from '#lib/constants/index.ts'; import { ModelRowDownloadState } from '#lib/enums/index.ts'; - import { deviceStore, modelsStore } from '#lib/stores/index.ts'; + import { deviceStore, modelsStore, voiceStore } from '#lib/stores/index.ts'; import type { ModelOption, ModelSidecarBadge } from '#lib/types/models.js'; interface Props { @@ -38,6 +43,7 @@ }: Props = $props(); let favorite = $derived(isFavorite(option)); + let dictates = $derived(voiceStore.isDictationModel(option.model)); let isHidden = $derived(modelsStore.isHidden(option.id)); // live while the download runs, frozen while it is paused let downloadProgress = $derived(downloadProgressFor(option.model)); @@ -101,9 +107,18 @@ title={option.model} /> + + + {#if dictates} + +