From 15dff06aa4bb29cfed6c1fd530ba98338eccf60f Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Fri, 2 Oct 2026 15:18:06 -0700 Subject: [PATCH 01/65] ggml-openvino: fix SWA mask detection When the SWA cache size matches the full cache size, identify SWA layers by the number of layers using each mask instead of cache size; the larger group is SWA, and a tie leaves the layers unclassified. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 26 +++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index ae36a09591da..bb80388dc080 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -791,10 +791,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr // from the first graph onwards, while the view grows with context depth and would invert the // comparison at shallow depth. // - // Layers whose leaf is smaller than the largest leaf are the windowed ones. When every layer - // reports the same extent there is no distinction to draw -- either the model has no windowed - // layers, or the window is at least as large as the context so the two caches coincide, in - // which case a windowed layer and a full-attention one compute the same thing. + // Layers whose leaf is smaller than the largest leaf are the windowed ones. Equal extents do not + // rule them out: the windowed cache is padded to n_swa + n_ubatch, which can equal the full + // context (gemma-4 at -c 1024 -ub 512). See the mask fallback below. // // Getting this wrong is silent and severe: with the windowed layers classified as // full-attention, permute's KV slicing uses attention_size instead of attention_size_swa. The @@ -839,6 +838,25 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr } } } + + // equal extents: tell the two masks apart by the layers that read them, the larger group is swa (gemma-4: 4 of 5 layers) + // groups of equal size can not be told apart, so leave the layers unclassified + if (model_params.swa_layers.empty()) { + std::map> mask_layers; + for (const auto & [layer, mask] : layer_mask) { + mask_layers[mask].push_back(layer); + } + if (mask_layers.size() == 2 && + mask_layers.begin()->second.size() != std::next(mask_layers.begin())->second.size()) { + auto swa = mask_layers.begin(); + auto other = std::next(swa); + if (other->second.size() > swa->second.size()) { + std::swap(swa, other); + } + model_params.swa_layers = swa->second; + model_params.swa_mask = swa->first; + } + } std::sort(model_params.swa_layers.begin(), model_params.swa_layers.end()); if (ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SWA_LAYERS")) { From 3f023f5b01947b07452f699068cd03d810c87021 Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Fri, 2 Oct 2026 15:18:24 -0700 Subject: [PATCH 02/65] ggml-openvino: fix SWA KV cache write indices Give SWA KV cache index tensors unique input names (a _swa suffix, like the masks) to prevent them from being merged with the full-attention cache indices. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index bb80388dc080..0af1ae9a0045 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -229,6 +229,15 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder, return get_tensor_ov_name(cgraph, tensor) + "_swa"; } } + if (!decoder->get_model_params().swa_layers.empty() && GgmlOvDecoder::is_kv_idx(tensor, op) && + op->src[2] != nullptr) { + // same as the masks: the full and the sliding-window cache get KV write indices of the same name + const ggml_tensor * cache = op->src[2]->view_src != nullptr ? op->src[2]->view_src : op->src[2]; + auto layer = extract_layer_from_name(cache->name); + if (layer.has_value() && decoder->is_swa_layer(layer.value())) { + return get_tensor_ov_name(cgraph, tensor) + "_swa"; + } + } return get_tensor_ov_name(cgraph, tensor); } From 706a4d9f2e46982630f4a5ef0cc318a723d85bf5 Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Sun, 4 Oct 2026 16:03:33 -0700 Subject: [PATCH 03/65] ggml-openvino: classify SWA layers only when the mask shows the window Two attention masks do not imply SWA: DeepSeek sparse attention uses two full-attention masks with the same name. When cache extents match, classify the larger mask group as SWA only once its mask has fewer keys per row than the other mask. Keep the classification per KV cache buffer so new sequences reuse the same graph, and include swa_layers when checking graph reuse. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 26 +++++++++++++++++++++++-- ggml/src/ggml-openvino/ggml-decoder.h | 7 ++++--- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 0af1ae9a0045..a91c9f19c4dc 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -811,6 +811,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr { std::map layer_extent; // layer -> leaf cache_k cell count std::map layer_mask; // layer -> mask it consumes + std::map layer_buffer; // layer -> id of the buffer holding its cache_k int64_t max_extent = 0; for (int i = 0; i < cgraph->n_nodes; i++) { @@ -836,6 +837,8 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr } layer_extent[layer.value()] = leaf->ne[1]; layer_mask[layer.value()] = mask; + layer_buffer[layer.value()] = + leaf->buffer != nullptr ? ggml_backend_openvino_buffer_get_ctx_id(leaf->buffer) : 0; max_extent = std::max(max_extent, leaf->ne[1]); } @@ -850,6 +853,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr // equal extents: tell the two masks apart by the layers that read them, the larger group is swa (gemma-4: 4 of 5 layers) // groups of equal size can not be told apart, so leave the layers unclassified + // two masks do not imply swa (deepseek sparse attention builds two full masks), so only classify once the window + // shows: the swa mask then keeps fewer keys per row than the other. Before that the two masks are equal. + // Remember it per KV cache buffer, so that a new sequence starting below the window keeps the same graph if (model_params.swa_layers.empty()) { std::map> mask_layers; for (const auto & [layer, mask] : layer_mask) { @@ -862,8 +868,24 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr if (other->second.size() > swa->second.size()) { std::swap(swa, other); } - model_params.swa_layers = swa->second; - model_params.swa_mask = swa->first; + static std::mutex seen_mutex; + static std::map> seen_swa_layers; // cache_k buffer id -> swa layers + const size_t buffer_id = layer_buffer[swa->second.front()]; + const int swa_kept = get_swa_window_from_mask(swa->first); + const int other_kept = get_swa_window_from_mask(other->first); + bool is_swa = swa_kept > 0 && swa_kept < other_kept; + { + std::lock_guard lock(seen_mutex); + if (is_swa && buffer_id != 0) { + seen_swa_layers[buffer_id] = swa->second; + } + auto seen = seen_swa_layers.find(buffer_id); + is_swa = is_swa || (buffer_id != 0 && seen != seen_swa_layers.end() && seen->second == swa->second); + } + if (is_swa) { + model_params.swa_layers = swa->second; + model_params.swa_mask = swa->first; + } } } std::sort(model_params.swa_layers.begin(), model_params.swa_layers.end()); diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 33b95340a1b4..a36e0ad4b210 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -47,14 +47,15 @@ struct ModelParams { memcmp(rope_params, other.rope_params, sizeof(int32_t) * 16) == 0; } + // swa_layers: the classification can change once the sliding window shows in the mask bool can_reuse_dynamically(const ModelParams & other) const { - return same_rope_params(other) && n_rs_slots == other.n_rs_slots && - has_rs_rollback == other.has_rs_rollback; + return same_rope_params(other) && n_rs_slots == other.n_rs_slots && has_rs_rollback == other.has_rs_rollback && + swa_layers == other.swa_layers; } bool can_reuse_statically(const ModelParams & other) const { return same_rope_params(other) && ctx == other.ctx && n_rs_slots == other.n_rs_slots && - has_rs_rollback == other.has_rs_rollback; + has_rs_rollback == other.has_rs_rollback && swa_layers == other.swa_layers; } bool kv_buffer_changed(const ModelParams & other) const { return kv_buffer_ctx_id != other.kv_buffer_ctx_id; } From e98f6457cc2980a14803b045ba451bc09a91fb7b Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Mon, 5 Oct 2026 07:20:27 -0700 Subject: [PATCH 04/65] ggml-openvino: classify SWA layers from the first graph Waiting for the window to appear in the mask caused a mid-sequence graph recompile (~9 s for Gemma-4 at -c 1024 after position 512). SWA classification already gives each mask group its own mask, KV write indices, and attention size, which is correct whether or not the mask is a sliding window. Stateful mask rebuild recovers the window from the mask, or the causal mask for full attention. Classify the larger of two mask groups from the first graph and drop the per-KV-buffer bookkeeping. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 40 +++++++------------------ ggml/src/ggml-openvino/ggml-decoder.h | 2 +- 2 files changed, 12 insertions(+), 30 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index a91c9f19c4dc..ed50ecfef08b 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -811,7 +811,6 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr { std::map layer_extent; // layer -> leaf cache_k cell count std::map layer_mask; // layer -> mask it consumes - std::map layer_buffer; // layer -> id of the buffer holding its cache_k int64_t max_extent = 0; for (int i = 0; i < cgraph->n_nodes; i++) { @@ -837,8 +836,6 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr } layer_extent[layer.value()] = leaf->ne[1]; layer_mask[layer.value()] = mask; - layer_buffer[layer.value()] = - leaf->buffer != nullptr ? ggml_backend_openvino_buffer_get_ctx_id(leaf->buffer) : 0; max_extent = std::max(max_extent, leaf->ne[1]); } @@ -851,11 +848,13 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr } } - // equal extents: tell the two masks apart by the layers that read them, the larger group is swa (gemma-4: 4 of 5 layers) - // groups of equal size can not be told apart, so leave the layers unclassified - // two masks do not imply swa (deepseek sparse attention builds two full masks), so only classify once the window - // shows: the swa mask then keeps fewer keys per row than the other. Before that the two masks are equal. - // Remember it per KV cache buffer, so that a new sequence starting below the window keeps the same graph + // equal extents: tell the two masks apart by the layers that read them, the larger group gets the swa role + // (gemma-4: 4 of 5 layers). Groups of equal size can not be told apart, so leave the layers unclassified. + // Two masks do not imply swa (deepseek sparse attention builds two full masks), but the role does not need + // them to: it gives each group its own mask, KV write indices and attention size, which is right either way. + // The only use of the window itself, the stateful mask rebuild, reads it back from the mask, and on a full + // mask that gives back the causal mask. Decide from the first graph, before the window shows in the mask, so + // the graph does not change, and is not recompiled, when it does. if (model_params.swa_layers.empty()) { std::map> mask_layers; for (const auto & [layer, mask] : layer_mask) { @@ -864,28 +863,11 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr if (mask_layers.size() == 2 && mask_layers.begin()->second.size() != std::next(mask_layers.begin())->second.size()) { auto swa = mask_layers.begin(); - auto other = std::next(swa); - if (other->second.size() > swa->second.size()) { - std::swap(swa, other); - } - static std::mutex seen_mutex; - static std::map> seen_swa_layers; // cache_k buffer id -> swa layers - const size_t buffer_id = layer_buffer[swa->second.front()]; - const int swa_kept = get_swa_window_from_mask(swa->first); - const int other_kept = get_swa_window_from_mask(other->first); - bool is_swa = swa_kept > 0 && swa_kept < other_kept; - { - std::lock_guard lock(seen_mutex); - if (is_swa && buffer_id != 0) { - seen_swa_layers[buffer_id] = swa->second; - } - auto seen = seen_swa_layers.find(buffer_id); - is_swa = is_swa || (buffer_id != 0 && seen != seen_swa_layers.end() && seen->second == swa->second); - } - if (is_swa) { - model_params.swa_layers = swa->second; - model_params.swa_mask = swa->first; + if (std::next(swa)->second.size() > swa->second.size()) { + swa = std::next(swa); } + model_params.swa_layers = swa->second; + model_params.swa_mask = swa->first; } } std::sort(model_params.swa_layers.begin(), model_params.swa_layers.end()); diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index a36e0ad4b210..0755dab558ab 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -47,7 +47,7 @@ struct ModelParams { memcmp(rope_params, other.rope_params, sizeof(int32_t) * 16) == 0; } - // swa_layers: the classification can change once the sliding window shows in the mask + // swa_layers: the masks and KV write indices of these layers are separate graph inputs bool can_reuse_dynamically(const ModelParams & other) const { return same_rope_params(other) && n_rs_slots == other.n_rs_slots && has_rs_rollback == other.has_rs_rollback && swa_layers == other.swa_layers; From 8c174e459a5a421eae6eba3c704b16430fb93169 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Mon, 5 Oct 2026 22:27:31 +0530 Subject: [PATCH 05/65] ggml-openvino: skip unselected graph branches and support DUP Upstream #29622 adds a mixed token/embd branch to every input embedding graph through ggml_build_forward_select(). Its nodes are not flagged for compute, but the backend translated them anyway, and the DUP in that branch was unsupported, so the scheduler split the graph and passed the embeddings across the split with a fixed token count. The first single-token decode then failed (test-thread-safety on CPU and GPU). Build the OV model from the compute nodes only, and translate a same-type contiguous DUP like CONT so the graph stays on one backend. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 1 + ggml/src/ggml-openvino/ggml-openvino.cpp | 7 +++++++ ggml/src/ggml-openvino/openvino/op_table.cpp | 1 + ggml/src/ggml-openvino/utils.cpp | 20 ++++++++++++++++++++ ggml/src/ggml-openvino/utils.h | 6 ++++++ 5 files changed, 35 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index ae36a09591da..0deda8a66ffb 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -2307,6 +2307,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_DIAG: case GGML_OP_TRI: case GGML_OP_REPEAT: + case GGML_OP_DUP: // Shape-preserving elementwise ops: the dynamic dim is unchanged from src[0]. // DIV/CLAMP are used in the MoE routing-weight normalization // (sum_rows -> clamp -> div). If they are left untracked here the dynamic diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 87ee096fa547..e0a475cd8572 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1529,6 +1529,13 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } break; } + case GGML_OP_DUP: { + // translated as CONT, so only a plain copy + if (op->type != op->src[0]->type || !ggml_are_same_shape(op, op->src[0]) || !ggml_is_contiguous(op->src[0])) { + return {false, "DUP with type conversion or non-contiguous src is not supported"}; + } + break; + } case GGML_OP_CPY: { if (op->src[0]->type != GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_BF16) { return {false, "CPY with BF16 src[1] type is not supported"}; diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index 12a0953e3cf9..23b3a2cff3ea 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -37,6 +37,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_ADD_ID", op::translate_add_id }, {"GGML_OP_CONCAT", op::translate_concat }, {"GGML_OP_CONT", op::translate_cont }, + {"GGML_OP_DUP", op::translate_cont }, {"GGML_OP_DIV", op::translate_div }, {"GGML_OP_FILL", op::translate_fill }, {"GGML_OP_GET_ROWS", op::translate_get_rows }, diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 67a4123cb195..66e9cd88f277 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -1726,6 +1726,25 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } } // namespace +// Nodes on the unselected branches of ggml_build_forward_select() stay in the graph but must not be +// computed. Keep them out of the OV model, or their inputs become parameters with fixed shapes. +static ggml_cgraph * get_compute_graph(ggml_cgraph * cgraph, ov_runtime_context & r_ctx) { + auto is_skipped = [](const ggml_tensor * node) { + return node->op != GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_COMPUTE); + }; + if (std::none_of(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, is_skipped)) { + return cgraph; + } + auto & compute = r_ctx.compute_graphs[cgraph]; + compute.nodes.clear(); + std::copy_if(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, std::back_inserter(compute.nodes), + [&](const ggml_tensor * node) { return !is_skipped(node); }); + compute.graph = *cgraph; + compute.graph.nodes = compute.nodes.data(); + compute.graph.n_nodes = (int) compute.nodes.size(); + return &compute.graph; +} + // Both execution paths use two cache levels: // 1. Reuse this backend's decoder/request via graph_key and compatibility checks. // 2. On a local miss, look up compiled_graph_key in the shared compilation cache, @@ -1744,6 +1763,7 @@ enum ggml_status ov_graph_compute(ggml_cgraph * cgraph, ggml_backend_t backend) GGML_ASSERT(ctx->runtime_context != nullptr); std::shared_ptr r_ctx = std::static_pointer_cast(ctx->runtime_context); std::lock_guard execution_lock(r_ctx->execution_mutex); + cgraph = get_compute_graph(cgraph, *r_ctx); return is_static ? ov_graph_compute_static(cgraph, r_ctx) : ov_graph_compute_dynamic(cgraph, r_ctx); } catch (const ov::Exception & e) { diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 491dbadc2e95..c34441f5e867 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -119,6 +119,12 @@ struct ov_runtime_context { std::unordered_map, graph_key_hash> ov_output_names_cache; size_t stateful_kv_size; std::map kv_state_input_name_map; + // compute-only copies of graphs that carry unselected ggml_build_forward_select() branches + struct compute_graph { + ggml_cgraph graph; + std::vector nodes; + }; + std::unordered_map compute_graphs; ov_runtime_context() : device("CPU"), stateful(false), stateful_kv_size(0) {} From 130d8bd1aeeb14907749ed423c7f948a5d374264 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Mon, 5 Oct 2026 22:27:47 +0530 Subject: [PATCH 06/65] ggml-openvino: make inp_scale_rows token dim dynamic #29622 also moves the per-token embedding scale (gemma3, gemma3n, gemma4) into a new [1, n_tokens] input. Give it a dynamic token dim and pad it per chunk on the static (NPU) path. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 7 +++++++ ggml/src/ggml-openvino/ggml-decoder.h | 5 +++++ ggml/src/ggml-openvino/utils.cpp | 9 +++++++++ 3 files changed, 21 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 0deda8a66ffb..9a4e604c09e1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1097,6 +1097,9 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, input_shape = m_is_static ? ov::PartialShape{1, 1, input->ne[1], m_prefill_chunk_size} : ov::PartialShape{1, 1, -1, -1}; + } else if (is_inp_scale_rows(input, op)) { + input_shape = ov::PartialShape{1, 1, m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1, 1}; + } else if (is_inp_mask(input, op)) { // mask if (m_is_static) { @@ -2101,6 +2104,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[src] = 0; continue; } + if (is_inp_scale_rows(src, node)) { + m_node_dynamic_dims[src] = 1; + continue; + } if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted) { m_node_dynamic_dims[src] = 1; continue; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 33b95340a1b4..a614d291acb5 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -393,6 +393,11 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { op->src[0] != nullptr && op->src[0]->op != GGML_OP_NONE; } + // per-token embedding scale [1, n_tokens] (inp->scale_rows in llama-graph.cpp) + static bool is_inp_scale_rows(const ggml_tensor * tensor, const ggml_tensor * op) { + return op->op == GGML_OP_MUL && tensor == op->src[1] && strcmp(tensor->name, "inp_scale_rows") == 0; + } + static bool is_rope_freqs_weight(const ggml_tensor * tensor, const ggml_tensor * op) { return op->op == GGML_OP_ROPE && tensor == op->src[2]; } diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 66e9cd88f277..f07e180a40f7 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -676,6 +676,15 @@ ov::Tensor get_ov_input_tensor_static_prefill(const std::shared_ptr(); + const auto * src = static_cast(ggml_tensor->data) + chunk_index * chunk_size; + std::copy(src, src + chunk_valid_size, dst); + std::fill(dst + chunk_valid_size, dst + chunk_size, 1.0f); + return input_tensor; + } + if (GgmlOvDecoder::is_inp_mean(ggml_tensor, op)) { const size_t n_seqs = ggml_tensor->ne[1]; const size_t src_stride = ggml_tensor->ne[0]; From 0087a1b5217e320bc5a6bda935b455e18d8f0e3f Mon Sep 17 00:00:00 2001 From: ravi9 Date: Mon, 5 Oct 2026 23:52:53 +0530 Subject: [PATCH 07/65] ggml-openvino: skip GPU MUL_MAT op tests with unbound Q4_1/Q4_K weights Op tests build Q4_1/Q4_K weights as u4 with an f16 zero point. The GPU plugin fails to compile that form for some row counts with "clFinish, error code: -5 CL_OUT_OF_RESOURCES", which aborts test-backend-ops on the MUL_MAT cases added in #29869 (e.g. m=1000, n=2, k=1024). Model weights use a u4 zero point and are not affected. Report these cases as unsupported on GPU until the plugin is fixed. Op tests check support before allocating, so the check matches unbound weights only; model loading probes with a dummy buffer and keeps its weights on the GPU. --- ggml/src/ggml-openvino/ggml-openvino.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index e0a475cd8572..f225afdb6160 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1575,6 +1575,14 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { (op->src[0]->buffer == nullptr || op->src[0]->buffer->usage != GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { return {false, "MUL_MAT scalar dot product with non-weight src[0] on GPU is not supported"}; } + // The GPU plugin fails to compile u4 weights with an f16 zero point for some row counts + // (clFinish CL_OUT_OF_RESOURCES). Op tests build Q4_1/Q4_K weights in that form; model weights use a + // u4 zero point. Op tests check support before allocating, while model loading checks with a dummy + // buffer, so only unbound weights are excluded. Remove once the GPU plugin is fixed. + if (ggml_openvino_is_gpu() && (op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q4_K) && + op->src[0]->buffer == nullptr) { + return {false, "MUL_MAT with unbound Q4_1/Q4_K src[0] on GPU is not supported"}; + } if (op->src[0]->ne[3] != op->src[1]->ne[3] && op->src[0]->ne[3] != 1 && op->src[1]->ne[3] != 1) { return {false, "MUL_MAT with incompatible broadcast on ne[3]: src0->ne[3]=" + std::to_string(op->src[0]->ne[3]) + ", src1->ne[3]=" + std::to_string(op->src[1]->ne[3])}; From 672083f8d20bdc39ef52da28fbf365867e1f3442 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Tue, 6 Oct 2026 00:20:46 +0530 Subject: [PATCH 08/65] ggml-openvino: create FILL in the output type translate_fill always built an f32 constant, so an f16 FILL produced f32 data and the copy back overran the f16 output buffer. Use the output type for the constant. --- ggml/src/ggml-openvino/openvino/op/fill.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/openvino/op/fill.cpp b/ggml/src/ggml-openvino/openvino/op/fill.cpp index db2fecb53caf..87358e12e8ed 100644 --- a/ggml/src/ggml-openvino/openvino/op/fill.cpp +++ b/ggml/src/ggml-openvino/openvino/op/fill.cpp @@ -20,7 +20,7 @@ OutputVector translate_fill(const NodeContext & context) { auto shape = context.get_input_shape(0).to_shape(); - auto val = ov::op::v0::Constant::create(ov::element::f32, {}, {c}); + auto val = ov::op::v0::Constant::create(context.get_output_type(), {}, {c}); auto target_shape = ov::op::v0::Constant::create(ov::element::i64, {shape.size()}, std::vector(shape.begin(), shape.end())); auto res = std::make_shared(val, target_shape); From 5f2e77ed2cf79da51d9d8bab747639ace8781009 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Tue, 6 Oct 2026 00:20:46 +0530 Subject: [PATCH 09/65] ggml-openvino: reject CONCAT with a quantized type Quantized inputs are dequantized when translated, so the backend cannot write a quantized CONCAT output. Report it as unsupported, as for CPY to a quantized type. --- ggml/src/ggml-openvino/ggml-openvino.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index f225afdb6160..22b2f45e24a6 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1369,6 +1369,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { if (op->type == GGML_TYPE_I64) { return {false, "CONCAT with I64 type is not supported"}; } + // quantized inputs are dequantized, so the output cannot be written in the quantized type + if (ggml_is_quantized(op->type)) { + return {false, "CONCAT with quantized type is not supported"}; + } if (ggml_openvino_is_gpu() && op->type == GGML_TYPE_BF16 && has_view_op_input(op)) { return {false, "CONCAT with BF16 type and VIEW input is not supported on GPU"}; } From 627e811319a087923cb4f0d3a379e8b810db1a83 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Tue, 6 Oct 2026 01:28:43 +0530 Subject: [PATCH 10/65] ggml-openvino: handle the single recurrent state gather of build_rs #29856 changed build_rs to gather all recurrent states with one GET_ROWS on the s_copy leaf and take the ubatch and extra states as views of it. The stateful path matched only the previous form, a GET_ROWS per view of s_copy, so Qwen3.5 failed with stateful execution on CPU and GPU ("is_axis_valid(axis, r)" in a Concat). For a single-slot cache, treat the GET_ROWS on the s_copy leaf as the active-state gather, keep the rank-4 layout of reshapes that read a view of it, and map the copy of the empty extra-state view to the single-slot remainder writeback. Do not warn about the dynamic dim of empty views. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 37 +++++++++++++++++-------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 9a4e604c09e1..10e82f3e602a 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -336,7 +336,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } if (op_case == 1 && m_is_stateful) { // Recurrent convolution and GDN gates retain their rank-4 layout. - bool recurrent = src->op == GGML_OP_GET_ROWS && is_recurrent_cache(src->src[0]); + // The gathered states may come through a view of the one gather of all states (see build_rs). + const auto * gather = src->op == GGML_OP_VIEW ? src->src[0] : src; + bool recurrent = gather->op == GGML_OP_GET_ROWS && is_recurrent_cache(gather->src[0]); for (int i = 0; i < m_cgraph->n_nodes && !recurrent; ++i) { const auto * consumer = m_cgraph->nodes[i]; if (consumer->op == GGML_OP_GATED_DELTA_NET) { @@ -411,15 +413,19 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { break; } case GGML_OP_GET_ROWS: { - if (node->src[1]->op == GGML_OP_VIEW) { - // GET_ROWS gathering recurrent state cache rows via the inp->s_copy index list: - // src[0] is a reshape of cache_r/cache_s, src[1] is a view of the s_copy leaf. - // op_case 1/2: active/extra rows of a multi-slot cache - // op_case 3/4: active/extra rows of a single-slot cache - if (node->src[0]->op == GGML_OP_RESHAPE && node->src[0]->src[0] != nullptr && - is_recurrent_cache(node->src[0]->src[0])) { - const bool single_slot = node->src[0]->src[0]->ne[1] == 1; + // GET_ROWS gathering recurrent state cache rows via the inp->s_copy index list: + // src[0] is a reshape of cache_r/cache_s, src[1] is a view of the s_copy leaf, or the leaf itself + // when one gather covers all states (see build_rs). + // op_case 1/2: active/extra rows of a multi-slot cache + // op_case 3/4: active/extra rows of a single-slot cache + if (node->src[0]->op == GGML_OP_RESHAPE && node->src[0]->src[0] != nullptr && + is_recurrent_cache(node->src[0]->src[0])) { + const bool single_slot = node->src[0]->src[0]->ne[1] == 1; + if (node->src[1]->op == GGML_OP_VIEW) { op_case = (node->src[1]->view_offs == 0 ? 1 : 2) + (single_slot ? 2 : 0); + } else if (single_slot) { + // a single-slot cache holds exactly the one state the gather selects + op_case = 3; } } break; @@ -579,6 +585,12 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) { op_case = 4; break; + } else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr && + node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr && + is_recurrent_cache(node->src[1]->view_src) && node->src[1]->view_src->ne[1] == 1) { + // defrag remainder writeback of a single-slot cache, taken from a view of the one gather of + // all states (see build_rs) + op_case = 9; } } else if (node->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr && @@ -2188,8 +2200,11 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { } if (m_node_dynamic_dims[node] != -1 && dynamic_dim_value != node->ne[m_node_dynamic_dims[node]]) { m_node_dynamic_dims[node] = -1; - GGML_LOG_WARN("ggml-openvino: dynamic dim value mismatch for VIEW node '%s', src[0]: '%s'\n", - node->name, node->src[0]->name); + // an empty view, e.g. the extra states of a single-slot recurrent cache, always mismatches + if (ggml_nelements(node) > 0) { + GGML_LOG_WARN("ggml-openvino: dynamic dim value mismatch for VIEW node '%s', src[0]: '%s'\n", + node->name, node->src[0]->name); + } } } break; From 5802ab87d8a8f722d4ee2603b8012c6e8701d7cc Mon Sep 17 00:00:00 2001 From: Mustafa Cavus Date: Sat, 3 Oct 2026 03:37:11 +0200 Subject: [PATCH 11/65] openvino: align eltwise operand ranks to work around a GPU-plugin defect --- .../src/ggml-openvino/ggml-openvino-extra.cpp | 1 + .../openvino/pass/align_eltwise_ranks.cpp | 64 +++++++++++++++++++ .../openvino/pass/align_eltwise_ranks.h | 38 +++++++++++ .../openvino/translate_session.cpp | 12 ++++ 4 files changed, 115 insertions(+) create mode 100644 ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp create mode 100644 ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 0257e23dbf32..14a0b0382b0d 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -131,6 +131,7 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_ENABLE_FALLBACK", "GGML_OPENVINO_MANUAL_GQA_ATTN", + "GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN", "GGML_OPENVINO_MOE_OP", "GGML_OPENVINO_MEMORY_OPTIMIZE", "GGML_OPENVINO_RELEASE_WEIGHTS", diff --git a/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp new file mode 100644 index 000000000000..7526fd150851 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp @@ -0,0 +1,64 @@ +#include "align_eltwise_ranks.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace pass { + +AlignEltwiseOperandRanks::AlignEltwiseOperandRanks() { + auto eltwise_m = ov::pass::pattern::wrap_type(); + + const auto callback = [this](ov::pass::pattern::Matcher & m) { + auto node = m.get_match_root(); + if (node->get_input_size() != 2) { + return false; + } + + auto lhs = node->input_value(0); + auto rhs = node->input_value(1); + + // A tensor-vs-Constant mismatch is the norm's own eps / 1-over-sqrt arithmetic. That + // folds into the `rms` primitive itself instead of becoming a fused eltwise post-op, + // so it is not affected and is left alone. + if (ov::is_type(lhs.get_node()) || + ov::is_type(rhs.get_node())) { + return false; + } + + const auto lhs_rank = lhs.get_partial_shape().rank(); + const auto rhs_rank = rhs.get_partial_shape().rank(); + if (lhs_rank.is_dynamic() || rhs_rank.is_dynamic() || lhs_rank == rhs_rank) { + return false; + } + + const size_t shorter_idx = lhs_rank.get_length() < rhs_rank.get_length() ? 0 : 1; + const auto & shorter = shorter_idx == 0 ? lhs : rhs; + const int64_t diff = std::abs(lhs_rank.get_length() - rhs_rank.get_length()); + + std::vector axes(static_cast(diff)); + std::iota(axes.begin(), axes.end(), 0); + auto unsqueeze = std::make_shared( + shorter, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ axes.size() }, axes)); + + node->input(shorter_idx).replace_source_output(unsqueeze->output(0)); + register_new_node(unsqueeze); + return true; + }; + + register_matcher( + std::make_shared(eltwise_m, "ov::frontend::ggml::pass::AlignEltwiseOperandRanks"), + callback); +} + +} // namespace pass +} // namespace ggml +} // namespace frontend +} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h new file mode 100644 index 000000000000..21ffbea0f2d6 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace pass { + +// Give a binary eltwise op's two operands the same rank, by unsqueezing leading axes onto the +// shorter one. +// +// This is semantically a no-op -- NUMPY broadcasting already left-pads the lower-rank operand +// with 1s, and the result rank is max(rank_a, rank_b) either way. It exists purely to work +// around an OpenVINO GPU-plugin defect: an eltwise op whose operands differ in rank is computed +// incorrectly once the plugin fuses it as a post-op into an `rms` primitive. gemma-4 dense hits +// this under stateful execution, where the layer tail adds a rank-3 residual to the rank-4 +// RMS-norm output; the model then degenerates into repeated tokens on GPU while CPU is correct. +// Equalising the ranks keeps the fusion and makes it compute the right answer. +// +// Deliberately a graph pass rather than something the op translators do: rank is load-bearing +// during translation (several translators and later passes read operand ranks), and rewriting +// operands mid-translate breaks the attention path. Running after the graph is complete avoids +// that entirely. +// +// Only applies when both operands are real tensors -- a tensor-vs-Constant mismatch is the +// RMS norm's own eps/rsqrt arithmetic, which folds into the `rms` primitive rather than +// becoming a fused post-op, and is not affected by the defect. +class AlignEltwiseOperandRanks : public ov::pass::MatcherPass { +public: + OPENVINO_MATCHER_PASS_RTTI("ov::frontend::ggml::pass::AlignEltwiseOperandRanks") + AlignEltwiseOperandRanks(); +}; + +} // namespace pass +} // namespace ggml +} // namespace frontend +} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index 5a3d11f2dcdd..ec3596de200d 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -7,6 +7,7 @@ #include "input_model.h" #include "pass/fuse_argsort_topk.h" #include "pass/fuse_moe_router.h" +#include "pass/align_eltwise_ranks.h" #include "pass/fuse_moe_compressed.h" #include "pass/fuse_to_conv.h" #include "pass/kv_state_seq_axis.h" @@ -498,6 +499,17 @@ std::shared_ptr TranslateSession::apply_transformations(std::shared_ptr(); } + // Workaround for an OpenVINO GPU-plugin defect: an eltwise op whose operands differ in + // rank is computed wrongly once the plugin fuses it as a post-op into `rms`. gemma-4 + // dense under stateful execution adds a rank-3 residual to the rank-4 norm output and + // decodes garbage on GPU while CPU is correct. Equalising the ranks is a no-op for + // NUMPY broadcasting and makes the fused path correct. + // Remove once the plugin guards that fusion. Opt out with + // GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN=1. + if (ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN")) { + manager.register_pass(); + } + if (ggml_model_decoder->is_stateful()) { const auto kv_param_res_names = ggml_model_decoder->get_kv_param_res_names(); const auto kv_param_res_pairs = get_kv_param_res_pairs(model, kv_param_res_names); From 409ba457cccd275ed78e6987fb15b964eca87659 Mon Sep 17 00:00:00 2001 From: Mustafa Cavus Date: Fri, 2 Oct 2026 17:57:27 +0200 Subject: [PATCH 12/65] openvino: match the MoE fusion on the rank-3 stateful graph --- .../openvino/pass/fuse_moe_compressed.cpp | 59 +++++++++++++++---- 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/ggml/src/ggml-openvino/openvino/pass/fuse_moe_compressed.cpp b/ggml/src/ggml-openvino/openvino/pass/fuse_moe_compressed.cpp index db8fc6133488..3041a6ca743a 100644 --- a/ggml/src/ggml-openvino/openvino/pass/fuse_moe_compressed.cpp +++ b/ggml/src/ggml-openvino/openvino/pass/fuse_moe_compressed.cpp @@ -321,22 +321,39 @@ FuseMoeCompressedFusedGateUp::FuseMoeCompressedFusedGateUp() { auto gate_up_w_m = any_input(); auto ids_gate_up_m = any_input(); auto bgm_fused_m = wrap_type({ a_m, gate_up_w_m, ids_gate_up_m, any_input() }); - auto gu_u_m = optional({ wrap_type( - { wrap_type({ bgm_fused_m, any_input() }), any_input() }) }); + // Two graph shapes reach here. The rank-4 (stateless) graph restores the batch dim with an + // Unsqueeze after the Transpose and may Convert afterwards: + // GatherMatmul -> Transpose -> Unsqueeze -> [Convert] -> Slice + // The rank-3 (stateful) graph never drops to a batch dim at all, so there is no Unsqueeze + // here - it appears later, between the GEGLU and the down Reshape - and the Convert sits on + // the other side of the Transpose: + // GatherMatmul -> Convert -> Transpose -> Slice + // optional({a, b}) matches T(a, b) or bare a, so one pattern covers both. + auto gu_t_m = + wrap_type({ optional({ bgm_fused_m }), any_input() }); + auto gu_u_m = + optional({ optional({ gu_t_m, any_input() }) }); auto gate_slice_m = wrap_type({ gu_u_m, any_input(), any_input(), any_input(), any_input() }); auto up_slice_m = wrap_type({ gu_u_m, any_input(), any_input(), any_input(), any_input() }); auto gelu_m = wrap_type({ gate_slice_m }); auto geglu_m = wrap_type({ gelu_m, up_slice_m }); + // The rank-3 graph inserts the Unsqueeze the gate/up branch lacked right here, before the + // Reshape that feeds the down projection; the rank-4 graph goes straight from the GEGLU + // into the Reshape. auto d_t_m = wrap_type( - { optional({ wrap_type({ geglu_m, any_input() }) }), + { optional({ wrap_type( + { optional({ geglu_m, any_input() }), any_input() }) }), any_input() }); auto down_w_m = any_input(); auto ids_down_m = any_input(); auto bgm_down_m = wrap_type({ d_t_m, down_w_m, ids_down_m, any_input() }); - auto down_u_m = optional({ wrap_type( - { wrap_type({ bgm_down_m, any_input() }), any_input() }) }); + // Same two shapes as the gate/up branch above. + auto down_t_m = + wrap_type({ optional({ bgm_down_m }), any_input() }); + auto down_u_m = + optional({ optional({ down_t_m, any_input() }) }); // gemma-4 applies an extra per-expert output scale to the down projection before the // router-weight multiply (llama-graph.cpp's ffn_down_exps.scale); FuseMoeCompressed's @@ -421,13 +438,20 @@ FuseMoeCompressedFusedGateUp::FuseMoeCompressedFusedGateUp() { } const size_t top_k = ids_pshape[ids_pshape.rank().get_length() - 1].get_length(); - // routing weights arrive as [1, n_tokens, top_k, 1]; the op wants [..., top_k] - auto routing = pm.at(routing_m); - const auto routing_pshape = routing.get_partial_shape(); - if (routing_pshape.rank().is_dynamic() || routing_pshape.rank().get_length() != 4 || - routing_pshape[3] != 1) { + // Routing weights arrive as [1, n_tokens, top_k, 1] on the rank-4 (stateless) graph and + // as [n_tokens, top_k, 1] on the rank-3 (stateful) one, which is the same thing without + // the leading batch dim. Normalise the rank-3 form up to the rank-4 one so everything + // below - and the op's own config - stays in the shape that is already validated on the + // stateless path; the batch dim is taken back off the result at the end. + const auto routing_in = pm.at(routing_m); + const auto routing_pshape = routing_in.get_partial_shape(); + const auto routing_rank = routing_pshape.rank(); + if (routing_rank.is_dynamic() || (routing_rank.get_length() != 4 && routing_rank.get_length() != 3) || + routing_pshape[routing_rank.get_length() - 1] != 1) { return false; } + const bool batchless = routing_rank.get_length() == 3; + // Fold gemma-4's per-expert output scale into the routing weights: the reduction is // sum_e(routing[e] * scale[e] * down_out[e]), and MOECompressed only takes one // per-expert weight, so pre-multiply it into routing here (same [.., top_k, 1] shape). @@ -435,7 +459,11 @@ FuseMoeCompressedFusedGateUp::FuseMoeCompressedFusedGateUp() { if (down_scale.get_partial_shape() != routing_pshape) { return false; } - routing = std::make_shared(routing, down_scale); + ov::Output routing = std::make_shared(routing_in, down_scale); + if (batchless) { + routing = std::make_shared( + routing, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 0 })); + } routing = std::make_shared( routing, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 3 })); if (ids_pshape.rank().get_length() == 2) { @@ -494,10 +522,19 @@ FuseMoeCompressedFusedGateUp::FuseMoeCompressedFusedGateUp() { auto moe = std::make_shared(args, config); ov::Output result = moe->output(0); + // The op was fed the batched form, so it produces [1, n_tokens, hidden]. On the rank-3 + // graph the ReduceSum being replaced is [n_tokens, hidden], so drop the batch dim again. + if (batchless) { + result = std::make_shared( + result, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 0 })); + } const auto root_type = m.get_match_root()->get_output_element_type(0); if (result.get_element_type() != root_type) { result = std::make_shared(result, root_type); } + if (result.get_partial_shape() != m.get_match_root()->get_output_partial_shape(0)) { + return false; + } result.get_node_shared_ptr()->set_friendly_name(m.get_match_root()->get_friendly_name()); ov::copy_runtime_info(m.get_matched_nodes(), result.get_node_shared_ptr()); From 39dacd4f602a35fb787ce6c1f75b6ebc5efbc65e Mon Sep 17 00:00:00 2001 From: ravi9 Date: Tue, 6 Oct 2026 06:56:13 +0530 Subject: [PATCH 13/65] ggml-openvino: do not unsqueeze an RMS norm output in AlignEltwiseOperandRanks The pass unsqueezes the lower-rank operand of an Add/Multiply/Subtract whose operand ranks differ. In gemma-3 the lower-rank operand of the post-attention residual add is the norm output, and unsqueezing it makes the GPU plugin compute the layer wrongly: gemma-3 returns empty answers on GPU with stateful execution. Skip the rewrite when the lower-rank operand is an RMS norm output. --- .../openvino/pass/align_eltwise_ranks.cpp | 32 +++++++++++++++++++ .../openvino/pass/align_eltwise_ranks.h | 3 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp index 7526fd150851..eae5b2c4e901 100644 --- a/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp +++ b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.cpp @@ -3,7 +3,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -13,6 +15,29 @@ namespace frontend { namespace ggml { namespace pass { +namespace { + +// True for an RMS-norm output, x * (1 / sqrt(mean(x^2) + eps)) as translate_rms_norm builds it, optionally +// scaled by the norm weight. +bool is_rms_norm_output(const ov::Output & value, int depth = 1) { + const auto * node = value.get_node(); + if (!ov::is_type(node)) { + return false; + } + for (const auto & input : node->input_values()) { + const auto * src = input.get_node(); + if (ov::is_type(src) && ov::is_type(src->get_input_node_ptr(1))) { + return true; + } + if (depth > 0 && is_rms_norm_output(input, depth - 1)) { + return true; + } + } + return false; +} + +} // namespace + AlignEltwiseOperandRanks::AlignEltwiseOperandRanks() { auto eltwise_m = ov::pass::pattern::wrap_type(); @@ -41,6 +66,13 @@ AlignEltwiseOperandRanks::AlignEltwiseOperandRanks() { const size_t shorter_idx = lhs_rank.get_length() < rhs_rank.get_length() ? 0 : 1; const auto & shorter = shorter_idx == 0 ? lhs : rhs; + + // The defect is with the norm output as the higher-rank operand. When the norm output is the + // lower-rank one (gemma-3 adds it to a rank-4 residual), unsqueezing it puts the Unsqueeze between + // `rms` and its post-op, and the GPU plugin then computes the layer wrongly. + if (is_rms_norm_output(shorter)) { + return false; + } const int64_t diff = std::abs(lhs_rank.get_length() - rhs_rank.get_length()); std::vector axes(static_cast(diff)); diff --git a/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h index 21ffbea0f2d6..04f59cce6187 100644 --- a/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h +++ b/ggml/src/ggml-openvino/openvino/pass/align_eltwise_ranks.h @@ -25,7 +25,8 @@ namespace pass { // // Only applies when both operands are real tensors -- a tensor-vs-Constant mismatch is the // RMS norm's own eps/rsqrt arithmetic, which folds into the `rms` primitive rather than -// becoming a fused post-op, and is not affected by the defect. +// becoming a fused post-op, and is not affected by the defect. The norm output itself is never +// unsqueezed: when it is the lower-rank operand (gemma-3), that breaks the fused path instead. class AlignEltwiseOperandRanks : public ov::pass::MatcherPass { public: OPENVINO_MATCHER_PASS_RTTI("ov::frontend::ggml::pass::AlignEltwiseOperandRanks") From a4493f9c064d94b5bc0a7fa6fe615ee1154875c1 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Tue, 6 Oct 2026 07:01:18 +0530 Subject: [PATCH 14/65] docs : update OpenVINO validated models --- docs/backend/OPENVINO.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index c9bbc9a9e38e..decc588a9f4c 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -113,13 +113,13 @@ Although, the validated models below were tested with `llama-cli` using the `Q4_ | [bartowski/Qwen_Qwen3-1.7B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3-1.7B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ | | [Qwen/Qwen3-4B-Q4_K_M](https://huggingface.co/Qwen/Qwen3-4B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ | | [lm-kit/Qwen3-8B-Q4_K_M](https://huggingface.co/lm-kit/qwen-3-8b-instruct-gguf) | ✓ / ✓ | ✓ / ✓ | ✓ | -| [bartowski/Qwen_Qwen3.5-0.8B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-0.8B-GGUF) | ✓ / ✓ | ✓ / ~ | ✗ | -| [bartowski/Qwen_Qwen3.5-2B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-2B-GGUF) | ✓ / ✓ | ✓ / ~ | ✗ | -| [bartowski/Qwen_Qwen3.5-4B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF) | ✓ / ✓ | ✓ / ~ | ✗ | -| [lmstudio-community/Qwen3.5-9B-Q4_K_M](https://huggingface.co/lmstudio-community/Qwen3.5-9B-GGUF) | ✓ / ✓ | ✓ / ~ | ✗ | +| [bartowski/Qwen_Qwen3.5-0.8B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-0.8B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ | +| [bartowski/Qwen_Qwen3.5-2B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-2B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ | +| [bartowski/Qwen_Qwen3.5-4B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ | +| [lmstudio-community/Qwen3.5-9B-Q4_K_M](https://huggingface.co/lmstudio-community/Qwen3.5-9B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ | | | | | | | [unsloth/gemma-3-4b-it-Q4_K_M](https://huggingface.co/unsloth/gemma-3-4b-it-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ | -| [bartowski/google_gemma-4-E2B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E2B-it-GGUF) | ✓ / ✓ | ✓ / ~ | ~ | +| [bartowski/google_gemma-4-E2B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E2B-it-GGUF) | ✓ / ✓ | ✓ / ✓ | ~ | | [bartowski/google_gemma-4-E4B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E4B-it-GGUF) | ✓ / ✓ | ✗ / ✗ | ✓ | | [bartowski/gemma-4-12B-it-Q4_K_M](https://huggingface.co/bartowski/gemma-4-12B-it-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ | | | | | | From 84232f4794f054e8192b809764581096a18e9108 Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Mon, 5 Oct 2026 11:34:08 -0700 Subject: [PATCH 15/65] ggml-openvino: derive attention sizes from the KQ mask shape Dynamic CPU/GPU graphs previously passed n_seq_active and attention_size(_swa) as separate inputs. Derive these values directly from the KQ mask shape using ShapeOf + Gather inside the model. This allows the GPU plugin to infer the Q reshape and KV slice shapes from shape inference rather than runtime input values. Q's head size also becomes static, enabling the fused SDPA kernel. GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK=1 restores the previous separate-input behavior. The fused SDPA path also requires two supporting changes: - Clamp the GPU mask to -30000. A key block that is entirely -inf for a row produces NaNs in the fused kernel. - Restate the head count and head size after the KV slice. The plugin loses all slice dimensions when the end index is dynamic, causing SDPA to fall back to the reference kernel. Additional graph and quantization improvements: - Skip the identity reshape of rows in SET_ROWS. - Share a single Split for one-element view slices in dynamic GPU graphs (e.g. Gemma-4 per-layer embeddings), replacing one StridedSlice per layer. - Add GGML_OPENVINO_REQUANT_EMBD=native (off by default) to preserve the file's native quantization for token_embd/output instead of requantizing to Q8_0_C. - Include both environment settings in the graph and model cache keys and document them. --- docs/backend/OPENVINO.md | 2 ++ ggml/src/ggml-openvino/README.md | 2 +- ggml/src/ggml-openvino/ggml-decoder.cpp | 26 +++++++++++++++++ ggml/src/ggml-openvino/ggml-decoder.h | 3 ++ .../src/ggml-openvino/ggml-openvino-extra.cpp | 13 +++++++++ ggml/src/ggml-openvino/ggml-openvino-extra.h | 3 ++ ggml/src/ggml-openvino/model-cache.cpp | 2 ++ ggml/src/ggml-openvino/openvino/decoder.h | 3 ++ .../openvino/op/flash_attn_ext.cpp | 9 ++++++ .../src/ggml-openvino/openvino/op/permute.cpp | 28 +++++++++++++++++-- .../ggml-openvino/openvino/op/set_rows.cpp | 17 +++++++---- .../openvino/translate_session.cpp | 16 +++++++++-- ggml/src/ggml-openvino/openvino/utils.cpp | 27 +++++++++++++++++- ggml/src/ggml-openvino/utils.cpp | 5 ++++ 14 files changed, 144 insertions(+), 12 deletions(-) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index decc588a9f4c..eb629167fd62 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -723,12 +723,14 @@ Boolean flags follow a uniform convention: set to a **positive integer** (e.g. ` | `GGML_OPENVINO_DISABLE_CACHE` | Boolean | `0` | Disable the in-process compiled-model / decoder cache (cache is on by default). Set to `1` to disable. | | `GGML_OPENVINO_DISABLE_KV_SLICE` | Boolean | `0` | Disable the KV-cache input-tensor slicing optimization (slicing is on by default on CPU/GPU). Set to `1` to disable. | | `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | Boolean | `0` | Disable the stateful KV-state sequence-axis relayout (relayout is on by default). It moves the KV state sequence axis from dim 1 to dim 2, so the GPU plugin can append new tokens in place instead of copying the whole state every token, and the reader side no longer transposes the whole accumulated state. Set to `1` to disable. | +| `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` | Boolean | `0` | Dynamic CPU/GPU graphs read the active sequence count and the attended KV length from the shape of the KQ mask inside the model, so the GPU plugin can infer the attention shapes without waiting for input values and selects its fused SDPA kernel. Set to `1` to pass them as separate inputs instead. | | `GGML_OPENVINO_MANUAL_GQA_ATTN` | Boolean | device-based | Tri-state. When **unset**, manual GQA attention is enabled by default on `GPU` and disabled on other devices. Set to a positive integer to force-enable, or `0` to force-disable. | | `GGML_OPENVINO_MEMORY_OPTIMIZE` | Boolean | `0` | Umbrella switch for compile-time memory reductions. Enables `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS` unless those fine-grained variables are explicitly set. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM`| Boolean | inherits from `GGML_OPENVINO_MEMORY_OPTIMIZE` | Reduce compile-time host memory use by streaming weight requantization and avoiding extra weight-node materialization where possible. Set explicitly to override the umbrella switch. | | `GGML_OPENVINO_RELEASE_WEIGHTS` | Boolean | inherits from `GGML_OPENVINO_MEMORY_OPTIMIZE` on GPU | GPU-only. Release host weight buffers after the compiled model cache can reuse the device/plugin copy. Requires stable graph shapes; dynamic workloads that need recompilation should leave this disabled. | | `GGML_OPENVINO_SPILL_DIR` | String | `not set` | Directory for a disk-backed weight buffer. When set, the repacked weight buffer is mapped from an unlinked file on this path instead of anonymous memory, so its pages are reclaimable under memory pressure instead of staying pinned, cutting the load-time host memory peak. Must point at real storage; a tmpfs mount (e.g. `/tmp` on many systems) backs it with RAM and makes the peak worse. | | `GGML_OPENVINO_REQUANT_KQUANT` | String | `not set` | Requantize Q6_K/Q5_K weights (and matching MoE expert weights) to a 4-bit target instead of the default Q8_0_C, trading accuracy for less memory traffic. One of `q4_asym64` (Q6_K/Q5_K only, keeps a real zero point at group 64), `q4_asym64_all` (also requantizes Q4_K), `q4_sym128` (Q6_K/Q5_K only), `q4_sym128_all` (Q4_K too, drops its per-group zero point), or `native` (no requantization). | +| `GGML_OPENVINO_REQUANT_EMBD` | String | `not set` | `native` keeps `token_embd` and `output` in their file quantization instead of requantizing them to Q8_0_C (CPU/GPU; for tied embeddings this is also the LM head). Less memory traffic per token at a small accuracy cost. | | `GGML_OPENVINO_PROFILING` | Integer | `0` | `1` logs execution timing; `2` or higher also enables OpenVINO and OpenCL profiling. | | `GGML_OPENVINO_DEBUG_NODE` | String | `not set` | Add the named graph nodes as compiled outputs for debugging. Separate multiple names with commas. | | `GGML_OPENVINO_MOE_OP` | Boolean | `1` | On GPU, set to `0` to keep the unfused GatherMatmul path. | diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 6a23f62bf246..a3c6af9ba8de 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -29,7 +29,7 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally. -Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. +Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_REQUANT_EMBD`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 10e82f3e602a..27a3e49e188b 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -940,11 +940,17 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr memcpy(&offset, cache_k_view->op_params, sizeof(size_t)); compute_params.seq_active_start = offset / seq_size; + // a mask that is itself a graph input has the shape of its OV parameter + const std::string mask_name = mask->op != GGML_OP_NONE ? std::string() : + mask == model_params.swa_mask ? get_tensor_ov_name(cgraph, mask) + "_swa" : + get_tensor_ov_name(cgraph, mask); if (layer_is_swa) { compute_params.attention_size_swa = mask->ne[0]; compute_params.swa_window = get_swa_window_from_mask(mask); + compute_params.mask_swa_name = mask_name; } else { compute_params.attention_size = mask->ne[0]; + compute_params.mask_name = mask_name; } if (is_static) { compute_params.attention_size = model_params.ctx_per_seq; @@ -958,6 +964,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr if (node->src[1]->op == GGML_OP_PERMUTE && node->src[1]->src[0]->op == GGML_OP_VIEW && node->src[1]->src[0]->src[0]->op == GGML_OP_ROPE) { compute_params.attention_size = node->ne[0]; + compute_params.mask_name.clear(); } } @@ -965,6 +972,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr if (node->op == GGML_OP_TRANSPOSE && node->src[0]->op == GGML_OP_PERMUTE && node->src[0]->src[0]->op == GGML_OP_VIEW) { compute_params.attention_size = node->ne[0]; + compute_params.mask_name.clear(); if (is_static) { compute_params.attention_size = model_params.ctx_per_seq; } @@ -1248,6 +1256,24 @@ void GgmlOvDecoder::add_extra_inputs() { } // create_1d_input("token_len", m_compute_params.token_len_per_seq * m_compute_params.n_seq_active); + // n_seq_active and attention_size(_swa) are dimensions of the KQ masks. Read them from the mask shape inside the + // model: the GPU plugin then gets the Q Reshape and KV Slice shapes from shape inference instead of waiting for + // the input values on the device + if (!m_is_static && !m_is_stateful && ggml_openvino_shape_from_mask_enabled()) { + auto from_mask = [this](const std::string & name, const std::string & mask, int64_t axis) { + auto it = m_model_extra_inputs.find(name); + if (it != m_model_extra_inputs.end() && !mask.empty() && m_model_inputs.count(mask) != 0) { + it->second.shape_source = mask; + it->second.shape_axis = axis; + } + }; + const auto & full = m_compute_params.mask_name; + const auto & swa = m_compute_params.mask_swa_name; + from_mask("attention_size", full, 3); + from_mask("attention_size_swa", swa, 3); + from_mask("n_seq_active", full.empty() ? swa : full, 0); + } + if (m_compute_params.cache_rs_reset_idx != -1 && m_model_params.n_rs_slots != 1) { // Whether/which cache slot to reset varies per compute call (e.g. a new sequence starting // vs. continued decoding). can_reuse_statically() does not invalidate the cached static diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index a614d291acb5..6087ca6626b6 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -66,6 +66,9 @@ struct ComputeParams { int attention_size = -1; int attention_size_swa = -1; int attention_size_static = -1; // encoder/cross-attn KV fill level (whisper) + // OV names of the KQ mask inputs that n_seq_active (mask->ne[3]) and attention_size(_swa) (mask->ne[0]) were read from + std::string mask_name; + std::string mask_swa_name; // Sliding window width, read back from the band of ggml's own SWA mask. ggml never passes // n_swa down to a backend, but fill_mask() bakes it into the mask contents, so the widest // unmasked row recovers it. Shorter than n_swa while the sequence is still short, which is diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 14a0b0382b0d..4c00a44ebb14 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -141,7 +141,9 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_NATIVE_SOFTPLUS", "GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", "GGML_OPENVINO_REQUANT_KQUANT", + "GGML_OPENVINO_REQUANT_EMBD", "GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT", + "GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK", // Build the precise (but O(n_nodes)) graph cache key. Needed by op tests. "GGML_OPENVINO_FULL_GRAPH_KEY", }; @@ -322,6 +324,10 @@ bool ggml_openvino_is_gpu() { return has_prefix(ggml_openvino_get_device_name(), "GPU"); } +bool ggml_openvino_shape_from_mask_enabled() { + return ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK") == 0; +} + size_t ggml_openvino_max_alloc_size() { return ggml_openvino_get_device_config().max_alloc_size; } @@ -356,6 +362,13 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * if (no_requant) { return std::nullopt; } + // GGML_OPENVINO_REQUANT_EMBD=native keeps token_embd/output in the file's quantization (tied models: also the lm_head) + const bool is_embd_or_output = + strncmp(tensor->name, "token_embd.weight", 17) == 0 || strncmp(tensor->name, "output.weight", 13) == 0; + const char * rq_embd = ggml_openvino_getenv_str("GGML_OPENVINO_REQUANT_EMBD"); + if (is_embd_or_output && rq_embd && strcmp(rq_embd, "native") == 0 && !ggml_openvino_is_npu()) { + return std::nullopt; + } if (strncmp(tensor->name, "token_embd.weight", 17) == 0) { return ((ggml_openvino_is_npu() && tensor->type == GGML_TYPE_Q6_K) ? ExtraQuantType::F16 : ExtraQuantType::Q8_0_C); diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 3a58b2d02803..9b42ac721068 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -120,6 +120,9 @@ bool ggml_openvino_is_npu(); // Check if running on a GPU (GPU, GPU.0, GPU.1, ...) bool ggml_openvino_is_gpu(); +// Read n_seq_active and attention_size(_swa) from the KQ mask shape (off with GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK=1) +bool ggml_openvino_shape_from_mask_enabled(); + // Largest single memory object the device can allocate, SIZE_MAX when there is no known limit size_t ggml_openvino_max_alloc_size(); diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index c8c5fb5adb8e..91af222c6f54 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -166,6 +166,7 @@ bool ggml_openvino_model_cache_only() { static const char * cache_settings[] = { "GGML_OPENVINO_REQUANT_KQUANT", + "GGML_OPENVINO_REQUANT_EMBD", "GGML_OPENVINO_NATIVE_SOFTPLUS", "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_MANUAL_GQA_ATTN", @@ -175,6 +176,7 @@ static const char * cache_settings[] = { "GGML_OPENVINO_REDUCE_COMPILE_MEM", "GGML_OPENVINO_MEMORY_OPTIMIZE", "GGML_OPENVINO_PROFILING", + "GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK", }; void ggml_openvino_model_cache_init() { diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index ec6975282a54..1294146b60eb 100644 --- a/ggml/src/ggml-openvino/openvino/decoder.h +++ b/ggml/src/ggml-openvino/openvino/decoder.h @@ -23,6 +23,9 @@ struct ModelExtraInputInfo { Shape shape; int64_t value; bool is_parameter; + // when set, the value is read from dimension shape_axis of this model input instead of a Parameter + std::string shape_source; + int64_t shape_axis = -1; }; class GgmlDecoder : public DecoderBase { diff --git a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp index 44c6dbc03ddb..60856d20bc72 100644 --- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp +++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -222,6 +223,14 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) { k = tile_kv(num_heads, num_heads_kv, head_size, k); v = tile_kv(num_heads, num_heads_kv, head_size, v); + // With n_seq_active read from the mask shape, the GPU plugin knows Q's head size and uses its fused SDPA kernel. + // That kernel works on blocks of keys: a block fully masked with -inf for a row gives exp(-inf - -inf) = NaN, + // which spreads to the row's result, so mask with a large finite value instead + if (has_mask && ggml_openvino_is_gpu() && !context.is_stateful() && ggml_openvino_shape_from_mask_enabled()) { + mask = std::make_shared( + mask, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, std::vector{-30000.0f})); + } + constexpr auto causal = false; if (has_mask) { auto sdpa = std::make_shared(q, k, v, mask, scale_node, causal); diff --git a/ggml/src/ggml-openvino/openvino/op/permute.cpp b/ggml/src/ggml-openvino/openvino/op/permute.cpp index df4f038984c5..a9834d99f54a 100644 --- a/ggml/src/ggml-openvino/openvino/op/permute.cpp +++ b/ggml/src/ggml-openvino/openvino/op/permute.cpp @@ -121,7 +121,26 @@ OutputVector translate_permute(const NodeContext & context) { auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0}); auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1}); - if (op_case == 3 || op_case == 4) { + if ((op_case == 3 || op_case == 4) && n_seq == 1 && perm_values == std::vector{0, 2, 1, 3}) { + // one sequence: slice the cache [1, 1, ctx, n_heads * head_size] on its context axis, then split the + // heads. The reshape after the slice also restates the head count and head size: the GPU plugin loses + // all dimensions of a slice with a runtime end, and SDPA would then run its reference kernel + auto two = ov::op::v0::Constant::create(ov::element::i64, {1}, {2}); + auto sliced = std::make_shared(src, zero, attention_size, one, two); + if (n_heads == 1) { + res = std::make_shared( + sliced, + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1, head_size}), + false); + } else { + auto split = std::make_shared( + sliced, + ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{1, -1, n_heads, head_size}), + false); + res = std::make_shared(split, perm); + } + } else if (op_case == 3 || op_case == 4) { auto src_reshaped = std::make_shared( src, ov::op::v0::Constant::create(ov::element::i64, {4}, {n_seq, ctx_per_seq, n_heads, head_size}), false); @@ -133,7 +152,12 @@ OutputVector translate_permute(const NodeContext & context) { std::make_shared(src_reshaped, seq_active_start, seq_active_end, one, zero); } auto slice2 = std::make_shared(after_seq_slice, zero, attention_size, one, one); - res = std::make_shared(slice2, perm); + // restate the head count and head size, see above + auto restated = std::make_shared( + slice2, + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{0, -1, n_heads, head_size}), + true); + res = std::make_shared(restated, perm); } else { auto three = ov::op::v0::Constant::create(ov::element::i64, {1}, {3}); auto src_reshaped = std::make_shared( diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp index 3b606c82accb..9773198f6968 100644 --- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp @@ -68,11 +68,18 @@ OutputVector translate_set_rows(const NodeContext & context) { auto row_size = context.get_input_shape(2)[3].get_length(); auto ind_squeezed = std::make_shared( indices, ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2})); - auto data_reshaped = std::make_shared( - data, - ov::op::v0::Constant::create(ov::element::i64, {4}, - {(int64_t) 1, (int64_t) 1, (int64_t) -1, (int64_t) row_size}), - false); + // skip the reshape when the rows already have that shape: it costs a GPU primitive per cache write + const auto & data_shape = data.get_partial_shape(); + const bool data_is_rows = data_shape.rank().is_static() && data_shape.rank().get_length() == 4 && + data_shape[0] == 1 && data_shape[1] == 1 && data_shape[3] == row_size; + ov::Output data_reshaped = data; + if (!data_is_rows) { + data_reshaped = std::make_shared( + data, + ov::op::v0::Constant::create(ov::element::i64, {4}, + {(int64_t) 1, (int64_t) 1, (int64_t) -1, (int64_t) row_size}), + false); + } res = std::make_shared(dst, ind_squeezed, data_reshaped, axes); } diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index ec3596de200d..f3183e27ee44 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -5,10 +5,10 @@ #include "ggml-openvino/openvino/node_context.h" #include "ggml-openvino/openvino/utils.h" #include "input_model.h" -#include "pass/fuse_argsort_topk.h" -#include "pass/fuse_moe_router.h" #include "pass/align_eltwise_ranks.h" +#include "pass/fuse_argsort_topk.h" #include "pass/fuse_moe_compressed.h" +#include "pass/fuse_moe_router.h" #include "pass/fuse_to_conv.h" #include "pass/kv_state_seq_axis.h" #include "pass/mark_decompression_convert_constant_folding.h" @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -44,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -53,7 +55,6 @@ #include #include #include -#include #include namespace ov { @@ -291,6 +292,15 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo } for (const auto & it : ggml_model_decoder->get_model_extra_inputs()) { + auto source = tensor_map->find(it.second.shape_source); + if (!it.second.shape_source.empty() && source != tensor_map->end()) { + auto dim = std::make_shared(std::make_shared(source->second, it.second.type), + v0::Constant::create(element::i64, {1}, {it.second.shape_axis}), + v0::Constant::create(element::i64, {}, {0})); + dim->set_friendly_name(it.first); + (*tensor_map)[it.first] = dim; + continue; + } auto input_node = create_extra_input(it.first, it.second); if (it.second.is_parameter) { params.push_back(ov::as_type_ptr(input_node)); diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index 40ba938a62ce..56d213f4f3b6 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -1,5 +1,7 @@ #include "utils.h" +#include "ggml-openvino/ggml-openvino-extra.h" + #include #include #include @@ -431,7 +433,10 @@ ov::Output process_view_input_new(const NodeContext & context, int inp // This ensures NPUW's FOLD doesn't parametrize per-layer slice indices (which // would introduce dynamic shapes). A shared Split node sits outside the repeated // subgraph boundary; each layer receives one of its output ports. - if (context.is_static() && view_input_size == 1) { + // The dynamic GPU path uses it too: a StridedSlice costs a full shape inference per run on GPU, a Split output does + // not (gemma-4 slices its per-layer embeddings this way, once per layer) + const bool dynamic_split = !context.is_static() && !context.is_stateful() && ggml_openvino_is_gpu(); + if ((context.is_static() || dynamic_split) && view_input_size == 1) { auto view_stride_v = context.get_view_input_stride(input_index, 0); auto view_src_stride_v = context.get_view_input_src_stride(input_index, 0); auto view_ggml_shape = context.get_view_input_ggml_shape(input_index, 0); @@ -471,6 +476,26 @@ ov::Output process_view_input_new(const NodeContext & context, int inp size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0; int64_t split_index = static_cast(relative_offset / view_src_stride_v[split_dim]); + if (split_index >= 0 && split_index < num_splits && dynamic_split) { + // 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 = + "split_dim_weak_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index()); + auto & rt_info = src_node->get_rt_info(); + std::shared_ptr split_node; + if (rt_info.count(rt_key) != 0) { + 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)}); + split_node = + std::make_shared(input, axis_const, static_cast(num_splits)); + split_node->set_friendly_name(src_node->get_friendly_name() + "_split"); + rt_info[rt_key] = std::weak_ptr(split_node); + } + return split_node->output(static_cast(split_index)); + } if (split_index >= 0 && split_index < num_splits) { auto src_node = input.get_node_shared_ptr(); std::string rt_key = "split_dim_" + std::to_string(split_dim); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index f07e180a40f7..6db96abfa19e 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -120,6 +120,7 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_SLICE") ? 1u : 0u); extra_cfg = extra_cfg * 131 + (manual_gqa_enabled ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1u : 0u); + extra_cfg = extra_cfg * 131 + (ggml_openvino_shape_from_mask_enabled() ? 1u : 0u); return extra_cfg; } @@ -205,6 +206,8 @@ static std::string compiled_graph_key(const ggml_cgraph * graph, if (!input.second.is_parameter) { append(input.second.value); } + append_string(input.second.shape_source); + append(input.second.shape_axis); } // Without an allocation generation, pointer reuse could select stale weights. // Such graphs still get private requests; they simply do not share compilation. @@ -256,6 +259,8 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph, if (!input.is_parameter) { append(input.value); } + append_string(input.shape_source); + append(input.shape_axis); } return key; } From 0aa29c76dafaed57528fd02b6f719125111390a8 Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Tue, 6 Oct 2026 14:23:12 -0700 Subject: [PATCH 16/65] ggml-openvino: only reuse Split outputs for exact chunk-aligned views The dynamic GPU path reused a Split output for any single-element view by deriving the chunk index from offset / stride. This produced incorrect results for views that were not chunk-aligned or whose remaining dimensions did not preserve the source strides, as seen in test-backend-ops CONT with use_view_slice. Restrict Split reuse to cases where the view exactly matches a split chunk, meaning the offset is aligned to the split stride and the remaining non-unit dimensions preserve the original source strides. Gemma-4 per-layer embedding slices continue to use the shared Split path. --- ggml/src/ggml-openvino/openvino/utils.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index 56d213f4f3b6..a0c0709282e0 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -476,7 +476,14 @@ ov::Output process_view_input_new(const NodeContext & context, int inp size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0; int64_t split_index = static_cast(relative_offset / view_src_stride_v[split_dim]); - if (split_index >= 0 && split_index < num_splits && dynamic_split) { + // the view must be exactly one Split output: offset on a chunk boundary, the strides of all + // other dims with more than one element equal + bool exact_chunk = relative_offset % view_src_stride_v[split_dim] == 0; + for (size_t i = 0; i < ndims && exact_chunk; ++i) { + exact_chunk = i == static_cast(split_dim) || view_ggml_shape[i] == 1 || + view_stride_v[i] == view_src_stride_v[i]; + } + if (split_index >= 0 && split_index < num_splits && dynamic_split && exact_chunk) { // 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 = @@ -496,7 +503,7 @@ ov::Output process_view_input_new(const NodeContext & context, int inp } return split_node->output(static_cast(split_index)); } - if (split_index >= 0 && split_index < num_splits) { + if (split_index >= 0 && split_index < num_splits && !dynamic_split) { auto src_node = input.get_node_shared_ptr(); std::string rt_key = "split_dim_" + std::to_string(split_dim); auto & rt_info = src_node->get_rt_info(); From e127d6b10fcef1a0f432f95b9fa18cb94182efce Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Tue, 6 Oct 2026 14:48:30 -0700 Subject: [PATCH 17/65] ggml-openvino: mark SWA fallback as a model-level heuristic Add a TODO above the equal-extent fallback to document that the larger mask group is currently assumed to be the SWA group. Since stateless graphs only require the two groups to remain distinct, this heuristic may only be necessary for stateful execution and could potentially be restricted to that path. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index ed50ecfef08b..b0f9cb2ed940 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -855,6 +855,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr // The only use of the window itself, the stateful mask rebuild, reads it back from the mask, and on a full // mask that gives back the causal mask. Decide from the first graph, before the window shows in the mask, so // the graph does not change, and is not recompiled, when it does. + // TODO: "larger group is swa" is a model-level guess. Revisit when llama.cpp tells the backend which layers + // use a sliding window. Stateless graphs only need the two groups kept apart (separate mask, KV write index + // and attention size inputs), not the swa role itself, so the guess could be limited to stateful execution. if (model_params.swa_layers.empty()) { std::map> mask_layers; for (const auto & [layer, mask] : layer_mask) { From e706353a2120e3ca9d530a4315a6bf839c94a9c3 Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Fri, 9 Oct 2026 08:00:59 -0700 Subject: [PATCH 18/65] ggml-openvino: initialize ModelExtraInputInfo shape fields Initialize the newly added `shape_source` and `shape_axis` fields in the `ModelExtraInputInfo` brace initializer used by `add_extra_inputs()`. Without initializers for these fields, GCC emits `-Wmissing-field-initializers`, causing CI to fail with `LLAMA_FATAL_WARNINGS`. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 27a3e49e188b..afb7dfca68ec 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1232,7 +1232,7 @@ void GgmlOvDecoder::add_extra_inputs() { // 2. `n_seq_active` and `seq_active_start`, used in FLASH_ATTN_EXT to indicate the active sequences in the batch auto create_1d_input = [this](const std::string & name, int64_t value, bool force_parameter = false) { - m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static}; + m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static, {}, -1}; }; if (m_compute_params.attention_size != -1) { From dfb6ad9fc2a22b1bf752311a013fe5206aee4d9d Mon Sep 17 00:00:00 2001 From: "Sabnis, Omkar" Date: Fri, 9 Oct 2026 12:24:59 -0700 Subject: [PATCH 19/65] ggml-openvino: remove GGML_OPENVINO_REQUANT_EMBD The option identifies embedding and output weights by their tensor names, which are defined by core llama.cpp. Remove it from this PR; preserving the file quantization of these weights will be addressed in a separate change that identifies them by their roles in the graph. --- docs/backend/OPENVINO.md | 1 - ggml/src/ggml-openvino/README.md | 2 +- ggml/src/ggml-openvino/ggml-openvino-extra.cpp | 8 -------- ggml/src/ggml-openvino/model-cache.cpp | 1 - 4 files changed, 1 insertion(+), 11 deletions(-) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index eb629167fd62..0d5804cafc2c 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -730,7 +730,6 @@ Boolean flags follow a uniform convention: set to a **positive integer** (e.g. ` | `GGML_OPENVINO_RELEASE_WEIGHTS` | Boolean | inherits from `GGML_OPENVINO_MEMORY_OPTIMIZE` on GPU | GPU-only. Release host weight buffers after the compiled model cache can reuse the device/plugin copy. Requires stable graph shapes; dynamic workloads that need recompilation should leave this disabled. | | `GGML_OPENVINO_SPILL_DIR` | String | `not set` | Directory for a disk-backed weight buffer. When set, the repacked weight buffer is mapped from an unlinked file on this path instead of anonymous memory, so its pages are reclaimable under memory pressure instead of staying pinned, cutting the load-time host memory peak. Must point at real storage; a tmpfs mount (e.g. `/tmp` on many systems) backs it with RAM and makes the peak worse. | | `GGML_OPENVINO_REQUANT_KQUANT` | String | `not set` | Requantize Q6_K/Q5_K weights (and matching MoE expert weights) to a 4-bit target instead of the default Q8_0_C, trading accuracy for less memory traffic. One of `q4_asym64` (Q6_K/Q5_K only, keeps a real zero point at group 64), `q4_asym64_all` (also requantizes Q4_K), `q4_sym128` (Q6_K/Q5_K only), `q4_sym128_all` (Q4_K too, drops its per-group zero point), or `native` (no requantization). | -| `GGML_OPENVINO_REQUANT_EMBD` | String | `not set` | `native` keeps `token_embd` and `output` in their file quantization instead of requantizing them to Q8_0_C (CPU/GPU; for tied embeddings this is also the LM head). Less memory traffic per token at a small accuracy cost. | | `GGML_OPENVINO_PROFILING` | Integer | `0` | `1` logs execution timing; `2` or higher also enables OpenVINO and OpenCL profiling. | | `GGML_OPENVINO_DEBUG_NODE` | String | `not set` | Add the named graph nodes as compiled outputs for debugging. Separate multiple names with commas. | | `GGML_OPENVINO_MOE_OP` | Boolean | `1` | On GPU, set to `0` to keep the unfused GatherMatmul path. | diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index a3c6af9ba8de..a12233d2aa17 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -29,7 +29,7 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally. -Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_REQUANT_EMBD`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. +Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode. diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 4c00a44ebb14..785ae6f6420c 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -141,7 +141,6 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_NATIVE_SOFTPLUS", "GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", "GGML_OPENVINO_REQUANT_KQUANT", - "GGML_OPENVINO_REQUANT_EMBD", "GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT", "GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK", // Build the precise (but O(n_nodes)) graph cache key. Needed by op tests. @@ -362,13 +361,6 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * if (no_requant) { return std::nullopt; } - // GGML_OPENVINO_REQUANT_EMBD=native keeps token_embd/output in the file's quantization (tied models: also the lm_head) - const bool is_embd_or_output = - strncmp(tensor->name, "token_embd.weight", 17) == 0 || strncmp(tensor->name, "output.weight", 13) == 0; - const char * rq_embd = ggml_openvino_getenv_str("GGML_OPENVINO_REQUANT_EMBD"); - if (is_embd_or_output && rq_embd && strcmp(rq_embd, "native") == 0 && !ggml_openvino_is_npu()) { - return std::nullopt; - } if (strncmp(tensor->name, "token_embd.weight", 17) == 0) { return ((ggml_openvino_is_npu() && tensor->type == GGML_TYPE_Q6_K) ? ExtraQuantType::F16 : ExtraQuantType::Q8_0_C); diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 91af222c6f54..278f62a25a52 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -166,7 +166,6 @@ bool ggml_openvino_model_cache_only() { static const char * cache_settings[] = { "GGML_OPENVINO_REQUANT_KQUANT", - "GGML_OPENVINO_REQUANT_EMBD", "GGML_OPENVINO_NATIVE_SOFTPLUS", "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_MANUAL_GQA_ATTN", From 90a6103ca13138251a545469d114c0be67d24128 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 14 Oct 2026 10:36:28 +0200 Subject: [PATCH 20/65] openvino : support Qwen MTP decoding Assisted-by: Codex --- ggml/src/ggml-openvino/README.md | 6 + ggml/src/ggml-openvino/ggml-decoder.cpp | 156 ++++++++++++++++-- ggml/src/ggml-openvino/ggml-decoder.h | 73 +++++++- ggml/src/ggml-openvino/ggml-openvino.cpp | 16 +- .../src/ggml-openvino/openvino/op/argsort.cpp | 52 ++++++ ggml/src/ggml-openvino/openvino/op/cpy.cpp | 50 +++++- .../openvino/op/gated_delta_net.cpp | 31 +++- .../openvino/op/gated_delta_net.hpp | 21 ++- .../src/ggml-openvino/openvino/op/reshape.cpp | 10 ++ .../ggml-openvino/openvino/op/rms_norm.cpp | 48 ++++-- ggml/src/ggml-openvino/openvino/op/view.cpp | 9 + 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 | 68 ++++++++ ggml/src/ggml-openvino/utils.cpp | 23 ++- tests/test-backend-ops.cpp | 57 ++++++- tests/test-backend-sampler.cpp | 148 ++++++++++++++++- 17 files changed, 705 insertions(+), 65 deletions(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index a12233d2aa17..4a562594cfa3 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -1,3 +1,9 @@ +# Qwen MTP + +Dynamic GPU execution supports Qwen MTP sampling and recurrent state snapshots. Build against the OpenVINO runtime and GPU plugin that provide ordinary `GatedDeltaNet` with `snapshot_count` and a third snapshot output. The backend and runtime must be rebuilt together. + +Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. CPU snapshot execution, NPU execution, and forced static MTP are not supported. + # Compiled model cache `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled CPU/GPU graphs with their weights. It bypasses the plugin-level `GGML_OPENVINO_CACHE_DIR` and uses `OPTIMIZE_SPEED`, so weightless caching is disabled. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index e1bdd9abe0a2..2ab114f2b8f1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -82,9 +82,15 @@ void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) { m_model_inputs.clear(); m_model_outputs.clear(); m_node_info_list.clear(); + m_node_dynamic_dims.clear(); set_input_output(); + compute_node_dynamic_dims(); compute_model_inputs(); compute_model_outputs(); + for (int i = 0; i < cgraph->n_nodes; ++i) { + m_node_info_list[i].node_op_case = compute_op_case(m_node_info_list[i].node); + m_node_info_list[i].node_op_type = compute_op_type(m_node_info_list[i].node); + } } // llama keeps separate graphs for batches with and without outputs, so a cache hit can come from a @@ -99,6 +105,14 @@ 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])) { + std::tie(m_model_params, m_compute_params) = compute_llm_params(cgraph, false); + add_extra_inputs(); + break; + } + } set_input_output(); compute_model_inputs(); compute_model_outputs(); @@ -302,12 +316,34 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } auto name = std::string(node->name); auto * src = node->src[0]; + if (src->op == GGML_OP_MUL && node->ne[0] == src->ne[0] * src->ne[1] && node->ne[3] == 1) { + for (int j = 0; j < 2; ++j) { + const auto * norm = src->src[j]; + if (norm->op == GGML_OP_MUL) { + norm = norm->src[0]; + } + if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW && + norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { + return 6; + } + } + } // Identify recurrent sequence reshapes before size checks, which are ambiguous for one token. bool recurrent_sequence = false; for (int i = 0; i < m_cgraph->n_nodes && !recurrent_sequence; ++i) { const auto * consumer = m_cgraph->nodes[i]; if (consumer->op == GGML_OP_MUL_MAT_ID && consumer->src[1] == node) { return 1; + } else if (consumer->op == GGML_OP_GATED_DELTA_NET) { + for (int j : {3, 4}) { + const auto * gate = consumer->src[j]; + if (gate->op == GGML_OP_UNARY) { + gate = gate->src[0]; + } + if (gate == node) { + return 10; + } + } } else if (consumer->op == GGML_OP_SSM_CONV) { const auto * concat = consumer->src[0]; if (concat->op == GGML_OP_CONCAT) { @@ -317,6 +353,21 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } else if (consumer->op == GGML_OP_UNARY && ggml_get_unary_op(consumer) == GGML_UNARY_OP_SOFTPLUS) { const auto * biased = consumer->src[0]; recurrent_sequence = biased->op == GGML_OP_ADD && biased->src[0] == node; + } else if (consumer->op == GGML_OP_MUL) { + for (int j = 0; j < 2; ++j) { + const auto * gate = consumer->src[j]; + const auto * norm = consumer->src[1 - j]; + if (gate->op != GGML_OP_UNARY || gate->src[0] != node) { + continue; + } + if (norm->op == GGML_OP_MUL) { + norm = norm->src[0]; + } + if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW && + norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { + return 10; + } + } } } if (recurrent_sequence && node->ne[0] == src->ne[0] && node->ne[3] == 1) { @@ -465,8 +516,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { break; } case GGML_OP_VIEW: { - if (!m_model_params.has_rs_rollback && node->src[0] != nullptr && - node->src[0]->op == GGML_OP_GATED_DELTA_NET) { + if (is_sampling_view(node)) { + return 3; + } + if (is_direct_gdn_view(node)) { // The GDN translator publishes native attention/state outputs under these VIEW names. op_case = 2; break; @@ -528,8 +581,7 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { if (node->src[0]->op == GGML_OP_VIEW) { if (is_same_shape(node->src[0]->src[0], node->src[0])) { op_case = 1; - } else if (!m_model_params.has_rs_rollback && - node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { + } else if (is_direct_gdn_view(node->src[0])) { // GDN attention is routed directly to this VIEW by get_output_names(). op_case = 3; } else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { @@ -580,7 +632,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { case GGML_OP_CPY: { if (node->src[0]->op == GGML_OP_VIEW) { if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { - if (!m_model_params.has_rs_rollback) { + if (is_gdn_snapshot_writeback(node)) { + op_case = is_direct_gdn_view(node->src[0]) ? 12 : 11; + } else if (!m_model_params.has_rs_rollback) { // op_case 7 replaces a single-slot cache; op_case 10 writes native GDN state // into an active range of a larger non-rollback cache. op_case = is_full_single_slot_writeback(node) ? 7 : 10; @@ -1030,6 +1084,22 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr } if (node->op == GGML_OP_GATED_DELTA_NET) { model_params.state_size = node->src[0]->ne[0]; + model_params.has_rs_rollback |= node->op_params[0] > 1; + compute_params.gdn_attention_rows[get_tensor_ov_name(cgraph, node)] = node->src[2]->ne[2] * node->src[2]->ne[3]; + } + if (is_sampling_view(node)) { + compute_params.sampling_rows[get_tensor_ov_name(cgraph, node)] = node->view_offs / node->src[0]->nb[1]; + } + if (is_gdn_snapshot_writeback(node)) { + const auto * source = node->src[0]; + const auto * destination = node->src[1]; + const auto * packed = source->src[0]; + ComputeParams::RsWriteback writeback; + writeback.slot_begin = destination->view_offs / destination->nb[1]; + writeback.src_begin = source->view_offs / packed->nb[1]; + writeback.seq_count = destination->ne[1]; + writeback.snapshot_stride = destination->nb[2] / destination->nb[1]; + compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; } if (node->op == GGML_OP_SCALE && node->view_src != nullptr && is_recurrent_cache(node->view_src)) { if (model_params.n_rs_slots == -1) { @@ -1062,7 +1132,8 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr // signature is local to the CPY and still works when fallback splits the graph. model_params.has_rs_rollback = true; } - if (row_bytes > 0 && (is_conv || is_gdn || is_extra) && !is_full_single_slot_writeback(node)) { + if (row_bytes > 0 && (is_conv || is_gdn || is_extra) && !is_full_single_slot_writeback(node) && + !(is_gdn && node->src[0]->src[0]->op_params[0] > 1)) { ComputeParams::RsWriteback writeback; writeback.slot_begin = (int) (dest_view->view_offs / row_bytes); if (is_conv) { @@ -1103,7 +1174,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr auto * output_tensor = cgraph->nodes[cgraph->n_nodes - 1]; compute_params.output_len = output_tensor->ne[1]; - if (model_params.is_cacheless_attn) { + { for (int i = 0; i < cgraph->n_nodes; i++) { const auto * node = cgraph->nodes[i]; if (node->op == GGML_OP_GET_ROWS && is_output_idx(node->src[1], node)) { @@ -1147,6 +1218,9 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, // output index input_shape = ov::PartialShape{1, 1, 1, m_is_static ? m_compute_params.output_len : -1}; + } else if (!m_is_static && is_activation_input(input, op)) { + input_shape = ov::PartialShape{1, 1, -1, input->ne[0]}; + } else if (is_inp_mean(input, op)) { input_shape = m_is_static ? ov::PartialShape{1, 1, input->ne[1], m_prefill_chunk_size} : ov::PartialShape{1, 1, -1, -1}; @@ -1335,6 +1409,16 @@ void GgmlOvDecoder::add_extra_inputs() { if (!m_is_static && writeback.src_begin >= 0) { create_1d_input("rs_src_begin_" + node_name, writeback.src_begin); } + if (writeback.seq_count >= 0) { + create_1d_input("rs_seq_count_" + node_name, writeback.seq_count); + create_1d_input("rs_snapshot_stride_" + node_name, writeback.snapshot_stride); + } + } + for (const auto & [node_name, row] : m_compute_params.sampling_rows) { + create_1d_input("sampling_row_" + node_name, row); + } + for (const auto & [node_name, rows] : m_compute_params.gdn_attention_rows) { + create_1d_input("gdn_attention_rows_" + node_name, rows); } } @@ -1432,6 +1516,17 @@ void GgmlOvDecoder::compute_model_outputs() { if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0) { continue; } + if (cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) { + const auto name = get_tensor_ov_name(m_cgraph, cur_node); + m_model_outputs[name] = cur_node; + m_model_output_names.insert(name); + } + if (is_gdn_snapshot_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); + } auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; 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. @@ -2037,9 +2132,22 @@ std::vector GgmlOvDecoder::get_output_stride(int node_idx) const { return get_stride(ggml_tensor); } +bool GgmlOvDecoder::is_direct_gdn_view(const ggml_tensor * node) const { + if (node == nullptr || node->op != GGML_OP_VIEW || node->src[0] == nullptr || + node->src[0]->op != GGML_OP_GATED_DELTA_NET) { + return false; + } + for (int i = 0; i < m_cgraph->n_nodes; ++i) { + if (m_cgraph->nodes[i] == node->src[0]) { + return get_output_names(i).size() > 1; + } + } + return false; +} + std::vector GgmlOvDecoder::get_output_names(int node_idx) const { auto * node = m_node_info_list[node_idx].node; - if (node->op == GGML_OP_GATED_DELTA_NET && !m_model_params.has_rs_rollback) { + 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; for (int i = node_idx + 1; i < m_cgraph->n_nodes; i++) { @@ -2056,6 +2164,9 @@ std::vector GgmlOvDecoder::get_output_names(int node_idx) const { name = get_tensor_ov_name(m_cgraph, consumer); } if (!attn_name.empty() && !state_name.empty()) { + if (m_model_params.has_rs_rollback) { + return {m_node_info_list[node_idx].node_name, attn_name, state_name}; + } return {attn_name, state_name}; } } @@ -2180,6 +2291,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[src] = 1; continue; } + if (!m_is_static && is_activation_input(src, node)) { + m_node_dynamic_dims[src] = 1; + continue; + } if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted) { m_node_dynamic_dims[src] = 1; continue; @@ -2239,6 +2354,15 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { } break; case GGML_OP_VIEW: { + if (is_sampling_view(node)) { + m_node_dynamic_dims[node] = -1; + break; + } + + if (node->src[0]->op == GGML_OP_GATED_DELTA_NET && node->view_offs == 0) { + m_node_dynamic_dims[node] = 2; + 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. @@ -2286,7 +2410,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]]; auto dynamic_dim_stride = node->src[0]->nb[dynamic_dim_idx]; for (int i = 0; i < GGML_MAX_DIMS; i++) { - if (node->nb[i] == dynamic_dim_stride && node->ne[i] == node->src[0]->ne[dynamic_dim_idx]) { + if (node->nb[i] == dynamic_dim_stride) { m_node_dynamic_dims[node] = i; break; } @@ -2359,14 +2483,17 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { } } break; - case GGML_OP_CONCAT: - for (int i = 0; i < GGML_MAX_DIMS; i++) { - if (node->src[0]->ne[i] != node->ne[i]) { - m_node_dynamic_dims[node] = i; - break; + case GGML_OP_CONCAT: { + const int axis = node->op_params[0]; + m_node_dynamic_dims[node] = axis; + for (int i = 0; i < 2; ++i) { + const int dynamic_axis = m_node_dynamic_dims[node->src[i]]; + if (dynamic_axis != -1 && dynamic_axis != axis) { + m_node_dynamic_dims[node] = dynamic_axis; } } break; + } case GGML_OP_SSM_CONV: case GGML_OP_GATED_DELTA_NET: m_node_dynamic_dims[node] = 1; @@ -2381,6 +2508,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_SCALE: case GGML_OP_SOFT_MAX: case GGML_OP_ARGSORT: + case GGML_OP_TOP_K: case GGML_OP_ADD_ID: case GGML_OP_UNARY: case GGML_OP_CUMSUM: diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index ee9788b19090..4e029d4aa3f7 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -111,11 +111,15 @@ struct ComputeParams { // [ 18432, 0, 1, 1] 1: VIEW cache_r_l0 (view) struct RsWriteback { - int slot_begin = 0; // first cache slot written by the CPY - int src_begin = -1; // first source column copied by a conv-state CPY + int64_t slot_begin = 0; // first cache slot written by the CPY + int64_t src_begin = -1; // first source column copied by a conv-state CPY + int64_t seq_count = -1; + int64_t snapshot_stride = -1; }; std::map rs_writebacks; + std::map sampling_rows; + std::map gdn_attention_rows; // Destination slot offset of each state cache writeback CPY node, keyed by node name. It // changes with the batch (kv head, active sequence count) and, with rollback enabled // (cparams.n_rs_seq > 0), the conv state is written back once per snapshot slot. Passed to the @@ -386,6 +390,15 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { return tensor->op == GGML_OP_GET_ROWS && op->op == GGML_OP_RMS_NORM; } + 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)) { + return false; + } + return (op->op == GGML_OP_RMS_NORM || op->op == GGML_OP_L2_NORM) && op->src[0] == tensor && + (tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY); + } + static bool is_inp_mask(const ggml_tensor * tensor, const ggml_tensor * op) { return op->op == GGML_OP_CPY || (op->op == GGML_OP_FLASH_ATTN_EXT && tensor == op->src[3]) || (op->op == GGML_OP_SOFT_MAX && tensor == op->src[1]); @@ -412,6 +425,62 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0); } + static bool is_gdn_snapshot_writeback(const ggml_tensor * node) { + if (!(node != nullptr && node->op == GGML_OP_CPY && 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_GATED_DELTA_NET && node->src[0]->src[0]->op_params[0] > 1 && + node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->view_src != nullptr && + node->src[1]->view_src == node->view_src && node->src[0]->ne[0] == node->src[1]->ne[0] && + node->src[1]->nb[1] > 0 && node->src[1]->nb[1] == ggml_row_size(node->type, node->ne[0]) && + node->src[1]->nb[2] % node->src[1]->nb[1] == 0 && + node->src[1]->view_offs % node->src[1]->nb[1] == 0)) { + return false; + } + const auto * source = node->src[0]; + const auto * destination = node->src[1]; + const auto * packed = source->src[0]; + if (node->type != GGML_TYPE_F32 || source->type != node->type || destination->type != node->type || + node->view_src->type != node->type || !ggml_is_contiguous(node->view_src) || + packed->nb[1] == 0 || source->view_offs % packed->nb[1] != 0 || + source->nb[0] != sizeof(float) || destination->nb[0] != sizeof(float) || + source->ne[3] != 1 || destination->ne[3] != 1) { + return false; + } + for (int i = 0; i < GGML_MAX_DIMS; ++i) { + if (source->ne[i] <= 0 || source->ne[i] != destination->ne[i]) { + return false; + } + } + const size_t plane_stride = destination->nb[2] / destination->nb[1]; + if (plane_stride == 0 || size_t(destination->ne[1]) > plane_stride - + (destination->view_offs / destination->nb[1]) % plane_stride) { + return false; + } + for (const auto * view : {source, destination}) { + size_t remaining = ggml_nbytes(view == source ? packed : node->view_src); + if (view->view_offs > remaining || remaining - view->view_offs < sizeof(float)) { + return false; + } + remaining -= view->view_offs + sizeof(float); + for (int i = 0; i < GGML_MAX_DIMS; ++i) { + const size_t count = view->ne[i] - 1; + if (view->nb[i] != 0 && count > remaining / view->nb[i]) { + return false; + } + remaining -= count * view->nb[i]; + } + } + return true; + } + + static bool is_sampling_view(const ggml_tensor * node) { + return node != nullptr && node->op == GGML_OP_VIEW && node->src[0] != nullptr && + node->src[0]->op == GGML_OP_PAD && node->ne[0] == node->src[0]->ne[0] && + node->ne[1] == 1 && node->ne[2] == 1 && node->ne[3] == 1; + } + + bool is_direct_gdn_view(const ggml_tensor * node) const; + inline static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { return is_recurrent_cache(tensor) || is_kvcache(tensor, op); } diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 22b2f45e24a6..1efa1b30aac2 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1297,7 +1297,8 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) { return false; } - return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op); + return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op) || + GgmlOvDecoder::is_gdn_snapshot_writeback(op); } static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) { @@ -1365,6 +1366,12 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } switch (op->op) { + case GGML_OP_TOP_K: { + if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_I32 || ggml_openvino_is_npu()) { + return {false, "TOP_K requires F32 input and I32 output on CPU or GPU"}; + } + break; + } case GGML_OP_CONCAT: { if (op->type == GGML_TYPE_I64) { return {false, "CONCAT with I64 type is not supported"}; @@ -1655,9 +1662,8 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { if (op->src[3]->ne[0] != 1) { return {false, "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported"}; } - // K > 1 (multiple state snapshots) not supported by fused op - if (((const int32_t *) op->op_params)[0] > 1) { - return {false, "GATED_DELTA_NET with K > 1 (multiple state snapshots) is not supported"}; + if (op->op_params[0] > 1 && (!ggml_openvino_is_gpu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"))) { + return {false, "GATED_DELTA_NET snapshots require dynamic GPU execution"}; } break; } @@ -1872,7 +1878,7 @@ 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)) { + if (!has_strides_on_element_grid(src) && !(i == 1 && GgmlOvDecoder::is_gdn_snapshot_writeback(op))) { return {false, "src[" + std::to_string(i) + "] strides are not multiples of each other"}; } const bool is_supported_3d_moe_expert = diff --git a/ggml/src/ggml-openvino/openvino/op/argsort.cpp b/ggml/src/ggml-openvino/openvino/op/argsort.cpp index dd0872516758..e6460b02eea7 100644 --- a/ggml/src/ggml-openvino/openvino/op/argsort.cpp +++ b/ggml/src/ggml-openvino/openvino/op/argsort.cpp @@ -2,9 +2,16 @@ #include "../op_table.h" #include "../utils.h" #include "ggml.h" +#include "ggml-openvino/ggml-openvino-extra.h" +#include +#include #include +#include +#include #include +#include +#include #include #include @@ -45,6 +52,51 @@ OutputVector translate_argsort(const NodeContext & context) { return rename_outputs_with_suffix({topk->output(1)}, context.get_name()); } +OutputVector translate_top_k(const NodeContext & context) { + num_inputs_check(context, 1, 1); + auto input = process_view_input_new(context, 0); + const int64_t k = context.get_output_shape()[3].get_length(); + const auto shape = input.get_partial_shape(); + if (ggml_openvino_is_gpu() && shape.rank() == 4 && shape[3].is_static() && + shape[3].get_length() > 65535 && shape[3].get_length() <= INT32_MAX && k <= 64) { + const int64_t width = shape[3].get_length(); + int64_t chunk_size = 4096; + while (chunk_size >= 1024 && width % chunk_size != 0) { + --chunk_size; + } + if (chunk_size >= 1024) { + const int64_t chunks = width / chunk_size; + auto chunked = std::make_shared(input, + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{-1, 1, chunks, chunk_size}), false); + // Each global top-k candidate is in its chunk's top-k set. + auto local = std::make_shared(chunked, + ov::op::v0::Constant::create(ov::element::i32, {}, {k}), -1, + ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::NONE, ov::element::i32, false); + std::vector offsets(chunks); + for (int64_t i = 0; i < chunks; ++i) { + offsets[i] = i * chunk_size; + } + auto indices = std::make_shared(local->output(1), + ov::op::v0::Constant::create(ov::element::i32, {1, 1, size_t(chunks), 1}, offsets)); + auto candidate_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1, chunks * k}); + auto values = std::make_shared(local->output(0), candidate_shape, false); + auto candidate_indices = std::make_shared(indices, candidate_shape, false); + auto selected = std::make_shared(values, + ov::op::v0::Constant::create(ov::element::i32, {}, {k}), -1, + ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::NONE, ov::element::i32, false); + auto result = std::make_shared(candidate_indices, selected->output(1), 3); + auto output_shape = std::make_shared(OutputVector{ + get_dimensions(input.get_node_shared_ptr(), {0, 1, 2}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {k})}, 0); + return rename_outputs_with_suffix({std::make_shared(result, output_shape, false)}, context.get_name()); + } + } + auto topk = std::make_shared( + input, ov::op::v0::Constant::create(ov::element::i32, {}, {k}), -1, + ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::NONE, ov::element::i32, false); + return rename_outputs_with_suffix({topk->output(1)}, context.get_name()); +} + } // namespace op } // namespace ggml } // namespace frontend diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp index 2c7299a894a1..904d4911c28d 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -12,8 +12,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -34,6 +36,45 @@ OutputVector translate_cpy(const NodeContext & context) { auto input_shape = context.get_input_shape(0); auto output_shape = context.get_input_shape(1); + if (op_case == 11 || op_case == 12) { + auto base = context.get_input(1); + auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {2}); + 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 feature = ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{1, 1, -1, output_shape[3].get_length()}); + ov::Output state_part = context.get_input(0); + if (op_case == 11) { + auto source_rows = std::make_shared( + std::make_shared(context.get_input(0), ov::element::i64), axis, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto source_indices = std::make_shared( + std::make_shared(context.get_input("rs_src_begin_" + context.get_name())), + std::make_shared(source_rows), + std::make_shared(one), ov::element::i64); + state_part = std::make_shared(context.get_input(0), source_indices, + ov::op::v0::Constant::create(ov::element::i64, {}, {2})); + } + auto states = std::make_shared(state_part, feature, false); + auto rows = std::make_shared( + std::make_shared(states, ov::element::i64), axis, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto indices = std::make_shared( + std::make_shared(zero), std::make_shared(rows), + std::make_shared(one), ov::element::i64); + auto seq_count = context.get_input("rs_seq_count_" + context.get_name()); + auto plane = std::make_shared(indices, seq_count); + auto sequence = std::make_shared(indices, seq_count); + auto slots = std::make_shared( + std::make_shared(plane, context.get_input("rs_snapshot_stride_" + context.get_name())), + std::make_shared(sequence, context.get_input("rs_slot_begin_" + context.get_name()))); + auto updated = std::make_shared( + std::make_shared(base, feature, false), slots, states, axis); + auto result = std::make_shared( + updated, std::make_shared(base, ov::element::i64), false); + return rename_outputs_with_suffix({result}, context.get_name()); + } + if (op_case == 4) { auto src = process_view_input_new(context, 0); auto base = context.get_input(1); @@ -145,9 +186,12 @@ OutputVector translate_cpy(const NodeContext & context) { const std::string src_begin_name = "rs_src_begin_" + context.get_name(); if (context.has_input(src_begin_name)) { auto src_begin = context.get_input(src_begin_name); - auto src_end = std::make_shared( - src_begin, ov::op::v0::Constant::create(ov::element::i64, {1}, {window_size})); - window = std::make_shared(context.get_input(0), src_begin, src_end, one, col_axis); + std::vector offsets(window_size); + std::iota(offsets.begin(), offsets.end(), 0); + auto indices = std::make_shared(src_begin, + ov::op::v0::Constant::create(ov::element::i64, {size_t(window_size)}, offsets)); + window = std::make_shared(context.get_input(0), indices, + ov::op::v0::Constant::create(ov::element::i64, {}, {3})); } else if (context.has_input("chunk_valid_len")) { std::vector offsets(window_size); std::iota(offsets.begin(), offsets.end(), 0); diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index 9cedf68116bf..a3a1957ae4ba 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -21,8 +21,12 @@ #include #include #include +#include #include +#include #include +#include +#include #include #include #include @@ -107,6 +111,7 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { const int64_t H_v = v_shape[2]; const int64_t S_v = v_shape[3]; const int64_t H_k = q_shape[2]; + const int64_t snapshot_count = context.get_output_op_params()[0]; // const int64_t S_k = q_shape[3]; auto q = context.get_input(0); @@ -177,7 +182,7 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { // << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape() // << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl; - auto gdn = std::make_shared(q, k, v, state, g, beta, fuse_qk_l2norm, q_eps, k_eps); + auto gdn = std::make_shared(q, k, v, state, g, beta, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); auto attn_4d = gdn->output(0); auto state_4d = gdn->output(1); // [B, H_v, key_dim, value_dim] @@ -195,12 +200,34 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { auto flat_shape_1d = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}); auto attn = std::make_shared(attn_4d, flat_shape_1d, false); - auto new_state = std::make_shared(state_transposed, flat_shape_1d, false); + Output states = state_transposed; + if (snapshot_count > 1) { + auto snapshots = std::make_shared( + gdn->output(2), ov::op::v0::Constant::create(ov::element::i64, {5}, {0, 1, 2, 4, 3})); + auto token_count = std::make_shared( + std::make_shared(attn_4d, ov::element::i64), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto valid_count = std::make_shared( + token_count, ov::op::v0::Constant::create(ov::element::i64, {1}, {snapshot_count})); + auto indices = std::make_shared( + ov::op::v0::Constant::create(ov::element::i64, {}, {0}), + std::make_shared(valid_count), + ov::op::v0::Constant::create(ov::element::i64, {}, {1}), ov::element::i64); + states = std::make_shared( + snapshots, indices, ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + } + auto new_state = std::make_shared(states, flat_shape_1d, false); auto packed = std::make_shared(ov::OutputVector{attn, new_state}, 0); auto out_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1 /*T * B + S_v * B*/, S_v * H_v}); auto res = std::make_shared(packed, out_shape, false); + if (context.get_output_names().size() == 3) { + auto flat_states = std::make_shared(states, + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1, S_v * S_v * H_v}), false); + return rename_outputs_with_suffix({res, attn_4d, flat_states}, context.get_name()); + } return rename_outputs_with_suffix({res}, context.get_name()); } diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp index 20a4cfdfe743..f547078ebcad 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp @@ -1,3 +1,6 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// #pragma once #include "openvino/op/op.hpp" @@ -9,7 +12,7 @@ namespace ov::op::internal { /// \ingroup ov_ops_cpp_api class OPENVINO_API GatedDeltaNet : public ov::op::Op { public: - OPENVINO_OP("GatedDeltaNet") + OPENVINO_OP("GatedDeltaNet"); GatedDeltaNet() = default; /// \brief Constructs a GatedDeltaNet operation. @@ -23,6 +26,7 @@ class OPENVINO_API GatedDeltaNet : public ov::op::Op { /// \param fuse_qk_l2norm Enables fusing q/k L2-normalization into this op. /// \param q_l2_norm_eps Epsilon used for query L2-normalization when fusion is enabled. /// \param k_l2_norm_eps Epsilon used for key L2-normalization when fusion is enabled. + /// \param snapshot_count Number of newest-first states; adds output [K, B, H_v, D_k, D_v] when K > 1. GatedDeltaNet(const Output& query, const Output& key, const Output& value, @@ -31,7 +35,8 @@ class OPENVINO_API GatedDeltaNet : public ov::op::Op { const Output& beta, const bool fuse_qk_l2norm = false, const float q_l2_norm_eps = 1e-6F, - const float k_l2_norm_eps = 1e-6F); + const float k_l2_norm_eps = 1e-6F, + const int64_t snapshot_count = 1); /// \brief Constructs a GatedDeltaNet operation from input vector. /// @@ -39,10 +44,12 @@ class OPENVINO_API GatedDeltaNet : public ov::op::Op { /// \param fuse_qk_l2norm Enables fusing q/k L2-normalization into this op. /// \param q_l2_norm_eps Epsilon used for query L2-normalization when fusion is enabled. /// \param k_l2_norm_eps Epsilon used for key L2-normalization when fusion is enabled. + /// \param snapshot_count Number of newest-first states; adds output [K, B, H_v, D_k, D_v] when K > 1. GatedDeltaNet(const ov::OutputVector& args, const bool fuse_qk_l2norm = false, const float q_l2_norm_eps = 1e-6F, - const float k_l2_norm_eps = 1e-6F); + const float k_l2_norm_eps = 1e-6F, + const int64_t snapshot_count = 1); 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; @@ -56,10 +63,18 @@ class OPENVINO_API GatedDeltaNet : public ov::op::Op { return m_k_l2_norm_eps; } + int64_t get_snapshot_count() const { + return m_snapshot_count; + } + void set_snapshot_count(int64_t snapshot_count) { + m_snapshot_count = snapshot_count; + } + private: bool m_fuse_qk_l2norm = false; float m_q_l2_norm_eps = 1e-6F; float m_k_l2_norm_eps = 1e-6F; + int64_t m_snapshot_count = 1; }; } // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op/reshape.cpp b/ggml/src/ggml-openvino/openvino/op/reshape.cpp index 5ed27b1a726e..65cf8433683f 100644 --- a/ggml/src/ggml-openvino/openvino/op/reshape.cpp +++ b/ggml/src/ggml-openvino/openvino/op/reshape.cpp @@ -70,6 +70,16 @@ OutputVector translate_reshape(const NodeContext & context) { case 8: shape[0] = -1; break; + case 10: + if (context.has_input("s_copy_active_slot_len")) { + new_shape_node = std::make_shared(ov::OutputVector{ + context.get_input("s_copy_active_slot_len"), + ov::op::v0::Constant::create(ov::element::i64, {3}, + std::vector{-1, shape[2], shape[3]})}, 0); + } else { + shape[1] = -1; + } + break; default: FRONT_END_OP_CONVERSION_CHECK(false, "Unsupported RESHAPE case: ", op_case); } diff --git a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp index 980fa3ceeba9..4933a09bc6e5 100644 --- a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp +++ b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp @@ -5,14 +5,18 @@ #include #include #include +#include #include +#include #include #include #include +#include #include #include #include #include +#include namespace ov { namespace frontend { @@ -26,13 +30,7 @@ OutputVector translate_rms_norm(const NodeContext & context) { ov::Output input_node; if (op_case == 3) { - // Flatten sequence and token dimensions to match the gate layout. - auto input_shape = context.get_input_shape(0).to_shape(); - input_node = std::make_shared( - context.get_input(0), - ov::op::v0::Constant::create( - ov::element::i64, {4}, std::vector{1, -1, (int64_t) input_shape[2], (int64_t) input_shape[3]}), - false); + input_node = context.get_input(0); } else if (op_case == 1) { input_node = process_view_input_new(context, 0); } else if (op_case == 2) { @@ -41,7 +39,10 @@ OutputVector translate_rms_norm(const NodeContext & context) { // ssm_state_size * n_seqs rows. Slice it off (scaling by the active sequence count) to keep // just the attention output. ov::Output state_end; - if (context.has_input("s_copy_active_slot_len")) { + const auto attention_rows_name = "gdn_attention_rows_" + context.get_view_input_src_name(0, 0); + if (context.has_input(attention_rows_name)) { + state_end = context.get_input(attention_rows_name); + } else if (context.has_input("s_copy_active_slot_len")) { auto len = context.get_input("s_copy_active_slot_len"); auto state_rows = std::make_shared( ov::op::v0::Constant::create(ov::element::i64, {1}, {ssm_state_size}), len); @@ -49,17 +50,30 @@ OutputVector translate_rms_norm(const NodeContext & context) { } else { state_end = ov::op::v0::Constant::create(ov::element::i64, {1}, {-ssm_state_size}); } - auto gdn_attn_output = std::make_shared( - context.get_input(0), ov::op::v0::Constant::create(ov::element::i64, {1}, {0}), state_end, - ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), - ov::op::v0::Constant::create(ov::element::i64, {1}, {2})); + ov::Output gdn_attn_output; + if (context.has_input(attention_rows_name)) { + auto indices = std::make_shared( + ov::op::v0::Constant::create(ov::element::i64, {}, {0}), + std::make_shared(state_end), + ov::op::v0::Constant::create(ov::element::i64, {}, {1}), ov::element::i64); + gdn_attn_output = std::make_shared(context.get_input(0), indices, + ov::op::v0::Constant::create(ov::element::i64, {}, {2})); + } else { + gdn_attn_output = std::make_shared( + context.get_input(0), ov::op::v0::Constant::create(ov::element::i64, {1}, {0}), state_end, + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {2})); + } auto input_shape = context.get_input_shape(0).to_shape(); - input_node = std::make_shared( - gdn_attn_output, - ov::op::v0::Constant::create( - ov::element::i64, {4}, std::vector{1, -1, (int64_t) input_shape[2], (int64_t) input_shape[3]}), - false); + ov::Output sequences = ov::op::v0::Constant::create(ov::element::i64, {1}, {input_shape[0]}); + if (context.has_input("s_copy_active_slot_len")) { + sequences = context.get_input("s_copy_active_slot_len"); + } + auto shape = std::make_shared(ov::OutputVector{ + sequences, ov::op::v0::Constant::create(ov::element::i64, {3}, + std::vector{-1, (int64_t) input_shape[2], (int64_t) input_shape[3]})}, 0); + input_node = std::make_shared(gdn_attn_output, shape, false); } else { input_node = process_view_input_new(context, 0); diff --git a/ggml/src/ggml-openvino/openvino/op/view.cpp b/ggml/src/ggml-openvino/openvino/op/view.cpp index 486c2ff28ce4..70e191e2c86d 100644 --- a/ggml/src/ggml-openvino/openvino/op/view.cpp +++ b/ggml/src/ggml-openvino/openvino/op/view.cpp @@ -16,6 +16,15 @@ namespace op { OutputVector translate_view(const NodeContext & context) { num_inputs_check(context, 1, 1); + if (context.get_op_case() == 3) { + auto row = context.get_input("sampling_row_" + context.get_name()); + auto selected = std::make_shared(context.get_input(0), row, + ov::op::v0::Constant::create(ov::element::i64, {}, {2})); + auto shape = ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{1, 1, 1, context.get_output_shape()[3].get_length()}); + return rename_outputs_with_suffix({std::make_shared(selected, shape, false)}, context.get_name()); + } + if (context.get_op_case() == 1) { // Static-mode identity pass-through for VIEWs over a GATED_DELTA_NET combined output or // the conv_input CONCAT; the consuming op (CPY/RMS_NORM) does its own runtime-correct diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index 23b3a2cff3ea..845d6fb27c5f 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -96,6 +96,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_FLASH_ATTN_EXT", op::translate_flash_attn_ext }, {"GGML_OP_CLAMP", op::translate_clamp }, {"GGML_OP_PAD", op::translate_pad }, + {"GGML_OP_TOP_K", op::translate_top_k }, {"GGML_OP_SSM_CONV", op::translate_ssm_conv }, {"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net }, {"GGML_OP_REPEAT", op::translate_repeat }, diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 6ed7549a2652..fd2b50d2fabe 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -43,6 +43,7 @@ GGML_OP_CONVERTER(translate_glu_geglu_quick); GGML_OP_CONVERTER(translate_set_rows); GGML_OP_CONVERTER(translate_cpy); GGML_OP_CONVERTER(translate_argsort); +GGML_OP_CONVERTER(translate_top_k); GGML_OP_CONVERTER(translate_flash_attn_ext); GGML_OP_CONVERTER(translate_clamp); GGML_OP_CONVERTER(translate_pad); diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index a0c0709282e0..a95ea7a238b2 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -370,6 +371,73 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return input; } + // Packed projections can store query and gate in separate halves of each head. + if (!context.is_static() && view_input_size == 1) { + 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); + if (source.size() == 4 && view.size() == 4 && source_stride.size() == 4 && view_stride.size() == 4 && + source[0] == 1 && source[1] == 1 && view[0] == 1 && view[1] == source[2] && + view[2] > 0 && view[3] > 0 && source_stride[3] > 0 && + view_stride[1] == source_stride[2] && view_stride[3] == source_stride[3] && + view_stride[2] % source_stride[3] == 0) { + const size_t head_width = view_stride[2] / source_stride[3]; + const auto offset = context.get_view_input_offset(input_index, 0); + const auto source_offset = context.get_view_input_src_offset(input_index, 0); + if (head_width > view[3] && source[3] % head_width == 0 && source[3] / head_width == view[2] && + offset >= source_offset && (offset - source_offset) % source_stride[3] == 0) { + const size_t begin = (offset - source_offset) / source_stride[3]; + if (begin <= head_width - view[3]) { + auto heads = std::make_shared(input, + ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{1, -1, int64_t(view[2]), int64_t(head_width)}), false); + auto part = std::make_shared(heads, + ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + view[3]}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + return part; + } + } + } + } + + if (!context.is_static() && view_input_size == 1 && context.has_input("s_copy_active_slot_len")) { + 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); + if (source.size() == 4 && view.size() == 4 && source_stride.size() == 4 && view_stride.size() == 4 && + source[0] == 1 && view[0] == source[1] && view[1] == source[2] && view[3] > 0 && + view[2] <= source[3] / view[3] && + view_stride[0] == source_stride[1] && view_stride[1] == source_stride[2] && + view_stride[3] == source_stride[3]) { + const auto offset = context.get_view_input_offset(input_index, 0); + const auto source_offset = context.get_view_input_src_offset(input_index, 0); + if (offset >= source_offset && source_stride[3] > 0 && + (offset - source_offset) % source_stride[3] == 0) { + const int64_t begin = (offset - source_offset) / source_stride[3]; + const int64_t width = view[2] * view[3]; + if (begin <= int64_t(source[3]) - width) { + 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 + width}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + auto prefix = std::make_shared( + std::make_shared(input, ov::element::i64), + ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 2}), + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto shape = std::make_shared(ov::OutputVector{prefix, + ov::op::v0::Constant::create(ov::element::i64, {2}, + std::vector{int64_t(view[2]), int64_t(view[3])})}, 0); + return std::make_shared(sliced, shape, false); + } + } + } + } + // If translate_view already resolved this VIEW (produced a Slice), the input // will already have the expected shape — skip re-slicing. // diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 6db96abfa19e..b3efddf0a86d 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -404,6 +404,11 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr & ggml_d output_data = ggml_tensor->view_src->data; } else { output_shape = GgmlOvDecoder::get_shape(ggml_tensor); + if (ggml_tensor->op == GGML_OP_GATED_DELTA_NET && ggml_tensor->op_params[0] > 1) { + const auto * value = ggml_tensor->src[2]; + const int64_t valid_count = std::min(value->ne[2], ggml_tensor->op_params[0]); + output_shape[2] = (value->ne[2] + valid_count * value->ne[0]) * value->ne[3]; + } } } @@ -803,7 +808,7 @@ enum ggml_status naive_compute(ggml_cgraph * cgraph, // Debug-only output added via GGML_OPENVINO_DEBUG_NODE; nothing to copy into. if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") || ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) { - print_output_tensor_info(output_names[i], output_tensor, output_tensor.data()); + print_output_tensor_info(output_names[i], output_tensor, nullptr); } continue; } @@ -894,7 +899,9 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share if (cache_hit) { entry = it->second; } else { - r_ctx->clear_caches_locked(); + if (r_ctx->stateful || r_ctx->decoder_cache.size() >= 8) { + r_ctx->clear_caches_locked(); + } auto mutex = std::make_shared(); entry = std::make_shared(mutex); r_ctx->decoder_cache[key] = entry; @@ -1365,7 +1372,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) { for (size_t i = 0; i < ov_output_names.size(); i++) { const auto output_tensor = infer_request->get_output_tensor(i); - print_output_tensor_info(ov_output_names[i], output_tensor, output_tensor.data()); + print_output_tensor_info(ov_output_names[i], output_tensor, nullptr); } } @@ -1680,7 +1687,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) { for (size_t i = 0; i < ov_output_names_local.size(); i++) { const auto output_tensor = infer_request->get_output_tensor(i); - print_output_tensor_info(ov_output_names_local[i], output_tensor, output_tensor.data()); + print_output_tensor_info(ov_output_names_local[i], output_tensor, nullptr); } } } @@ -1720,7 +1727,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) { for (size_t i = 0; i < ov_output_names_local.size(); i++) { const auto output_tensor = infer_request->get_output_tensor(i); - print_output_tensor_info(ov_output_names_local[i], output_tensor, output_tensor.data()); + print_output_tensor_info(ov_output_names_local[i], output_tensor, nullptr); } } } @@ -1996,6 +2003,8 @@ void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor } void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst) { + ov::Tensor host(tensor.get_element_type(), tensor.get_shape()); + tensor.copy_to(host); std::cout << "Output name: " << name << ", Output shape: " << tensor.get_shape() << ", Address: " << output_dst << '\n'; @@ -2025,13 +2034,13 @@ void print_output_tensor_info(const std::string & name, const ov::Tensor & tenso switch (tensor.get_element_type()) { case ov::element::f32: { - const float * data = tensor.data(); + const float * data = host.data(); size_t size = tensor.get_size(); print_float_stats("[f32]", size, [data](size_t i) { return data[i]; }); break; } case ov::element::f16: { - const ov::float16 * data = tensor.data(); + const ov::float16 * data = host.data(); size_t size = tensor.get_size(); print_float_stats("[f16]", size, [data](size_t i) { return static_cast(data[i]); }); break; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index d8893025e700..40c5bc11fa68 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -3746,6 +3746,29 @@ struct test_rms_norm : public test_case { } }; +struct test_rms_norm_head_view : public test_case { + const int64_t head_size; + const int64_t heads; + const int64_t tokens; + const bool gate; + + test_rms_norm_head_view(int64_t head_size, int64_t heads, int64_t tokens, bool gate) + : head_size(head_size), heads(heads), tokens(tokens), gate(gate) {} + + std::string vars() override { return VARS_TO_STR4(head_size, heads, tokens, gate); } + std::string op_desc(ggml_tensor *) override { return "RMS_NORM_HEAD_VIEW"; } + bool run_whole_graph() override { return true; } + + ggml_tensor * build_graph(ggml_context * ctx) override { + auto * input = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2 * head_size * heads, tokens); + auto * packed = ggml_scale(ctx, input, 0.75f); + auto * view = ggml_view_3d(ctx, packed, head_size, heads, tokens, + 2 * head_size * sizeof(float), 2 * head_size * heads * sizeof(float), + gate ? head_size * sizeof(float) : 0); + return ggml_rms_norm(ctx, view, 1e-6f); + } +}; + // GGML_OP_RMS_NORM_BACK struct test_rms_norm_back : public test_case { const ggml_type type; @@ -4783,17 +4806,20 @@ struct test_gated_delta_net_cache_fusion : public test_case { const int64_t n_seq_tokens; const int64_t n_seqs; const int64_t K; // snapshot slot count (>1) + const int64_t cache_slots; + const int64_t cache_begin; ggml_tensor * cpy_node = nullptr; std::string vars() override { - return VARS_TO_STR6(type, head_count, head_size, n_seq_tokens, n_seqs, K); + return VARS_TO_STR8(type, head_count, head_size, n_seq_tokens, n_seqs, K, cache_slots, cache_begin); } test_gated_delta_net_cache_fusion(ggml_type type = GGML_TYPE_F32, int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1, - int64_t K = 2) - : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), K(K) {} + int64_t K = 2, int64_t cache_slots = 0, int64_t cache_begin = 0) + : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), K(K), + cache_slots(cache_slots ? cache_slots : n_seqs), cache_begin(cache_begin) {} ggml_tensor * build_graph(ggml_context * ctx) override { const int64_t S_v = head_size; @@ -4838,12 +4864,12 @@ struct test_gated_delta_net_cache_fusion : public test_case { ggml_row_size(gdn_out->type, attn_score_elems)); // recurrent cache view [D, n_seqs, n_written] - ggml_tensor * cache = ggml_new_tensor_3d(ctx, type, D, n_seqs, n_written); + ggml_tensor * cache = ggml_new_tensor_2d(ctx, type, D, cache_slots * K); ggml_set_name(cache, "cache"); ggml_tensor * dst = ggml_view_3d(ctx, cache, D, n_seqs, n_written, ggml_row_size(cache->type, D), - ggml_row_size(cache->type, D * n_seqs), 0); + ggml_row_size(cache->type, D * cache_slots), ggml_row_size(cache->type, D * cache_begin)); ggml_tensor * cpy = ggml_cpy(ctx, src, dst); ggml_set_name(cpy, "gdn_cache_cpy"); @@ -4851,7 +4877,7 @@ struct test_gated_delta_net_cache_fusion : public test_case { // read the cpy output (not the plain dst view, which would not pull the cpy into the graph) // so that neither the gdn nor the cpy is the graph output - ggml_tensor * out = ggml_sum(ctx, cpy); + ggml_tensor * out = ggml_sum(ctx, ggml_add(ctx, cache, ggml_scale(ctx, ggml_sum(ctx, cpy), 0.0f))); return out; } @@ -4861,7 +4887,7 @@ struct test_gated_delta_net_cache_fusion : public test_case { } bool run_whole_graph() override { return true; } - std::vector fusion_test_nodes() override { return { cpy_node }; } + std::vector fusion_test_nodes() override { return {}; } uint64_t op_flops(ggml_tensor * t) override { GGML_UNUSED(t); @@ -4882,7 +4908,7 @@ struct test_gated_delta_net_cache_fusion : public test_case { } else if (strcmp(t->name, "v") == 0) { init_tensor_uniform(t, -0.3f, 5.0f); } else if (strcmp(t->name, "cache") == 0) { - init_tensor_uniform(t, 0.0f, 0.0f); + init_tensor_uniform(t, 0.25f, 0.75f); } else { init_tensor_uniform(t); } @@ -10110,6 +10136,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_softcap(GGML_TYPE_F32, {10, 10, 10, 10}, 50.0f)); test_cases.emplace_back(new test_silu_back()); + for (int64_t tokens : {1, 2, 5}) { + for (bool gate : {false, true}) { + test_cases.emplace_back(new test_rms_norm_head_view(256, 8, tokens, gate)); + } + } for (float eps : { 0.0f, 1e-6f, 1e-4f, 1e-1f, 10.f }) { for (uint32_t n : { 64, 1025 }) { for (bool v : { false, true }) { @@ -11025,6 +11056,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {n, 2, 1, 3}, k, true)); } } + for (int k : {10, 64}) { + for (bool ties : {false, true}) { + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {248320, 2, 1, 3}, k, ties)); + } + } for (int i = 0; i < 20; ++i) { for (int k : {1, 2, 3, 7, 15, 100, 500, 1023, 9999}) { if (k <= 1<> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1, 4)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2, 4)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1, 4)); + for (int64_t head_size : {32, 128}) { + for (int64_t tokens : {1, 2, 3, 5}) { + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, head_size, tokens, 2, 3, 5, 1)); + } + } #if 0 // these tests are disabled to save execution time, sbut they can be handy for debugging diff --git a/tests/test-backend-sampler.cpp b/tests/test-backend-sampler.cpp index 56736ac4682d..d5098b3ce8e2 100644 --- a/tests/test-backend-sampler.cpp +++ b/tests/test-backend-sampler.cpp @@ -2,6 +2,7 @@ #include "llama.h" #include "llama-cpp.h" #include "common.h" +#include "../src/llama-ext.h" #ifdef NDEBUG #undef NDEBUG @@ -87,7 +88,8 @@ struct test_context { int32_t n_seq_max = -1, uint32_t n_outputs_max = 0, uint32_t n_ubatch = 0, - uint32_t n_outputs_max_per_seq = 1) { + uint32_t n_outputs_max_per_seq = 1, + uint32_t n_rs_seq = 0) { auto * model = params.model.get(); GGML_ASSERT(model); @@ -101,6 +103,7 @@ struct test_context { } cparams.n_outputs_max = n_outputs_max; cparams.n_outputs_max_per_seq = n_outputs_max_per_seq; + cparams.n_rs_seq = n_rs_seq; cparams.samplers = configs.data(); cparams.n_samplers = configs.size(); cparams.kv_unified = true; @@ -375,6 +378,10 @@ static void test_backend_top_k_sampling(const test_params & params) { llama_token * candidates = llama_get_sampled_candidates_ith(test_ctx.ctx.get(), batch_idx); uint32_t n_candidates = llama_get_sampled_candidates_count_ith(test_ctx.ctx.get(), batch_idx); + GGML_ASSERT(n_candidates == (uint32_t) k && n_logits == (uint32_t) k); + std::vector sorted_candidates(candidates, candidates + n_candidates); + std::sort(sorted_candidates.begin(), sorted_candidates.end()); + GGML_ASSERT(std::adjacent_find(sorted_candidates.begin(), sorted_candidates.end()) == sorted_candidates.end()); for (size_t i = 0; i < n_candidates; ++i) { printf("top_k candidate[%zu] = %d : %s\n", i, candidates[i], test_ctx.token_to_piece(candidates[i], false).c_str()); @@ -984,7 +991,8 @@ static sampler_comparison_stats compare_sampler_outputs( const char * name, const std::unordered_map & expected, const backend_sampler_output & actual, - bool allow_extra_candidates = false) { + bool allow_extra_candidates = false, + float tolerance = 1e-3f) { GGML_ASSERT(actual.logits.size() == actual.candidates.size()); sampler_comparison_stats result; @@ -1017,7 +1025,7 @@ static sampler_comparison_stats compare_sampler_outputs( const float diff = fabsf(it->second - logit); result.max_diff = std::max(result.max_diff, diff); - if (!std::isfinite(logit) || diff > 1e-3f) { + if (!std::isfinite(logit) || diff > tolerance) { if (result.n_mismatch < 5) { printf("%s mismatch token %d: cpu=%.6f backend=%.6f diff=%.6f\n", name, token, it->second, logit, diff); @@ -1040,6 +1048,135 @@ static sampler_comparison_stats compare_sampler_outputs( return result; } +static void test_backend_top_k_rows_impl(const test_params & params, uint32_t n_rs_seq, bool hidden = false) { + const int32_t k = 8; + llama_sampler_ptr chain0(llama_sampler_chain_init(llama_sampler_chain_default_params())); + llama_sampler_ptr chain1(llama_sampler_chain_init(llama_sampler_chain_default_params())); + llama_sampler_chain_add(chain0.get(), llama_sampler_init_top_k(k)); + llama_sampler_chain_add(chain1.get(), llama_sampler_init_top_k(k)); + std::vector configs = {{0, chain0.get()}, {1, chain1.get()}}; + std::vector reference_configs; + test_context ctx(params, configs, 2, 6, 8, 3, n_rs_seq); + test_context reference(params, reference_configs, 2, 6, 8, 3); + if (hidden) { + llama_set_embeddings_nextn(ctx.ctx.get(), true, false); + llama_set_embeddings_nextn(reference.ctx.get(), true, false); + } + llama_sampler_ptr cpu_top_k(llama_sampler_init_top_k(k)); + + struct batch_case { + int counts[2]; + bool output; + }; + const batch_case cases[] = {{{2, 2}, true}, {{1, 1}, true}, {{2, 0}, false}, + {{0, 3}, true}, {{2, 1}, true}, {{1, 1}, true}, {{1, 0}, true}}; + int32_t positions[2] = {0, 0}; + int case_index = 0; + for (const auto & c : cases) { + auto make_batch = [&](llama_context * context) { + common_batch batch(context); + for (llama_seq_id seq = 0; seq < 2; ++seq) { + const int rejected = n_rs_seq > 0 && context == reference.ctx.get() ? + (case_index == 4 && seq == 0 ? 1 : case_index == 3 && seq == 1 ? 2 : 0) : 0; + const int count = c.counts[seq] - rejected; + for (int i = 0; i < count; ++i) { + const llama_token token = (100 + seq * 100 + positions[seq] + i) % ctx.n_vocab; + batch.add(token, positions[seq] + i, seq, c.output); + } + } + return batch; + }; + auto batch = make_batch(ctx.ctx.get()); + auto reference_batch = make_batch(reference.ctx.get()); + GGML_ASSERT(llama_process(ctx.ctx.get(), LLAMA_PROCESS_TYPE_DECODE, batch.get()) == 0); + GGML_ASSERT(llama_process(reference.ctx.get(), LLAMA_PROCESS_TYPE_DECODE, reference_batch.get()) == 0); + if (hidden) { + const int32_t n_embd = llama_model_n_embd(params.model.get()); + for (int i = 0; i < batch.size(); ++i) { + if (n_rs_seq > 0 && ((case_index == 4 && i == 1) || (case_index == 3 && i > 0))) { + continue; + } + const int reference_row = i - (n_rs_seq > 0 && case_index == 4 && i > 1); + const float * actual = llama_get_embeddings_nextn_ith(ctx.ctx.get(), i); + const float * expected = llama_get_embeddings_nextn_ith(reference.ctx.get(), reference_row); + GGML_ASSERT(actual != nullptr && expected != nullptr); + double error = 0.0; + double norm = 0.0; + float max_diff = 0.0f; + for (int j = 0; j < n_embd; ++j) { + GGML_ASSERT(std::isfinite(actual[j]) && std::isfinite(expected[j])); + const float diff = actual[j] - expected[j]; + max_diff = std::max(max_diff, std::abs(diff)); + error += double(diff) * diff; + norm += double(expected[j]) * expected[j]; + } + const double relative_error = std::sqrt(error / std::max(norm, 1e-12)); + printf("top_k_rows h_nextn: max_diff=%.6f relative_error=%.6f\n", max_diff, relative_error); + GGML_ASSERT(relative_error < 1e-2); + } + } + for (int i = 0; c.output && i < batch.size(); ++i) { + if (n_rs_seq > 0 && ((case_index == 4 && i == 1) || (case_index == 3 && i > 0))) { + continue; + } + const int reference_row = i - (n_rs_seq > 0 && case_index == 4 && i > 1); + const float * raw = llama_get_logits_ith(reference.ctx.get(), reference_row); + GGML_ASSERT(raw != nullptr); + const auto expected = apply_cpu_sampler(std::vector(raw, raw + ctx.n_vocab), cpu_top_k.get()); + const uint32_t n_logits = llama_get_sampled_logits_count_ith(ctx.ctx.get(), i); + const uint32_t n_candidates = llama_get_sampled_candidates_count_ith(ctx.ctx.get(), i); + GGML_ASSERT(n_logits == (uint32_t) k && n_candidates == (uint32_t) k); + const float * logits = llama_get_sampled_logits_ith(ctx.ctx.get(), i); + const llama_token * candidates = llama_get_sampled_candidates_ith(ctx.ctx.get(), i); + GGML_ASSERT(logits != nullptr && candidates != nullptr); + backend_sampler_output actual; + actual.logits.assign(logits, logits + n_logits); + actual.candidates.assign(candidates, candidates + n_candidates); + const float tolerance = 2e-2f; + float cutoff = expected.front().logit; + for (const auto & candidate : expected) { + cutoff = std::min(cutoff, candidate.logit); + } + std::unordered_map selected_logits; + for (const auto token : actual.candidates) { + GGML_ASSERT(token >= 0 && token < ctx.n_vocab); + GGML_ASSERT(raw[token] >= cutoff - tolerance); + GGML_ASSERT(selected_logits.emplace(token, raw[token]).second); + } + for (const auto & candidate : expected) { + GGML_ASSERT(candidate.logit <= cutoff + tolerance || selected_logits.count(candidate.id) != 0); + } + // GPU f16 rounding can exchange candidates at the top-k boundary. + GGML_ASSERT(compare_sampler_outputs("top_k_rows", selected_logits, actual, false, tolerance).n_mismatch == 0); + } + for (int seq = 0; seq < 2; ++seq) { + positions[seq] += c.counts[seq]; + } + if (n_rs_seq > 0 && case_index == 4) { + GGML_ASSERT(llama_memory_seq_rm(llama_get_memory(ctx.ctx.get()), 0, positions[0] - 1, -1)); + --positions[0]; + } + if (n_rs_seq > 0 && case_index == 3) { + GGML_ASSERT(llama_memory_seq_rm(llama_get_memory(ctx.ctx.get()), 1, positions[1] - 2, -1)); + positions[1] -= 2; + } + ++case_index; + } + printf("backend top-k changing rows test PASSED\n"); +} + +static void test_backend_top_k_rows(const test_params & params) { + test_backend_top_k_rows_impl(params, 0); +} + +static void test_backend_top_k_rows_rollback(const test_params & params) { + test_backend_top_k_rows_impl(params, 2); +} + +static void test_backend_top_k_hidden_rollback(const test_params & params) { + test_backend_top_k_rows_impl(params, 2, true); +} + static float find_backend_logit(const backend_sampler_output & output, llama_token token) { for (size_t i = 0; i < output.candidates.size(); ++i) { if (output.candidates[i] == token) { @@ -1984,6 +2121,9 @@ static const backend_test_case BACKEND_TESTS[] = { { "temp", test_backend_temp_sampling, true }, { "temp_ext", test_backend_temp_ext_sampling, true }, { "top_k", test_backend_top_k_sampling, true }, + { "top_k_rows", test_backend_top_k_rows, true }, + { "top_k_rollback", test_backend_top_k_rows_rollback, false }, + { "top_k_hidden_rollback", test_backend_top_k_hidden_rollback, false }, { "multi_sequence", test_backend_multi_sequence_sampling, true }, { "dist", test_backend_dist_sampling, true }, { "dist_and_cpu", test_backend_dist_sampling_and_cpu, true }, @@ -2085,7 +2225,7 @@ static std::vector collect_tests_to_run(const std::st if (test.name == "penalties" || test.name == "set_sampler" || test.name == "mixed" || test.name == "top_p" || test.name == "multi_output_sampling_chain" || - test.name == "multi_output_cpu") { + test.name == "multi_output_cpu" || test.name == "top_k_rows" || test.name == "top_k_rollback" || test.name == "top_k_hidden_rollback") { fprintf(stderr, "Skipping test '%s' on HIP backend (no backend TOP_K support)\n", test.name.c_str()); continue; } From 4f92304c26941abd98ab28167f2a7eefe24c258e Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 15 Oct 2026 09:21:09 +0200 Subject: [PATCH 21/65] openvino: Optimize TopK --- ggml/src/ggml-openvino/openvino/op/argsort.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-openvino/openvino/op/argsort.cpp b/ggml/src/ggml-openvino/openvino/op/argsort.cpp index e6460b02eea7..a3ae09fbd98a 100644 --- a/ggml/src/ggml-openvino/openvino/op/argsort.cpp +++ b/ggml/src/ggml-openvino/openvino/op/argsort.cpp @@ -69,9 +69,10 @@ OutputVector translate_top_k(const NodeContext & context) { auto chunked = std::make_shared(input, ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{-1, 1, chunks, chunk_size}), false); // Each global top-k candidate is in its chunk's top-k set. + // Value sorting selects the parallel GPU kernel; ggml allows any index order. auto local = std::make_shared(chunked, ov::op::v0::Constant::create(ov::element::i32, {}, {k}), -1, - ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::NONE, ov::element::i32, false); + ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES, ov::element::i32, false); std::vector offsets(chunks); for (int64_t i = 0; i < chunks; ++i) { offsets[i] = i * chunk_size; @@ -83,7 +84,7 @@ OutputVector translate_top_k(const NodeContext & context) { auto candidate_indices = std::make_shared(indices, candidate_shape, false); auto selected = std::make_shared(values, ov::op::v0::Constant::create(ov::element::i32, {}, {k}), -1, - ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::NONE, ov::element::i32, false); + ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES, ov::element::i32, false); auto result = std::make_shared(candidate_indices, selected->output(1), 3); auto output_shape = std::make_shared(OutputVector{ get_dimensions(input.get_node_shared_ptr(), {0, 1, 2}), From 73f61e1cbe96703ad8976e8c387485547aec6459 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 15 Oct 2026 11:14:49 +0200 Subject: [PATCH 22/65] openvino: remove single-slot recurrent cache shortcuts Use runtime reset, reorder and partial writeback paths at every stateless slot count. Preserve initially empty cache writes across graph reuse, select active state rows dynamically, and fix reset byte offsets. Add a four-slot reset/copy/rollback regression and document the corrected performance baseline and native cache-fusion opportunities. Validate the 35B model in four-slot serving with and without MTP, plus CPU/GPU operator checks and the existing hidden-state rollback test. Assisted-by: Codex --- docs/backend/OPENVINO-RECURRENT-CACHE.md | 123 ++++++++++++++++++ ggml/src/ggml-openvino/README.md | 6 + ggml/src/ggml-openvino/ggml-decoder.cpp | 69 +++++----- ggml/src/ggml-openvino/openvino/op/cpy.cpp | 49 +++---- .../ggml-openvino/openvino/op/get_rows.cpp | 4 - ggml/src/ggml-openvino/openvino/op/scale.cpp | 4 - ggml/src/ggml-openvino/openvino/op/view.cpp | 11 ++ ggml/src/ggml-openvino/utils.cpp | 27 +--- tests/test-backend-sampler.cpp | 72 ++++++++++ 9 files changed, 268 insertions(+), 97 deletions(-) create mode 100644 docs/backend/OPENVINO-RECURRENT-CACHE.md diff --git a/docs/backend/OPENVINO-RECURRENT-CACHE.md b/docs/backend/OPENVINO-RECURRENT-CACHE.md new file mode 100644 index 000000000000..e1b03f88cda9 --- /dev/null +++ b/docs/backend/OPENVINO-RECURRENT-CACHE.md @@ -0,0 +1,123 @@ +# Generic recurrent-cache baseline for Qwen MTP + +Date: 2026-10-15. Branch: `qwen-openvino-generic-cache`. Model: Qwen3.6-35B-A3B-Q4_K_M_yamini.gguf. + +Removing the single-slot shortcuts changes the matched non-MTP `tg512` baseline from **35.54 to 19.72 tokens/s** (33.62 to 19.10 at depth 1024). Four-slot serving passes both with and without MTP. On the same greeting workload, MTP now measures **23.21 tokens/s versus 19.45 without MTP**, approximately a 19% improvement against the generic path. + +The previous non-MTP baseline used single-slot shortcuts that were unavailable to MTP. Consequently, the earlier 36.1 versus 80.7 ms three-token comparison mixed the cost of general cache maintenance with the cost of retaining rollback snapshots. It did not isolate snapshot capture alone. The baseline below removes that confound. + +## Changes + +Stateless execution now uses the same reset, gather/reorder, and partial-writeback translations for one or multiple slots. Removed the host-side single-slot cache clear, reset/gather identity cases, and full-cache replacement/no-op CPY cases 7/8/9. Native GatedDeltaNet direct output routing, convolution-window Gather, and the TopK improvement remain: these support multiple slots. + +Exercising the generic paths also exposed and fixed three correctness problems: + +- Reset offsets were divided by elements per row instead of bytes per row, selecting the wrong row for nonzero offsets. +- Views of active recurrent states could retain inactive rows from the combined gather when the active sequence count changed. They now select the runtime active prefix before reshaping. +- An initially empty reset or reorder remainder could disappear from the translated in-place alias chain even when a later batch made it nonempty. Dynamic recurrent writes now remain in that chain, and remainder source/destination offsets are runtime inputs. + +The compiled-model cache translation revision is incremented. Existing blobs must be regenerated once with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` unset. The user's `tmp/qwen36_ud_cache` directory was not present in this workspace; measurements use cold model loading and exclude it from token-throughput timing. + +## Benchmark method and results + +Hardware: Intel Arc B390 iGPU / Core Ultra X7 358H, 62 GiB RAM. Both locally matched runs use Release `build/MtpOVPerf`, the same existing unrelated working-tree changes, llama.cpp starting at `4f92304c2`, and the OpenVINO runtime containing `21cacac33d`. No stateful execution is used. The appendix used `build/ReleaseOV`, whose configured runtime is a different 2026.4.1 toolkit; treat that column as a reference, not the matched control. + +Both matched benchmark runs use: + +```sh +GGML_OPENVINO_DEVICE=GPU \ +GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ +GGML_OPENVINO_DISABLE_KV_SLICE=1 \ +GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ +build/MtpOVPerf/bin/llama-bench \ + -m "$HOME/models/Qwen3.6-35B-A3B-GGUF/Qwen3.6-35B-A3B-Q4_K_M_yamini.gguf" \ + -p 1024 -n 512 -d 0,1024 +``` + +Default five repetitions; values are reported tokens/s with the benchmark's standard deviation. GPU workloads run serially. + +| Workload | User appendix | Local before removal | Generic cache path | +| --- | ---: | ---: | ---: | +| pp1024 | 1051.29 +/- 5.21 | 1151.77 +/- 8.85 | 1058.21 +/- 7.29 | +| tg512 | 36.98 +/- 0.10 | 35.54 +/- 0.06 | 19.72 +/- 0.03 | +| pp1024 at depth 1024 | 979.10 +/- 61.42 | 1089.73 +/- 48.93 | 1016.84 +/- 17.64 | +| tg512 at depth 1024 | 34.77 +/- 0.05 | 33.62 +/- 0.05 | 19.10 +/- 0.03 | + +### Controlled target calls + +One loaded model, identical forced-token stream, context 4096, one slot, two CPU threads, hidden-state extraction enabled. Each case has a 128-token prefix, eight warmup calls, and 32 measured calls. Values are median milliseconds per target call. The previous OpenVINO and Vulkan columns are from the 2026-10-14 experiment; Vulkan was not rerun for this OpenVINO-only cleanup. + +| Target call | Previous OV path | Generic OV path | Prior Vulkan reference | +| --- | ---: | ---: | ---: | +| 1 token, no snapshots | 28.31 | 49.41 | 43.21 | +| 3 tokens, no snapshots | 36.10 | 62.55 | 54.29 | +| 1 token, snapshots | 62.01 | 76.49 | 33.54 | +| 3 tokens, snapshots, no rejection | 80.74 | 95.57 | 52.59 | +| 3 tokens, snapshots, reject 2 | 79.37 | 95.67 | 52.72 | + +With the generic baseline, moving from one to three tokens without snapshots adds **13.14 ms**; enabling snapshots at three tokens adds **33.02 ms**. Along this comparison, the snapshot-enabled path accounts for about **72%** of the increase from one-token ordinary decode to three-token verification, rather than the earlier approximately 85%. These deltas include the full graph's layout, cache, scheduling, and storage changes; they are not timings of the native GDN kernel alone. + +Rejecting two tokens changes the target median by only 0.10 ms here. The host `seq_rm` median is 0.0075 ms; the following target call includes the deferred restore. The large penalty is present even with no rejection. In the final rejection-case call, the full target call was 96.10 ms and OpenVINO `infer()` was 94.40 ms. This places most latency inside OpenVINO execution, which includes scheduling and synchronization as well as kernels. + +The old claim that a one-token call returns to roughly 28-30 ms applies to the removed shortcuts. The generic path now measures 49.41 ms without snapshots and 76.49 ms with them. + +### End-to-end generation + +Same `Hi` prompt, context 4096, one slot, two CPU threads, temperature zero, and a 192-token cap. These runs use the target requantization and the same Release build. Per-call medians exclude positions below 64. Generation rates exclude model loading and prompt processing. + +| Measurement | Generic non-MTP | Generic MTP, two proposals | +| --- | ---: | ---: | +| Generation throughput | 19.45 tokens/s | 23.21 tokens/s | +| Generated tokens | 159 | 154 | +| One-token target call, median | 49.85 ms | - | +| Three-token verification, median | - | 95.62 ms | +| One draft token, median | - | 6.09 ms | +| Three-token draft catch-up, median | - | 1.91 ms | +| Accepted proposals | - | 95 / 116 (81.90%) | +| Mean output length per round | - | 2.64 | + +MTP is approximately **19.3% faster** than the generic non-MTP path on this greeting. The generated continuations have different lengths, so use the controlled target-call table for causal comparisons of batch width and snapshots. These are one process run per mode with many warmed calls, rather than repeated independent trials. + +Compared with the earlier TopK-optimized MTP run, throughput falls from 27.55 to 23.21 tokens/s while output length and acceptance remain 154 and 95/116. Median verification rises from 78.08 to 95.62 ms; draft latency changes only from 5.93 to 6.09 ms. The generic reset/reorder correctness fixes affect snapshot-enabled graphs too, particularly operations that were empty in the first captured batch. The absolute MTP slowdown therefore accompanies removal of the misleadingly fast non-MTP baseline. + +A speculative round costs approximately `verification + catch-up + 2 * draft + host work`, divided by `1 + accepted proposals`, not always three output tokens. The measured median compute subtotal is 109.71 ms/round; at 2.64 output tokens this is 41.56 ms/token before remaining host work, close to the reported 43.09 ms/token. + +The previous Vulkan greeting reference was 49.83 tokens/s, with 42.56 ms verification, 4.99 ms per draft, and 2.31 ms catch-up. Vulkan was not rerun here. The remaining OpenVINO gap is concentrated in target verification; the controlled results still identify snapshot-enabled cache maintenance as the largest added cost, while ordinary generic cache maintenance is also substantial. Separate kernel profiling is needed to divide that cost among dispatch, shape work, layout conversion, and memory traffic. + +## Validation + +- Release build and `git diff --check` pass. +- New `test-backend-sampler --test recurrent_slots`: four slots with changing active subsets, nonzero-slot reset, sequence copy/branch, inactive-slot preservation, and unequal rejection lengths. Both zero and two rollback positions are compared with independently replayed single-sequence logits on Qwen3.5-2B Q4_0. Maximum relative logit error: 0.006757 across 40 sequence comparisons. +- Existing hidden-state / zero-output / changing-sequence / rollback sampler check passes. +- Selected GPU operator tests: 266/266 supported cases pass. +- Selected CPU operator tests: 262/262 supported cases pass. +- Full 35B model: 12/12 server requests pass without MTP and 12/12 with two-token MTP, using `-np 4 -c 16384`, ordinary separate KV streams (`kv_unified=false`), temperature zero, and the target requantization. Cases include two concurrent four-slot waves, reset/reuse of selected slots, and cached continuation of an inactive slot. The MTP run generated 64 draft tokens and accepted 43. These short requests include graph compilation and are functional checks, not throughput comparisons. + +The optional full-model functional attempt with requantization unset hit an OpenVINO `FullyConnectedHorizontalFusion` failure in the unchanged runtime: projection scale shapes `[8192,1]`, `[512,64]`, and `[512,64]` cannot be concatenated. Full-model validation therefore uses the target `q4_asym64_all` configuration. That runtime fusion issue is outside this cache cleanup. + +A stateless forced-static CPU smoke test (Qwen3.5-2B, prefill chunks of 8, 16 generated tokens) matches dynamic CPU generation. Stateful execution and NPU execution were not tested. CPU recurrent snapshots are not supported by the native OpenVINO runtime. + +## Generic cache fusion opportunities + +`cache_r` and `cache_s` are the convolution and recurrent matrix state of the model's linear-attention blocks; they are separate from the ordinary flash-attention K/V cache. + +The proposed graph groups are useful fusion boundaries. Their main benefit would be eliminating intermediate kernels, shape work, and repeated cache copying. The current full-model translator already publishes the final cache root after chaining in-place writes; the existing target IRs have one `cache_r` and one `cache_s` Result per recurrent layer. Older IRs with duplicate cache Results should not be used to count current output transfers. + +| Proposed native operation | GGML subgraph from cgraph_ov.txt | Inputs | Outputs | +| --- | --- | --- | --- | +| RecurrentConvCache | 7-14 and 17-27 | old convolution cache; new QKV; reset range; source/destination row maps; active count; valid-token count; snapshot window starts and destination rows | convolution input for SSM_CONV; final updated convolution cache | +| RecurrentStateGather | 28-35 | old matrix-state cache; reset range; source/destination row maps; active count | active matrix states for GatedDeltaNet; reset/reordered cache feeding the later state writeback | + +`RecurrentConvCache` must depend on the QKV projection at node 15/16. Its first output replaces node 18, while its second replaces the final cache write. A kernel can read each history/new-token element directly for both outputs without constructing separate reset, gather, concatenation, and snapshot-copy intermediates. The convolution itself can remain outside this first implementation. + +`RecurrentStateGather` alone cannot perform final GDN writeback: that data does not exist until GatedDeltaNet runs. A subsequent generic cache-update fusion, or a cache-aware GatedDeltaNet variant, would remove the remaining snapshot layout/scatter chain. Only the final cache becomes a model Result; the prepared-cache output remains internal. + +Both operations must preserve arbitrary active subsets, inactive slots, repeated gather indices/sequence copies, nonzero destination rows, reset-before-gather ordering, valid snapshot prefixes when Tname, "conv_states_all", strlen("conv_states_all")) == 0; } - -bool is_full_single_slot_writeback(const ggml_tensor * node) { - return node->view_src != nullptr && node->view_src->ne[1] == 1 && node->src[1] != nullptr && - node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src && - node->src[1]->view_offs == 0 && ggml_nbytes(node->src[1]) == ggml_nbytes(node->view_src); -} } // namespace // MoE expert aggregation (build_moe_ffn in llama-graph.cpp): each expert plane is @@ -476,16 +470,11 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { // GET_ROWS gathering recurrent state cache rows via the inp->s_copy index list: // src[0] is a reshape of cache_r/cache_s, src[1] is a view of the s_copy leaf, or the leaf itself // when one gather covers all states (see build_rs). - // op_case 1/2: active/extra rows of a multi-slot cache - // op_case 3/4: active/extra rows of a single-slot cache + // op_case 1/2: active/extra rows, independent of cache capacity. if (node->src[0]->op == GGML_OP_RESHAPE && node->src[0]->src[0] != nullptr && is_recurrent_cache(node->src[0]->src[0])) { - const bool single_slot = node->src[0]->src[0]->ne[1] == 1; if (node->src[1]->op == GGML_OP_VIEW) { - op_case = (node->src[1]->view_offs == 0 ? 1 : 2) + (single_slot ? 2 : 0); - } else if (single_slot) { - // a single-slot cache holds exactly the one state the gather selects - op_case = 3; + op_case = node->src[1]->view_offs == 0 ? 1 : 2; } } break; @@ -519,6 +508,13 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { if (is_sampling_view(node)) { return 3; } + if (node->view_offs == 0 && node->src[0]->op == GGML_OP_GET_ROWS && + is_recurrent_cache(node->src[0]->src[0]) && node->ne[0] == node->src[0]->ne[0] && + node->ne[2] == 1 && node->ne[3] == 1 && m_compute_params.s_copy_active_slot_len != -1) { + // build_rs gathers active and inactive rows together; consumers need only the + // active prefix, whose length changes independently of the gather's row count. + return 4; + } if (is_direct_gdn_view(node)) { // The GDN translator publishes native attention/state outputs under these VIEW names. op_case = 2; @@ -635,14 +631,13 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { if (is_gdn_snapshot_writeback(node)) { op_case = is_direct_gdn_view(node->src[0]) ? 12 : 11; } else if (!m_model_params.has_rs_rollback) { - // op_case 7 replaces a single-slot cache; op_case 10 writes native GDN state - // into an active range of a larger non-rollback cache. - op_case = is_full_single_slot_writeback(node) ? 7 : 10; + // Write native GDN state into the runtime active range of the cache. + op_case = 10; } else { op_case = 1; } } else if (GgmlOvDecoder::is_conv_state_writeback(node)) { - op_case = is_full_single_slot_writeback(node) ? 8 : 2; + op_case = 2; break; } else if (is_conv_states_all_tensor(node->view_src) && node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) { @@ -650,16 +645,15 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { break; } else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr && - is_recurrent_cache(node->src[1]->view_src) && node->src[1]->view_src->ne[1] == 1) { - // defrag remainder writeback of a single-slot cache, taken from a view of the one gather of - // all states (see build_rs) - op_case = 9; + is_recurrent_cache(node->src[1]->view_src)) { + // Remainder view of the combined state gather (see build_rs). + op_case = 3; } } else if (node->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr && is_recurrent_cache(node->src[1]->view_src)) { // s_copy defrag remainder writeback: gathered extra state rows copied back into the cache - op_case = node->src[1]->view_src->ne[1] == 1 ? 9 : 3; + op_case = 3; } else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr) { // op_case 5: KV write for decoder self-attention (dynamic write offset) // op_case 6: KV write for encoder self-attn or cross-attn (static offset) @@ -698,7 +692,7 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } case GGML_OP_SCALE: { if (node->view_src && node->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY) { - op_case = node->view_src->ne[1] == 1 ? 2 : 1; + op_case = 1; } break; } @@ -1108,7 +1102,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr GGML_ASSERT(model_params.n_rs_slots == node->view_src->ne[1]); } compute_params.cache_rs_reset_len = ggml_nelements(node) / node->view_src->ne[0]; - compute_params.cache_rs_reset_idx = node->src[0]->view_offs / node->view_src->ne[0]; + compute_params.cache_rs_reset_idx = node->src[0]->view_offs / node->view_src->nb[1]; } // Capture the destination slot block of every recurrent state cache writeback, plus the // source window needed by conv state and packed GDN rollback writes. The active sequences @@ -1119,7 +1113,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr const bool is_conv = is_conv_state_writeback(node); const bool is_gdn = node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr && node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET; - const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS; + const bool is_extra_view = node->src[0]->op == GGML_OP_VIEW && + node->src[0]->src[0]->op == GGML_OP_GET_ROWS; + const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS || is_extra_view; const bool is_gdn_rollback = is_gdn && is_same_shape(node->src[0], node->src[1]); const ggml_tensor * dest_view = node->src[1]; @@ -1132,7 +1128,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr // signature is local to the CPY and still works when fallback splits the graph. model_params.has_rs_rollback = true; } - if (row_bytes > 0 && (is_conv || is_gdn || is_extra) && !is_full_single_slot_writeback(node) && + if (row_bytes > 0 && (is_conv || is_gdn || is_extra) && !(is_gdn && node->src[0]->src[0]->op_params[0] > 1)) { ComputeParams::RsWriteback writeback; writeback.slot_begin = (int) (dest_view->view_offs / row_bytes); @@ -1140,10 +1136,12 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[0]); } else if (is_gdn_rollback) { writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[1]); + } else if (is_extra_view) { + writeback.src_begin = (int) (node->src[0]->view_offs / row_bytes); } compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; } - if ((is_conv || is_gdn) && !is_full_single_slot_writeback(node)) { + if (is_conv || is_gdn) { compute_params.s_copy_active_slot_len = (int) dest_view->ne[1]; } } @@ -1382,7 +1380,7 @@ void GgmlOvDecoder::add_extra_inputs() { from_mask("n_seq_active", full.empty() ? swa : full, 0); } - if (m_compute_params.cache_rs_reset_idx != -1 && m_model_params.n_rs_slots != 1) { + if (m_compute_params.cache_rs_reset_idx != -1) { // Whether/which cache slot to reset varies per compute call (e.g. a new sequence starting // vs. continued decoding). can_reuse_statically() does not invalidate the cached static // model on ComputeParams changes, so these must stay runtime Parameters even when static @@ -1513,7 +1511,10 @@ void GgmlOvDecoder::compute_model_outputs() { if (cur_node->op == GGML_OP_NONE || cur_node->op == GGML_OP_VIEW || cur_node->op == GGML_OP_RESHAPE) { continue; } - if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0) { + const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(cur_node->view_src) && + ::is_inplace_op(cur_node) && + (cur_node->op == GGML_OP_SCALE || !m_is_static); + if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0 && !runtime_recurrent_write) { continue; } if (cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) { @@ -1530,7 +1531,8 @@ void GgmlOvDecoder::compute_model_outputs() { auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; 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) && ggml_nbytes(cur_node) > 0) { + if (cur_node != nullptr && ::is_inplace_op(cur_node) && + (ggml_nbytes(cur_node) > 0 || runtime_recurrent_write)) { cur_node = cur_node->view_src; } } else { @@ -2175,7 +2177,12 @@ 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_inplace_op(node) || node->view_src == nullptr || ggml_nbytes(node) == 0) { + // 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) && + (node->op == GGML_OP_SCALE || !m_is_static); + if (!::is_inplace_op(node) || node->view_src == nullptr || + (ggml_nbytes(node) == 0 && !runtime_recurrent_write)) { return ""; } const int op_case = m_node_info_list[node_idx].node_op_case; diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp index 904d4911c28d..8a79c7c415f4 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -114,10 +114,9 @@ OutputVector translate_cpy(const NodeContext & context) { // runtime input, so the cached model works for any kv head and active sequence count. The // result is the full updated cache. // op_case 1: gated-delta-net state, op_case 2: conv state, op_case 3: defrag remainder. - if (op_case == 3) { - // With -np 1 (and generally whenever there is no defrag remainder) this GET_ROWS gathers - // zero rows: nothing to write back, and the cache is unchanged. NPU rejects zero-size - // tensors, so short-circuit instead of building a degenerate Slice/Concat chain. + if (op_case == 3 && context.is_static()) { + // A statically empty remainder leaves the cache unchanged at any slot capacity. + // NPU rejects zero-size tensors, so avoid a degenerate Slice/Concat chain. bool is_empty = false; if (input_shape.rank().is_static()) { for (const auto & d : input_shape) { @@ -131,24 +130,13 @@ OutputVector translate_cpy(const NodeContext & context) { return {context.get_input(1)}; } } - // op_case 7/8/9 are the single-slot variants; op_case 10 writes native GDN state into a - // multi-slot cache without rollback snapshots. - const bool single_slot_assign = op_case >= 7 && op_case <= 9; - const bool direct_gdn_state = op_case == 7 || op_case == 10; - int writeback_case = op_case; - if (op_case == 10) { - writeback_case = 1; - } else if (single_slot_assign) { - writeback_case = op_case - 6; - } + // op_case 10 consumes native GDN state without rollback snapshots. + const bool direct_gdn_state = op_case == 10; + const int writeback_case = direct_gdn_state ? 1 : op_case; const std::string slot_begin_name = "rs_slot_begin_" + context.get_name(); const bool slice_assign = writeback_case >= 1 && writeback_case <= 3 && - (single_slot_assign || context.has_input(slot_begin_name)); + context.has_input(slot_begin_name); if (slice_assign) { - if (single_slot_assign && writeback_case == 3) { - return {context.get_input(1)}; - } - const int64_t slot_axis = 2; auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0}); auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1}); @@ -158,15 +146,12 @@ OutputVector translate_cpy(const NodeContext & context) { std::vector{1, 1, -1, output_shape[3].get_length()}); ov::Output src; - ov::Output begin; - if (!single_slot_assign) { - begin = context.get_input(slot_begin_name); - } + auto begin = context.get_input(slot_begin_name); auto base = context.get_input(1); if (writeback_case == 1) { if (direct_gdn_state) { // Non-rollback GDN publishes state directly as [active_slots, heads, value_dim, - // key_dim]. Flatten each active slot before replacing or updating the cache. + // key_dim]. Flatten each active slot before updating the cache. src = std::make_shared(context.get_input(0), feature, false); } else { // Multi-slot rollback still consumes GGML's packed [attention | state snapshots] @@ -232,10 +217,6 @@ OutputVector translate_cpy(const NodeContext & context) { src = std::make_shared(src, context.get_output_type()); } - if (single_slot_assign) { - return rename_outputs_with_suffix({src}, 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})); @@ -253,16 +234,20 @@ OutputVector translate_cpy(const NodeContext & context) { } else { // op_case 3: gathered remainder rows already have the cache slot layout [1, 1, extra, feature] src = context.get_input(0); + if (context.get_view_input_size(0) > 0 && !context.is_static()) { + // build_rs gathers active and extra rows together. The remainder boundary moves + // with the active sequences, so do not capture the first batch's VIEW offset. + src = std::make_shared(src, + context.get_input("rs_src_begin_" + context.get_name()), int_max, one, axis); + } else { + src = process_view_input_new(context, 0); + } } if (src.get_element_type() != context.get_output_type()) { src = std::make_shared(src, context.get_output_type()); } - if (single_slot_assign) { - return rename_outputs_with_suffix({src}, 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})); diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index 200821d97489..9716ba38323b 100644 --- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp @@ -44,10 +44,6 @@ OutputVector translate_get_rows(const NodeContext & context) { } auto op_case = context.get_op_case(); - if (op_case == 3 || op_case == 4) { - return {data}; - } - ov::Output indices; if ((op_case == 1 || op_case == 2) && context.has_input("s_copy_active_slot_len")) { // Recurrent state reorder (inp->s_copy): slice the active (op_case 1) or extra (op_case 2) diff --git a/ggml/src/ggml-openvino/openvino/op/scale.cpp b/ggml/src/ggml-openvino/openvino/op/scale.cpp index 2947ee03c97c..1d5ef4ffa4ac 100644 --- a/ggml/src/ggml-openvino/openvino/op/scale.cpp +++ b/ggml/src/ggml-openvino/openvino/op/scale.cpp @@ -37,10 +37,6 @@ OutputVector translate_scale(const NodeContext & context) { auto scale_node = std::make_shared(ov::element::f32, ov::Shape{}, std::vector{scale}); - if (context.get_op_case() == 2) { - return {context.get_input(0)}; - } - if (context.get_op_case() == 1 && context.has_input("cache_rs_reset_len")) { auto cache_rs_reset_idx = context.get_input("cache_rs_reset_idx"); auto cache_rs_reset_len = context.get_input("cache_rs_reset_len"); diff --git a/ggml/src/ggml-openvino/openvino/op/view.cpp b/ggml/src/ggml-openvino/openvino/op/view.cpp index 70e191e2c86d..4ebe9c4b483a 100644 --- a/ggml/src/ggml-openvino/openvino/op/view.cpp +++ b/ggml/src/ggml-openvino/openvino/op/view.cpp @@ -25,6 +25,17 @@ OutputVector translate_view(const NodeContext & context) { return rename_outputs_with_suffix({std::make_shared(selected, shape, false)}, context.get_name()); } + if (context.get_op_case() == 4) { + auto input = context.get_input(0); + auto active = std::make_shared(input, + ov::op::v0::Constant::create(ov::element::i64, {1}, {0}), + context.get_input("s_copy_active_slot_len"), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {1}, + {input.get_partial_shape().rank().get_length() - 2})); + return rename_outputs_with_suffix({active}, context.get_name()); + } + if (context.get_op_case() == 1) { // Static-mode identity pass-through for VIEWs over a GATED_DELTA_NET combined output or // the conv_input CONCAT; the consuming op (CPY/RMS_NORM) does its own runtime-correct diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index b3efddf0a86d..2d76e56164f8 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -114,7 +114,7 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : ggml_openvino_is_gpu(); - uint64_t extra_cfg = 1; // Graph-ordinal port names (invalidate older disk-cache blobs). + uint64_t extra_cfg = 2; // Generic recurrent reset/reorder/writeback (invalidate older disk-cache blobs). extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_SLICE") ? 1u : 0u); @@ -358,27 +358,6 @@ static void dump_ov_profiling_info(const ov::InferRequest & infer_request) { executed_count, total_real_time / 1000.0, total_cpu_time / 1000.0); } -static void reset_single_slot_recurrent_cache(ggml_cgraph * cgraph, - const ModelParams & model_params, - const ComputeParams & compute_params) { - if (model_params.n_rs_slots != 1 || compute_params.cache_rs_reset_len == 0) { - return; - } - GGML_ASSERT(compute_params.cache_rs_reset_idx == 0 && compute_params.cache_rs_reset_len == 1); - - std::set buffers; - for (int i = 0; i < cgraph->n_nodes; i++) { - auto * node = cgraph->nodes[i]; - if (node->op == GGML_OP_SCALE && GgmlOvDecoder::is_recurrent_cache(node->view_src) && - node->view_src->ne[1] == 1 && node->view_src->buffer != nullptr) { - buffers.insert(node->view_src->buffer); - } - } - for (auto * buffer : buffers) { - ggml_backend_buffer_clear(buffer, 0); - } -} - ov::Tensor create_ov_output_tensor(const std::shared_ptr & ggml_decoder, const std::shared_ptr & infer_request, int output_index, @@ -1325,8 +1304,6 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share "or disable GGML_OPENVINO_STATEFUL_EXECUTION.\n"); return GGML_STATUS_FAILED; } - } else { - reset_single_slot_recurrent_cache(cgraph, m_params, c_params); } for (size_t i = 0; i < ov_input_names.size(); i++) { @@ -1647,8 +1624,6 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } } - reset_single_slot_recurrent_cache(cgraph, m_params, c_params); - if (is_prefill) { auto inp_len = get_inp_pos_n_tokens(cgraph, inp_pos); for (int chunk_index = 0; chunk_index * prefill_chunk_size < inp_len; chunk_index++) { diff --git a/tests/test-backend-sampler.cpp b/tests/test-backend-sampler.cpp index d5098b3ce8e2..c6fdaf1ffab1 100644 --- a/tests/test-backend-sampler.cpp +++ b/tests/test-backend-sampler.cpp @@ -1177,6 +1177,77 @@ static void test_backend_top_k_hidden_rollback(const test_params & params) { test_backend_top_k_rows_impl(params, 2, true); } +// Compare slot transitions against a fresh, independently replayed sequence. This catches +// resets of the wrong cache row and writes that clobber inactive or copied sequences. +static void test_backend_recurrent_slots(const test_params & params) { + std::vector configs; + test_context reference(params, configs, 1, 1, 64); + for (uint32_t rollback : {0u, 2u}) { + test_context ctx(params, configs, 4, 12, 16, 3, rollback); + std::vector> history(4); + int next_token = 100; + auto run = [&](std::vector counts) { + common_batch batch(ctx.ctx.get()); + std::vector rows(4, -1); + for (int seq = 0; seq < 4; ++seq) { + for (int i = 0; i < counts[seq]; ++i) { + const llama_token token = next_token++ % ctx.n_vocab; + batch.add(token, history[seq].size(), seq, i + 1 == counts[seq]); + history[seq].push_back(token); + rows[seq] = batch.size() - 1; + } + } + GGML_ASSERT(llama_process(ctx.ctx.get(), LLAMA_PROCESS_TYPE_DECODE, batch.get()) == 0); + for (int seq = 0; seq < 4; ++seq) { + if (rows[seq] < 0) { + continue; + } + llama_memory_clear(llama_get_memory(reference.ctx.get()), true); + common_batch replay(reference.ctx.get()); + for (size_t i = 0; i < history[seq].size(); ++i) { + replay.add(history[seq][i], i, 0, i + 1 == history[seq].size()); + } + GGML_ASSERT(llama_process(reference.ctx.get(), LLAMA_PROCESS_TYPE_DECODE, replay.get()) == 0); + const float * actual = llama_get_logits_ith(ctx.ctx.get(), rows[seq]); + const float * expected = llama_get_logits_ith(reference.ctx.get(), replay.size() - 1); + GGML_ASSERT(actual && expected); + double error = 0.0, norm = 0.0; + for (int j = 0; j < ctx.n_vocab; ++j) { + GGML_ASSERT(std::isfinite(actual[j]) && std::isfinite(expected[j])); + const double diff = double(actual[j]) - expected[j]; + error += diff * diff; + norm += double(expected[j]) * expected[j]; + } + const double relative_error = std::sqrt(error / std::max(norm, 1e-12)); + printf("recurrent_slots rollback=%u seq=%d tokens=%zu relative_error=%.6f\n", + rollback, seq, history[seq].size(), relative_error); + GGML_ASSERT(relative_error < 1e-2); + } + }; + auto memory = llama_get_memory(ctx.ctx.get()); + run({3, 3, 3, 3}); + run({0, 0, 1, 0}); + GGML_ASSERT(llama_memory_seq_rm(memory, 1, 0, -1)); + history[1].clear(); + run({0, 2, 0, 0}); + run({3, 1, 1, 3}); + if (rollback) { + for (int seq : {0, 3}) { + const int reject = seq == 0 ? 2 : 1; + history[seq].resize(history[seq].size() - reject); + GGML_ASSERT(llama_memory_seq_rm(memory, seq, history[seq].size(), -1)); + } + } + run({1, 1, 1, 1}); + GGML_ASSERT(llama_memory_seq_rm(memory, 1, 0, -1)); + llama_memory_seq_cp(memory, 2, 1, 0, -1); + history[1] = history[2]; + run({0, 2, 1, 0}); + run({1, 1, 1, 1}); + } + printf("backend recurrent slot reset/copy/rollback test PASSED\n"); +} + static float find_backend_logit(const backend_sampler_output & output, llama_token token) { for (size_t i = 0; i < output.candidates.size(); ++i) { if (output.candidates[i] == token) { @@ -2124,6 +2195,7 @@ static const backend_test_case BACKEND_TESTS[] = { { "top_k_rows", test_backend_top_k_rows, true }, { "top_k_rollback", test_backend_top_k_rows_rollback, false }, { "top_k_hidden_rollback", test_backend_top_k_hidden_rollback, false }, + { "recurrent_slots", test_backend_recurrent_slots, false }, { "multi_sequence", test_backend_multi_sequence_sampling, true }, { "dist", test_backend_dist_sampling, true }, { "dist_and_cpu", test_backend_dist_sampling_and_cpu, true }, From 2a978aa9be483c2467b586b7134e38562b17aacd Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 16 Oct 2026 11:10:23 +0200 Subject: [PATCH 23/65] openvino: fuse generic recurrent caches and remove shape waits Translate recurrent reset, reorder and writeback through native GPU cache kernels. Derive active dimensions from row-map shapes, reuse USM host controls and fold GDN state layouts into gather/update. Keep primitive fallbacks, update cache compatibility, move development reports into dev_doc and record Qwen3.6 UD-Q4_K_M as the new target. Validated clean build, recurrent regressions, native tests and four-slot serving with and without MTP. Requires native OpenVINO commit 9e08e52ad5 for the optimized GPU path. --- ggml/src/ggml-openvino/CMakeLists.txt | 27 +++ ggml/src/ggml-openvino/README.md | 4 +- .../dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md | 189 ++++++++++++++++ .../OPENVINO-QWEN35-08B-PERF-RESULTS.md | 190 ++++++++++++++++ .../dev_doc}/OPENVINO-RECURRENT-CACHE.md | 73 ++++++- ggml/src/ggml-openvino/ggml-decoder.cpp | 73 +++++++ ggml/src/ggml-openvino/ggml-decoder.h | 10 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 1 + ggml/src/ggml-openvino/openvino/op/cpy.cpp | 73 ++++++- .../openvino/op/gated_delta_net.cpp | 67 ++++-- .../openvino/op/recurrent_cache.hpp | 72 +++++++ .../openvino/recurrent_cache_fusion.cpp | 203 ++++++++++++++++++ .../openvino/recurrent_cache_fusion.h | 24 +++ .../openvino/translate_session.cpp | 14 +- ggml/src/ggml-openvino/utils.cpp | 53 ++++- 15 files changed, 1043 insertions(+), 30 deletions(-) create mode 100644 ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md create mode 100644 ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md rename {docs/backend => ggml/src/ggml-openvino/dev_doc}/OPENVINO-RECURRENT-CACHE.md (59%) create mode 100644 ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp create mode 100644 ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp create mode 100644 ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index 347c24f4f526..845b7c0740da 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -31,3 +31,30 @@ if (GGML_OPENVINO) message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}") endif() endif() + +# Keep released runtimes working through the existing primitive translations. +include(CheckCXXSourceCompiles) +unset(GGML_OPENVINO_HAS_RECURRENT_CACHE CACHE) +set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) +set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op") +check_cxx_source_compiles("#include +int main() { auto gather = std::make_shared(ov::OutputVector{}); + auto conv = std::make_shared(ov::OutputVector{}, 3); }" + GGML_OPENVINO_HAS_RECURRENT_CACHE) +unset(CMAKE_REQUIRED_LIBRARIES) +unset(CMAKE_REQUIRED_INCLUDES) +if(GGML_OPENVINO_HAS_RECURRENT_CACHE) + target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_RECURRENT_CACHE=1) +endif() + +unset(GGML_OPENVINO_HAS_STATE_UPDATE CACHE) +set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) +set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op") +check_cxx_source_compiles("#include +int main() { auto update = std::make_shared(ov::OutputVector{}); }" + GGML_OPENVINO_HAS_STATE_UPDATE) +unset(CMAKE_REQUIRED_LIBRARIES) +unset(CMAKE_REQUIRED_INCLUDES) +if(GGML_OPENVINO_HAS_STATE_UPDATE) + target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_STATE_UPDATE=1) +endif() diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 2a62ede7d5bf..3d26c68d63ae 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -6,7 +6,9 @@ Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP w Stateless recurrent execution uses the same reset, reorder, and partial cache-writeback paths at every slot capacity, including one slot without MTP. `test-backend-sampler --test recurrent_slots` compares four-slot reset, copy, inactive-slot preservation, and rollback against independently replayed sequences. -See the [recurrent-cache report](../../../docs/backend/OPENVINO-RECURRENT-CACHE.md) for the measured baseline and proposed native cache-operation fusions. +The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all`, `GGML_OPENVINO_NATIVE_SOFTPLUS=1`, and `GGML_OPENVINO_DISABLE_KV_SLICE=1`. See the [performance report](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) for measurements; the earlier yamini-model results remain historical references. + +See the [recurrent-cache report](dev_doc/OPENVINO-RECURRENT-CACHE.md) for the measured baseline and proposed native cache-operation fusions. # Compiled model cache diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md new file mode 100644 index 000000000000..477b0d7110ca --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md @@ -0,0 +1,189 @@ +# Qwen3.5 0.8B F16: OpenVINO GPU investigation and optimization plan + +Date: 2026-10-16. This document records the original investigation and plan. Steps 1–3 are now implemented locally; measurements and validation are recorded in [OPENVINO-QWEN35-08B-PERF-RESULTS.md](OPENVINO-QWEN35-08B-PERF-RESULTS.md). The baseline findings below describe the pre-optimization implementation. The current target has since changed to `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, keeping GPU, `q4_asym64_all`, native softplus, and disabled KV slicing; the results report records its retest separately. + +OpenVINO GPU currently reaches **43.5–43.8 tokens/s**, compared with **57.91 tokens/s** for a new Vulkan Release build from the same working tree. The next priority is eliminating runtime shape synchronization: an ordinary single-token inference calls `clFinish` **164 times**, of which **163 are shape-inference synchronizations: 108 Reshapes and 55 Slices**. Cache allocations and bindings already use device USM. Native cache fusion helps, but leaves this synchronization problem and matrix-state writeback/layout work intact. + +The user's 18.99 tokens/s OpenVINO example selected **CPU**, so it is not the GPU baseline. The user's expectation of further improvement is reasonable; reaching a particular throughput on the 35B model still needs measurement after the small-model changes. + +## Reproducible baseline + +Hardware: Intel Arc B390 integrated GPU / Core Ultra X7 358H. Model: `~/models/Qwen3.5-0.8B-GGUF/Qwen3.5-0.8B-F16.gguf`. This dense, unquantized model removes MoE and requantization from the comparison. + +- OpenVINO frontend: Release `build/MtpOVPerf`, llama.cpp HEAD `73f61e1cb`, with the existing uncommitted native recurrent-cache implementation. +- Runtime: `/home/zijun/openvino-build-mtp`, OpenVINO HEAD `21cacac33d`, with the existing native-op changes. +- Matched Vulkan: new Release `build/VulkanPerf08`, same current llama.cpp working tree, Vulkan SDK 1.4.357.1. The existing Debug `build/vulkan` was left unchanged. +- GPU workloads ran serially. No stateful tests or execution. No backend implementation files changed during this investigation. +- Environment is scrubbed of inherited OpenVINO/Vulkan controls before each run. Requantization and compiled-model disk caching are unset. Throughput excludes initial loading/compilation through llama-bench's warmup. + +```sh +GGML_OPENVINO_DEVICE=GPU \ +GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ +GGML_OPENVINO_DISABLE_KV_SLICE=1 \ +build/MtpOVPerf/bin/llama-bench \ + -m "$HOME/models/Qwen3.5-0.8B-GGUF/Qwen3.5-0.8B-F16.gguf" \ + -p 0 -n 128 -r 3 +``` + +| Run | tokens/s, benchmark mean ± SD | Approx. ms/token | +| --- | ---: | ---: | +| OV GPU, native cache ops | 43.76 ± 0.10 | 22.85 | +| OV GPU, independent repeat | 43.51 ± 0.11 | 22.98 | +| OV GPU, `GGML_OPENVINO_DISABLE_RECURRENT_CACHE=1` | 39.14 ± 0.12 | 25.55 | +| OV GPU, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS=1` | 43.26 ± 0.11 | 23.12 | +| Existing Vulkan Debug, older build | 55.69 ± 0.25 | 17.96 | +| Matched Vulkan Release | 57.91 ± 0.17 | 17.27 | + +Native fusion saves approximately **2.70 ms/token**, or 11.8% higher throughput, on this model. Approximately **5.6–5.7 ms/token** remains to match Vulkan Release. Disabling remote outputs changes latency by only about 0.26 ms relative to the first native run; this is a small, order-sensitive control, not a complete measurement of memory-copy cost. + +Timing instrumentation is separate from these baselines. One profiling-level-1 run measured 41.24 tokens/s; a later verbose level-1 run measured 43.57. Its warmed medians were 0.100 ms for graph decoding, 22.637 ms for the inference phase including bindings, and 22.193 ms inside `InferRequest::infer`. Most latency is inside the runtime, rather than llama.cpp graph construction or tensor binding. Do not use the noisier instrumented result as a new baseline. + +## Controlled token-count and snapshot comparison + +The existing `tmp/mtp-gap-20261014/batch-bench.cpp` harness was reused, including a newly linked Vulkan Release executable. Each case uses a 128-token prefix, eight warmups, 16 measured calls, context 4096, one active sequence, hidden output enabled, and all input rows requesting logits. Means below are milliseconds per complete synchronized decode call. + +| Case | OV GPU | Vulkan Release | +| --- | ---: | ---: | +| 1 token, snapshots disabled | 23.49 | 17.07 | +| 3 tokens, snapshots disabled | 24.44 | 18.40 | +| 1 token, two rollback positions configured | 29.84 | 17.85 | +| 3 tokens, two rollback positions configured | 31.82 | 19.32 | +| 3 tokens, reject two after each call | 32.01 | 18.59 | + +On OV, ordinary T1→T3 adds only **0.95 ms**. Enabling snapshot storage adds **7.38 ms** to T3. Actual rejection adds approximately **0.19 ms** in this run. The slightly lower Vulkan reject-case timing is not evidence that rejection accelerates inference; the cases advance context length differently and are separate short measurements. + +This isolates a substantial generic/snapshot-path penalty without any MoE or quantization. These are target-call measurements, not an MTP throughput prediction: draft generation, catch-up, acceptance, and host sampling must be measured separately on the target model. + +## What the runtime actually does + +### USM and model I/O + +A scratch `LD_PRELOAD` probe inspects bound tensors and intercepts OpenCL submissions and USM copies. A warmed native T1 call has: + +| Item | Count / size | +| --- | ---: | +| OV Parameters | 184 | +| OV Results | 51 | +| Cache inputs, all USM | 48 | +| Cache outputs, all USM | 48 | +| Host inputs | 136, mostly scalar metadata | +| Cache-r allocation represented at I/O | 18 × 73,728 bytes | +| Cache-s allocation represented at I/O | 18 × 1,048,576 bytes | +| Cache-k/cache-v allocation represented at I/O | 12 × 262,144 bytes | +| Host→device USM copies per inference | 136 calls, **1,588 bytes total** | +| USM-host→ordinary-host output copies | 3 calls, **1,001,472 bytes total** | +| OpenCL NDRange submissions | **789** | +| `clFinish` calls | **164** | + +The three host outputs are logits (993,280 bytes), `h_nextn` (4,096 bytes), and `result_norm` (4,096 bytes). The cache byte counts are bound capacities, not host-transfer volumes. No full recurrent-cache host round trip appears in the intercepted copies. Device kernels still read, convert, transpose, and write cache data. + +Code confirms the binding behavior: `ggml-openvino.cpp` allocates GPU `cache_*` buffers with `create_usm_device_tensor`; `ggml-openvino-extra.cpp` wraps their pointers as USMTensors; `utils.cpp` reuses them for both inputs and outputs. There is already **one final Result per cache per layer**. Reducing duplicate cache Results is therefore not the immediate opportunity. + +The small host inputs are different: `get_ov_input_tensor()` allocates a fresh tensor for each extra scalar on every invocation. The runtime uploads them individually. Per-layer `rs_slot_begin_*` and `rs_src_begin_*` parameters are combined into small device-side Concat/Reshape expressions even for the native cache ops. + +### Synchronization and shape inference + +The probe measures roughly **12.9–13.3 ms spent inside `clFinish`** per warmed call, with raw inference around 22.4 ms. This includes completion of useful GPU work; it is **not** 13 ms of independently removable overhead. + +An additional GPU verbose trace (`OV_VERBOSE=4`, `OV_VERBOSE_COLOR=0`) confirms three consecutive calls each contain exactly: + +- **108 Reshape shape-inference synchronizations**, six per recurrent layer: QKV mixed, alpha, beta, gate, z, and final-output reshapes. +- **55 StridedSlice shape-inference synchronizations**. +- The remaining finish is inference completion; the probe records a separate final event wait as well. + +`primitive_inst::update_shape()` waits for runtime value dependencies before calculating output layouts. The in-order shared OpenCL queue takes the `finish()` path. In `openvino/op/reshape.cpp`, cases 6 and 10 build shape vectors using **the tensor value** of `s_copy_active_slot_len`. This introduces synchronization even though the active sequence count is already known by the frontend on every call. `recurrent_cache_fusion.cpp` also slices the row map using that value; other active-state views and cache writeback slices retain similar dependencies. + +This explains why fusing many GGML nodes does not eliminate the gap: arithmetic fusion does not automatically remove the surrounding shape computations or their queue drains. Removing waits blindly would be incorrect; their data dependencies must first be eliminated or satisfied safely. + +### Device execution profile + +Level-2 profiling substantially changes synchronization/timing (the short OV run reports only 17.34 tokens/s). Use it to locate kernels, not as an end-to-end benchmark. A warmed native profile has 1,180 entries marked EXECUTED, versus 1,777 with native cache fusion disabled. These entries include CPU/shape nodes and are not equivalent to kernel dispatches. + +| Profiled work | Native OV device-time sum | +| --- | ---: | +| FullyConnected, 187 nodes | 14.697 ms | +| Transpose, 48 nodes | 1.032 ms | +| Convert, 180 entries | 0.377 ms | +| GatedDeltaNet, 18 | 0.274 ms | +| RecurrentStateGather, 18 | 0.246 ms | +| RecurrentConvCache, 18 | approximately 0.073 ms | +| All recorded executed entries | 17.837 ms | + +The matched Vulkan instrumented profile sums to 17.858 ms, including approximately 15.573 ms of matmul work. The huge F16 vocabulary projection alone is approximately 4.45 ms in OV and 4.41 ms in Vulkan. Different profilers change scheduling, so these sums cannot be subtracted from plain wall time to calculate an exact overhead budget. They do suggest that dense matrix computation is not the first issue to address. + +The matrix-state path still materializes gather output, transposes between GGML `[B,H,V,K]` and native GDN `[B,H,K,V]`, transposes results back, and assembles cache writeback. Snapshot routing adds more state-selection/writeback work. The current `RecurrentStateGather` also produces a complete prepared-cache copy before the final update. These are more promising fusion targets than micro-tuning the already small convolution-cache kernel. + +## Implementation plan, in order + +### 1. Remove active-count value dependencies from shapes + +**Files:** `ggml-decoder.{h,cpp}`, `utils.cpp`, `openvino/op/reshape.cpp`, `openvino/op/view.cpp`, `openvino/utils.cpp`, `openvino/recurrent_cache_fusion.cpp`. + +1. Expose a runtime active-row-map input whose **shape** is `[1,1,1,B]`, where B comes from the actual active recurrent-state view each compute. Bind the corresponding prefix of `rs_s_copy`; retain the full map separately for remainder reordering. Do not assume B=1 or equate B with configured slot capacity, total tokens, or snapshot count. +2. Derive `s_copy_active_slot_len` for shape expressions from `ShapeOf(active_rows)` through the existing shape-source mechanism. Use constant reshape patterns with `-1`/copied dimensions wherever that expresses the same shape. This targets all 108 recurrent reshape waits while preserving changing B and T. +3. Feed the native cache ops the already-shaped active map, removing their value-dependent prefix Slice. Remove redundant active-prefix slices only when the producer structurally guarantees that exact active output, for every supported B/T. +4. Inspect the executed graph to ensure the new expressions remain shape-only through GPU lowering. A frontend ShapeOf is insufficient if the plugin still makes the dependency value-driven. + +**Gate:** changing-slot/rollback correctness tests pass; the 108 identified reshape waits disappear or any surviving dependency is individually explained. Repeat uninstrumented tg128. The first performance target is **at least 50 tokens/s** (≤20 ms/token), not a promised gain. + +### 2. Pack and reuse recurrent control inputs + +**Files:** decoder runtime-parameter collection and binding, `recurrent_cache_fusion.cpp`, native op metadata interfaces if needed. + +1. Materialize reset range, remainder offsets, and convolution snapshot windows on the host into persistent, correctly shaped metadata tensors. Feed native ops directly instead of building their metadata with GPU Concats/Reshapes. +2. Share metadata across layers only when graph structure and runtime provenance guarantee equality. Never deduplicate merely because values match in the first batch. Keep per-node descriptors for genuinely different writes. +3. Use reusable USM-host storage for small host-produced controls where supported; measure against one packed device upload. Keep caches in device USM. Avoid moving shape metadata to device-only storage and forcing a readback for shape inference. +4. Reuse bindings when tensor identity, address, type, and shape are unchanged. Rebind after allocation/view/shape changes. Increment the compiled-model cache ABI/revision for any input-interface change. + +**Gate:** reduce the current 136 tiny uploads to a small number of packed controls, verify no stale metadata across reset/reorder/rejection, and record input count, upload count, and uninstrumented latency. Binding alone has only about a 0.44 ms observed budget; a larger gain must come from removing device metadata work/synchronization. + +### 3. Fuse matrix-state writeback and eliminate state-layout traffic + +**Files:** `openvino/op/cpy.cpp`, `openvino/op/gated_delta_net.cpp`, native recurrent-cache/GDN core ops, GPU primitive and kernel implementations. + +1. Add a generic native **RecurrentStateUpdate** operation, or extend the current cache operation, to combine the prepared full cache with active final states/snapshots in one kernel. Output shape equals cache shape; runtime offsets and snapshot selections affect indexing, not shape inference. Preserve inactive slots, reset-before-gather semantics, cyclic/duplicate sources, and ordered overlapping-write precedence. +2. Accept GDN's native state layout in the update kernel and transpose while writing GGML cache layout. Fold active-state gather and input-layout conversion together where possible. This avoids standalone full-state transpose intermediates and Slice/Concat/Range writeback chains. +3. If profiling still justifies it, extend GDN to consume the original cache plus active-row/reset metadata and emit active results/snapshots directly in cache-compatible layout. A complete fused gather→GDN→writeback path can avoid the prepared-cache intermediate. Keep old source storage immutable until all potentially aliasing reads finish; arbitrary multi-slot cycles forbid naive in-place writes. +4. Preserve the existing external cache precision and numerical contract. Do not trade throughput for a silent F32→F16 cache change. Compare native-on/off logits and replay behavior after fusion. + +**Gate:** remove the identified state writeback shape waits and standalone state transposes; reduce T3 snapshot overhead substantially from **7.38 ms toward ≤2 ms** on 0.8B. This is a target, subject to measurement. Retain all multislot/snapshot regressions and compiled-model export/import coverage. + +### 4. Optimize remaining dispatches based on a fresh profile + +Only after steps 1–3, reassess kernel submission and dense compute: + +- Consider fusing `RecurrentConvCache` with SSM convolution and SiLU, avoiding materialized history-plus-QKV and extra launches. Its current cache kernel is only ~0.073 ms aggregate; prioritize measured dispatch/synchronization savings, not an assumed large bandwidth saving. +- Remove unused `h_nextn`/`result_norm` host Results when the caller does not request them, while retaining the exact MTP/embedding/sampling contract. They are only 8 KiB here, so this is a secondary I/O cleanup. +- Compare remaining FP16 projection/gating kernels with Vulkan. Preserve accuracy and multi-token performance when adjusting fusions or kernel selection. +- If translated shape-only expressions still wait unnecessarily, make a narrowly justified GPU-plugin shape-dependency fix. Do not globally bypass `finish()` or change queue ordering without dependency correctness tests. + +**Gate:** aim for **≥55 tokens/s** on 0.8B, within roughly 5% of the current 57.91 t/s Vulkan Release reference. Report gains and counter changes separately for each retained patch. + +### 5. Validate generality, then measure the target model + +For every functional patch, exercise the existing recurrent-slots and hidden/rollback regressions with active subsets, nonzero-slot resets, copies/branches, inactive-state preservation, unequal rejection lengths, zero requested outputs, and changing B/T on a reused graph. For native-op changes, extend the existing f16/f32, i32/i64, dynamic/static, cycle/overlap, and export/import tests. Statefulness remains out of scope. + +After the small-model improvements: + +1. Run 0.8B `llama-server -np 4` reset/reuse/concurrent waves and a longer-context `-p 1024 -n 512 -d 0,1024` performance check. +2. Rebuild/reuse compiled caches with the new revision. For functional tests, unset requantization when supported; the previously observed 35B no-requant fusion failure may still require the target requant config. +3. Run the target Qwen3.6-35B-A3B with `q4_asym64_all`, GPU, native softplus, and KV slicing disabled. Repeat `-np 4` server checks without and with two-token MTP. +4. Repeat the established target bench, controlled T1/T3/snapshot matrix, and matched CLI/MTP traces. Report draft, catch-up, verification, acceptance, and complete generation throughput. +5. Compare against the current generic/native target baselines: **23.05 t/s non-MTP tg512**, **22.32 at depth 1024**, and **27.93 t/s MTP on the prior greeting workload**. The user's **≥30 t/s** goal is a target; small-model gains cannot simply be multiplied into the 35B result. + +Keep useful patches independently reviewable across llama.cpp and OpenVINO, with measured results and relevant files only. The existing native implementation remains uncommitted; this investigation does not create additional implementation commits. + +## Evidence and limitations + +All commands, environments, logs, profiles, and the scratch probe are under [`tmp/qwen08-perf-plan-20261016`](../../../../tmp/qwen08-perf-plan-20261016/). Useful entry points: + +- `run.py`, per-run `command.json`, and `summary.json`. +- `ov-native`, `ov-native-repeat`, `ov-unfused`, `ov-host-outputs`, `vulkan-release`: plain benchmark evidence. +- `ov-matrix`, `vulkan-matrix`: controlled target calls; `batch-vulkan` is linked to the new Release build. +- `ov-profile`, `ov-profile-unfused`, `vulkan-profile`: instrumented operation profiles. +- `probe.cpp`, `ov-probe/probe-1-io.tsv`, `ov-probe/probe-1-exec.xml`, and `ov-probe/run.log`: actual bindings, runtime graph, OpenCL call/copy counts. +- `ov-sync-trace/run.log`: `primitive_inst.cpp:481:update_shape` records proving the 108 Reshape + 55 Slice waits per inference. Do not benchmark with this verbose tracing enabled. + +The probe is investigative tooling, not production code. It counts intercepted NDRange calls and Intel USM memcpy calls, not every possible driver-internal transfer. An initial debug-input attempt failed because that helper calls `Tensor::data()` on a remote tensor; the final probe inspects remote handles safely. Early probe build/instrumentation attempts were corrected; reported probe results come from the final successful run. + +No new model-correctness claim is made from throughput tests alone. The prior native implementation's functional coverage is documented in [OPENVINO-RECURRENT-CACHE.md](OPENVINO-RECURRENT-CACHE.md); the planned changes must repeat the relevant coverage. No 35B performance rerun was performed in this investigation-only round. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md new file mode 100644 index 000000000000..e809f3a0b02e --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md @@ -0,0 +1,190 @@ +# Qwen recurrent-cache optimization results + +Date: 2026-10-16. Implementation was measured from the local changes in llama.cpp (`qwen-openvino-generic-cache`, HEAD `73f61e1cb`) and `/home/zijun/openvino` (`qwen-mtp-openvino-checkpoint`, HEAD `21cacac33d`). The matching native OpenVINO changes are committed as `9e08e52ad5` (`intel_gpu: fuse generic recurrent cache maintenance`). Builds use Release `build/MtpOVPerf` and `/home/zijun/openvino-build-mtp`. Unrelated working-tree changes were preserved. Results below exclude load/requantization/graph compilation from generation throughput. No stateful execution is involved. + + +From this retest onward, the target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`. GPU, `q4_asym64_all`, native softplus, and disabled KV slicing remain unchanged. The yamini-model tables below retain their original model identity; new measurements are reported separately. +## Implemented changes + +1. Added an active recurrent-row-map prefix input with dynamic length. Active sequence counts now come from its runtime shape instead of an uploaded scalar value. This preserves changing slot counts and removes all 108 recurrent Reshape shape-inference waits in the 0.8B graph. +2. Reuse per-request runtime control tensors in USM host allocations. This removes almost all tiny scalar uploads while keeping shape metadata CPU-readable. Ordinary cache buffers remain in device USM, as before. +3. Materialize convolution windows and remainder offsets as packed host controls. Metadata varies per actual graph write; it is not deduplicated by coincidentally equal first-batch values. +4. Added native `RecurrentStateUpdate`: a full-cache output with runtime active/snapshot offsets and ordered overlap handling. It replaces Slice/Concat/Range state writeback, removing the remaining 36 ordinary-decode shape-inference waits. +5. StateUpdate converts native GDN state/snapshot matrices to GGML cache layout while writing. RecurrentStateGather converts gathered matrices into native GDN layout while reading. Standalone recurrent input/output state transposes are eliminated on the structurally matched path. Original source cache reads remain immutable, including arbitrary row-map cycles and duplicates. +6. Added native-op capability probing and updated the compiled-model cache revision. Dynamic CPU, static, and released-runtime paths retain their primitive translations. Existing disk-cache blobs need regeneration. + +## 0.8B F16 results + +The same small-model command and matched Vulkan Release reference as the [investigation](OPENVINO-QWEN35-08B-PERF-PLAN.md) are used: `llama-bench -p 0 -n 128 -r 3`, GPU, native softplus, KV slicing disabled, requant unset. Changes were measured incrementally; small differences between adjacent runs are subject to run order and machine variability. + +| Stage | Generation tokens/s | +| --- | ---: | +| Initial native cache implementation | 43.76 ± 0.10 | +| Active count from row-map shape | 46.82 ± 0.05 | +| Reusable USM host scalar controls | 50.23 ± 0.07 | +| Native full-cache state update | 51.15 ± 0.15 | +| Output state transpose folded into update | 52.60 ± 0.07 | +| Packed window/remainder metadata | 52.50 ± 0.07 | +| Input state transpose folded into gather | 53.75 ± 0.08 | +| Final independent optimized repeat | **56.21 ± 0.06** | +| Matched Vulkan Release reference | 57.91 ± 0.17 | + +The final independent repeat reaches **56.21 ± 0.06 tokens/s**, **28.4%** above the initial native path and **2.9%** below Vulkan Release. An earlier final-build repeat measured 55.51 ± 0.17 tokens/s. Both meet the ≥55 tokens/s small-model target. The independent repeat ran after the target MTP process exited, with no overlapping GPU workload. + +A longer three-repeat check (`-p 1024 -n 512 -d 0,1024`) records: + +| 0.8B workload | Optimized tokens/s | +| --- | ---: | +| pp1024 | 6781.63 ± 418.28 | +| tg512 | **55.46 ± 0.07** | +| pp1024 at depth 1024 | 5330.30 ± 1286.93 | +| tg512 at depth 1024 | **53.04 ± 0.18** | + +Prefill has high variance in this short run; the decode measurements are more stable. No matched Vulkan longer-context baseline was rerun. + +The intercepted warmed ordinary-decode work changes as follows: + +| Counter | Initial native | Optimized | +| --- | ---: | ---: | +| Model Parameters | 184 | 130 | +| Model Results | 51 | 51 | +| Remote USM cache inputs/outputs | 48 / 48 | 48 / 48 | +| Tiny host→device copies | 136, 1588 bytes | 8, 560 bytes | +| Host output copies | 3, 1001472 bytes | 3, 1001472 bytes | +| `clFinish` calls | 164 | 1 | +| Kernel submissions | 789 | 606 | +| Profile entries marked EXECUTED | 1180 | 945 | + +The sole remaining finish is inference completion. The prior 163 queue drains were 108 Reshapes and 55 Slices; deriving shapes and native writeback removes them instead of bypassing synchronization. Profiling-level-2 device times are diagnostic only: the optimized trace records 16.982 ms total, of which 14.835 ms (87.4%) is FullyConnected. Profiling changes scheduling and is not the throughput baseline. + +The existing controlled target-call harness uses a 128-token prefix, 8 warmups, 16 measured calls, hidden states enabled, and all rows requesting logits: + +| Case | Initial OV ms/call | Optimized OV ms/call | Vulkan reference ms/call | +| --- | ---: | ---: | ---: | +| T1, no snapshots | 23.49 | 19.15 | 17.07 | +| T3, no snapshots | 24.44 | 19.93 | 18.40 | +| T1, rollback storage enabled | 29.84 | 22.28 | 17.85 | +| T3, rollback storage enabled | 31.82 | 24.46 | 19.32 | +| T3, reject two | 32.01 | 24.59 | 18.59 | + +Snapshot storage still adds about 4.53 ms to the optimized T3 call, compared with 7.38 ms initially. The ≤2 ms snapshot-overhead target is not met. Rejection itself remains small. Single-token throughput and snapshot verification are different performance cases. + +## Current target: Qwen3.6 UD-Q4_K_M retest + +Model: `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf` (22,663,387,424 bytes; 21.10 GiB). Same architecture metadata and one `nextn_predict_layers` MTP layer as the previous GGUF. The build and runtime are unchanged from the optimized measurements above. GPU workloads run serially; compiled-model disk caching and stateful execution are unset. + +```sh +GGML_OPENVINO_DEVICE=GPU \ +GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ +GGML_OPENVINO_DISABLE_KV_SLICE=1 \ +GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ +build/MtpOVPerf/bin/llama-bench \ + -m "$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" \ + -p 1024 -n 512 -d 0,1024 +``` + +Five repetitions; mean ± benchmark standard deviation: + +| Workload | Previous optimized yamini tokens/s | Current UD tokens/s | +| --- | ---: | ---: | +| pp1024 | 1125.19 ± 8.25 | **1127.99 ± 7.25** | +| tg512 | 29.91 ± 0.47 | **27.41 ± 0.07** | +| pp1024 at depth 1024 | 1074.27 ± 33.48 | **1081.64 ± 19.96** | +| tg512 at depth 1024 | 28.47 ± 0.44 | **26.19 ± 0.04** | + +UD decode is 8.4% lower at depth zero and 8.0% lower at depth 1024. This compares different GGUF quantizations under the same optimized backend; it is not a before/after optimization measurement on UD. No pre-optimization or Vulkan UD baseline has been measured. + +The quantization mix differs substantially: non-expert/non-MTP weights change from 95 Q6_K, 53 Q4_K, 94 Q8_0 and 10 Q5_K tensors to 1 Q6_K and 251 Q8_0 tensors. Those weights grow from 1.87 GB to 2.56 GB. Trunk MoE expert weights change from 20 Q6_K/100 Q4_K to 3 Q6_K/80 Q4_K/37 Q5_K. The full MTP block changes from 11 Q8_0/7 F32/2 BF16 (898 MB) to 8 Q8_0/7 F32/2 BF16/1 Q5_K/2 Q4_K (529 MB): its three expert tensors changed from Q8_0 to K-quants, while its non-expert tensor types remain the same. The same requantization setting does not make all weights identical: K-quants are processed by that setting while existing Q8_0 tensors retain their separate translation. The denser non-expert weights are a plausible contributor to slower decode, but per-op profiling is needed to attribute the gap quantitatively. + +The forced-token matrix uses a 128-token prefix, eight warmups, 32 measured calls, hidden output enabled, and logits on all input tokens. Median milliseconds: + +| Target call | Optimized yamini ms | Current UD ms | +| --- | ---: | ---: | +| T1, no snapshots | 29.64 | **35.19** | +| T3, no snapshots | 38.75 | **44.10** | +| T1, snapshots | 37.51 | **43.42** | +| T3, snapshots | 53.95 | **58.83** | +| T3, reject two | 53.90 | **59.42** | + +UD ordinary T1→T3 costs **8.91 ms**, and snapshot storage adds **14.73 ms** to T3. The latter is close to yamini's 15.20 ms: the extra UD cost is already present in ordinary decode and does not look like a new snapshot-path regression. Rejection raises the T3 median by 0.58 ms in this run; host sequence removal is 0.0072 ms. These differences include full inference scheduling, layout and compute, not only MoE or cache kernels. + +The `Hi` greeting runs use context 4096, one slot, two CPU threads, temperature zero and a 192-token cap. Warmed medians exclude positions below 64. These are one process run per mode, not independent repeated trials. + +| Measurement | Optimized yamini | Current UD | +| --- | ---: | ---: | +| Non-MTP generation tokens/s | 32.23 | **27.15** | +| MTP generation tokens/s | 38.74 | **35.93** | +| Non-MTP target T1 median ms | 29.76 | **35.88** | +| MTP verification T3 median ms | 51.55 | **57.74** | +| Draft token median ms | 6.010 | **5.980** | +| Draft catch-up T3 median ms | 1.808 | **1.790** | +| Accepted proposals | 95/116 (81.90%) | **114/136 (83.82%)** | +| Mean output tokens/round | 2.64 | **2.68** | + +MTP is **32.3% faster** than non-MTP on UD. Both UD continuations have 182 tokens; the yamini continuations had 162 without MTP and 154 with MTP, so cross-model generation rates do not represent an identical-output trial. The changed MTP expert quantization does not show a material draft-latency change in this run. Verification rises by about 6.2 ms, consistent with the additional UD latency observed in ordinary target inference. + +The median round compute subtotal is approximately `57.74 + 2*5.980 + 1.790 = 71.49 ms`. At the measured mean 2.68 output tokens/round this is **26.68 ms/token**, before remaining host work, close to **27.83 ms/token** reported end-to-end. Cold prompt processing is 3.57 s with MTP and 0.40 s without it; graph compilation/startup work is excluded from generation throughput. + +The UD non-MTP `llama-server -np 4 -c 16384` check passes **12/12 requests**, including concurrent four-slot waves, selected-slot reset/reuse, and cached continuation. The UD MTP server also passes **12/12 requests** with two proposals, accepting **42/64 draft tokens**. These short concurrent requests include compilation and test functionality, not warmed serving throughput. No stateful tests were run. A detached clean source checkout containing only the proposed llama.cpp commit files builds `llama-bench`, `llama-cli`, `llama-server`, and `test-backend-sampler` successfully. Its 0.8B slot/rollback and hidden-row regressions pass, and all seven native tests pass again. This confirms the changes build without the unrelated dirty files in the main workspace. Exact commands, metadata/type counts, logs and responses are in `tmp/qwen36-ud-20261016/`. + +## Historical target 35B results (yamini) + +Model: Qwen3.6-35B-A3B-Q4_K_M_yamini.gguf. Same Release build and runtime, `q4_asym64_all`, GPU, native softplus, KV slicing disabled. Baseline is the previous native implementation, rather than the removed single-slot shortcut path. Five benchmark repetitions: `-p 1024 -n 512 -d 0,1024`. + +| Workload | Previous native tokens/s | Optimized tokens/s | +| --- | ---: | ---: | +| pp1024 | 1079.26 ± 7.49 | 1125.19 ± 8.25 | +| tg512 | 23.05 ± 0.27 | 29.91 ± 0.47 | +| pp1024 at depth 1024 | 1031.68 ± 18.71 | 1074.27 ± 33.48 | +| tg512 at depth 1024 | 22.32 ± 0.03 | 28.47 ± 0.44 | + +Generation improves **29.8%** at depth zero and **27.6%** at depth 1024. The 30 tokens/s target is approached at depth zero; the five-repeat mean remains below it. These are generic stateless cache paths. + +Controlled target calls use the same forced-token stream, 128-token prefix, eight warmups, and 32 measured calls. Values below are median milliseconds; hidden states are enabled and all token rows request logits. The Vulkan column is the prior target-model reference, not a new Vulkan rerun. + +| Target call | Previous native OV ms | Optimized OV ms | Prior Vulkan ms | +| --- | ---: | ---: | ---: | +| T1, no snapshots | 42.11 | 29.64 | 43.21 | +| T3, no snapshots | 55.43 | 38.75 | 54.29 | +| T1, snapshots | 60.86 | 37.51 | 33.54 | +| T3, snapshots | 79.27 | 53.95 | 52.59 | +| T3, reject two | 79.58 | 53.90 | 52.72 | + +Three-token verification falls by **31.9%**, from 79.27 to 53.95 ms. The snapshot-enabled T3 penalty falls from 23.84 to **15.20 ms** relative to ordinary T3. Increasing ordinary token width from one to three costs 9.11 ms; rejection adds no measurable penalty in this short comparison, and host sequence removal takes about 0.0072 ms. Restoring state is included in the following target inference. These measurements distinguish snapshot preparation/storage from actual rollback and from multi-token computation; they do not isolate individual kernels. + +Optimized controlled snapshot-enabled T3 is within 2.6% of the previous Vulkan reference, while the ordinary T1 path reaches approximately 30 ms. The greeting workload uses `Hi`, context 4096, one slot, two CPU threads, temperature zero, a 192-token cap, and two draft proposals for MTP. Warmed call medians exclude positions below 64. These are one process run per mode, with many warmed calls, rather than repeated independent trials. + +| Measurement | Previous native OV | Optimized OV | Prior Vulkan reference | +| --- | ---: | ---: | ---: | +| Non-MTP generation tokens/s | 22.95 | **32.23** | — | +| MTP generation tokens/s | 27.93 | **38.74** | 49.83 | +| Non-MTP target T1 median ms | 42.39 | 29.76 | — | +| MTP verification T3 median ms | 77.10 | **51.55** | 42.56 | +| Draft token median ms | 6.015 | 6.010 | 4.99 | +| Draft catch-up T3 median ms | 1.799 | 1.808 | 2.31 | +| Accepted proposals | 95/116 | **95/116** | differing acceptance | + +MTP improves **38.7%** over the previous native path and runs **20.2%** faster than optimized non-MTP on this greeting. The new MTP continuation still has 154 tokens and identical acceptance, so the improvement is not explained by increased acceptance. Non-MTP produces 162 tokens versus 159 previously; use the forced-token table for causal comparisons. + +A round's median compute subtotal is approximately `51.55 + 2*6.010 + 1.808 = 65.38 ms`. Divide by the mean 2.64 output tokens, not always three: this gives **24.76 ms/token** before remaining host work, close to the measured **25.81 ms/token**. Draft generation/catch-up are essentially unchanged; the throughput gain comes from target verification. + +MTP remains **22.3% below** the prior 49.83 tokens/s Vulkan greeting reference. Its 51.55 ms verification is about 9 ms slower than the previous Vulkan greeting, and two draft tokens add about 2 ms more than that reference. The close controlled T3 results and larger greeting gap are different context/output/acceptance workloads; they should not be mixed into one exact overhead estimate. Vulkan's target-model reference was not rerun in this implementation round. Cold prompt time is 3.54 s for MTP versus 0.28 s without it, including first-use graph work; these values are separate from warmed generation. + +## Original optimization validation and artifacts (0.8B and yamini) + +Native GPU tests cover dynamic active counts/token widths, f16/f32, i32/i64, reset, duplicate/cyclic maps, preserved inactive rows, overlapping snapshot destinations, native matrix-layout gather/update, cloning, and compiled export/import. Model regressions replay each active sequence independently to check changing slot subsets, nonzero reset, copied sequences, inactive-state preservation and unequal rejection. Hidden-output tests cover changing selected rows and zero requested outputs. A CPU smoke run passes on 0.8B. + +The final native/type-propagation suite passes **7/7 tests**. The small-model replay regression passes **40/40 sequence comparisons**, with maximum relative logit error **0.002724** against independently replayed sequences. Hidden-state/selected-row/zero-output rollback tests pass with no sampled-token mismatches. The 0.8B `llama-server -np 4 -c 16384` run passes **12/12 requests**, covering concurrent waves, selected-slot reset/reuse, and cached continuation. The 35B non-MTP `llama-server -np 4 -c 16384` run also passes **12/12 requests** under `q4_asym64_all`. The 35B MTP server also passes **12/12 requests** with two proposals, accepting **43/64 draft tokens**. These short server requests include cold graph work and validate functionality; their timings are not warmed throughput baselines. Qwen3.5-0.8B has no MTP tensors, so MTP server validation uses the 35B target. Stateful testing remains outside this work's scope. + +A native-on/off crosscheck repeats the recurrent-slot regression and captures every compared logit vector: **80/80 records match exactly**, with maximum relative error 0 and no argmax mismatches. This checks the new native cache/state-layout translations against the retained generic decomposition. + +The full 0.8B compiled-model cache exports and reloads successfully with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`; GPU cold/export, GPU import, and CPU fallback produce the same eight-token greedy continuation. Native export/import tests additionally cover dynamic metadata and matrix attributes. Release rebuild and `git diff --check` pass for both repositories. CPU fallback is smoke-tested; static, stateful, NPU, and a released runtime without the new native ops were not tested in this implementation round. + +Commands, environments, profiles, model responses, and intermediate/final logs are in `tmp/qwen08-opt-20261016/`. The original baseline evidence is in `tmp/qwen08-perf-plan-20261016/`; the prior 35B native baseline is in `tmp/mtp-native-20261016/`. Early StateUpdate execution attempts exposed a missing GPU factory registration; it was corrected before the successful native/model tests and reported benchmarks. + +## Remaining opportunities + +- Snapshot-enabled verification still has additional state traffic and graph work. A complete native gather→GDN→cache-update operation could eliminate prepared-cache and snapshot intermediates, but requires careful multi-slot alias and overlap semantics. +- Further cache kernel tuning has a limited budget on ordinary 0.8B decode; dense matmul dominates the current profile. Remaining kernel/reorder fusion should be driven by measured latency rather than node count alone. +- Logits still cross to host for sampling, and hidden/norm outputs remain per the caller's output contract. Removing them requires caller-aware output selection; their presence is not a full-cache host-copy problem. +- Vulkan's 57.91 t/s remains ahead; the final 56.21 t/s small-model repeat meets the ≥55 t/s target. Target-model MTP also includes draft/catch-up and acceptance effects that cannot be inferred from the 0.8B target-call matrix. diff --git a/docs/backend/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md similarity index 59% rename from docs/backend/OPENVINO-RECURRENT-CACHE.md rename to ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index e1b03f88cda9..cee316861101 100644 --- a/docs/backend/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -116,8 +116,79 @@ Both operations must preserve arbitrary active subsets, inactive slots, repeated Arbitrary reorders can contain cycles or duplicate sources. A single kernel cannot safely overwrite a buffer that it is still gathering from unless alias safety is proven. Start with an immutable input and separate output allocation; optimize storage reuse only with explicit read-before-write guarantees. Batch metadata can be shared across layers instead of generating redundant per-layer scalar bindings. A frontend custom op without a native GPU implementation would simply expand back into the same operations and would not demonstrate the intended speedup. -First benchmark the two native operations against their existing subgraphs at 1 and 4 slots, 1/2/3 input tokens, with and without snapshots; then rerun the regression and server cases above. These are proposed operations, not implemented or measured speedups in this commit. +First benchmark the two native operations against their existing subgraphs at 1 and 4 slots, 1/2/3 input tokens, with and without snapshots; then rerun the regression and server cases above. These operations were proposals in the 2026-10-15 baseline commit; the implementation and measurements follow below. ## Artifacts Local scratch artifacts are in `tmp/mtp-generic-20261015/`: `run.py`, exact command/environment JSON files, before/after benchmark logs, numerical regression logs, server responses, and synchronized target/draft trace logs. The controlled target and CLI trace harnesses are in `tmp/mtp-gap-20261014/`. + +## Native implementation (2026-10-16) + +`RecurrentStateGather` and `RecurrentConvCache` now have native OpenVINO GPU implementations. They share a GPU primitive and OpenCL kernel, selected by the history attribute (zero for matrix-state gather, positive for convolution history). Each output element has one writer; all cache reads come from an immutable input allocation. The kernel honors the reset range before reading mapped rows, preserves inactive rows, and applies convolution snapshot windows in the original write order. + +The frontend recognizes complete combined-gather `build_rs` groups from their topology. It removes the reset/reorder/remainder chain and routes the convolution CONCAT and all its snapshot CPYs to the native op's two outputs. The convolution-cache gather becomes unreachable and is eliminated. Matrix-state output is still followed by the existing GDN state/snapshot writeback; fusing that later chain is a separate opportunity. Runtime row maps, reset ranges, remainder source/destination offsets, QKV dimensions, and snapshot windows remain dynamic. Short batches use the original runtime window starts, including repeated initial-history windows when fewer than K tokens are available. + +The metadata interface uses rank-four integer tensors. The six shared inputs are old cache `[1,1,S,F]`, active source rows `[1,1,1,B]`, extra source row map `[1,1,1,N]`, reset begin `[1,1,1,1]`, reset length `[1,1,1,1]`, and extra offsets `[1,1,1,2]` containing destination begin and source-map begin. Using a suffix offset permits an empty remainder without binding a zero-sized GPU input. Convolution adds QKV `[1,B,C,T]` and window pairs `[1,1,K,2]` containing start column and destination row; history H is an attribute and F=C*H. Outputs are active state `[1,1,B,F]` or convolution input `[1,B,C,H+T]`, followed by the full updated cache `[1,1,S,F]`. + +Released runtimes lacking these native classes use the existing translators through a CMake symbol check. CPU, forced-static, stateful, and split graphs retain their previous translations. Set `GGML_OPENVINO_DISABLE_RECURRENT_CACHE=1` to compare against the generic decomposition. The disk-cache translation revision is 3 and includes this switch, so old blobs need regeneration. + +Validation completed: + +- Native GPU exact-reference checks: f16/f32 data, i32/i64 metadata, dynamic and fixed shapes, changing batch/token counts, empty/nonempty remainder, nonzero reset, duplicate/cyclic maps, inactive rows, overlapping and short snapshot windows, cloned operations, and compiled-model export/import. +- Large remote-buffer cyclic reorder with caller-bound input/output sharing, repeated four times. +- Core type/shape validation, including rejection of dynamic rank, incorrect metadata types, incompatible history/channel dimensions, and invalid history. +- Four-slot model reset/copy/rollback: 40 comparisons, maximum relative logit error 0.006757, matching the generic baseline. Hidden-state/zero-output/rollback sampler check passes with no logit mismatches. +- Full 35B `llama-server -np 4`: all 12 requests pass without MTP and all 12 pass with two-token MTP under `q4_asym64_all`; MTP accepted 43 of 64 proposals. Cases include concurrent waves, selected-slot reuse, and cached continuation. +- GPU execution profiles confirm exactly one native convolution-cache op and one native matrix-state gather per recurrent layer. On the small Qwen3.5-2B model, the convolution gather is eliminated. Device profiling here establishes execution and graph structure; its summed durations are not full inference latency. +- CPU fallback generation passes. The GPU disable switch also executes the original decomposition with no native recurrent-cache ops. Stateful and NPU execution were not tested. + +Build/test commands and raw results are in `tmp/mtp-native-20261016/`. Native standalone tests use the permanent OpenVINO sources under `src/core/tests/type_prop/recurrent_cache.cpp` and `src/plugins/intel_gpu/tests/functional/single_layer_tests/recurrent_cache.cpp`. + +### Matched full-model benchmark + +Same target environment, Release `build/MtpOVPerf`, five repetitions and `-p 1024 -n 512 -d 0,1024` as the generic baseline: + +| Workload | Generic cache | Native cache | Change | +| --- | ---: | ---: | ---: | +| pp1024 | 1058.21 +/- 7.29 | 1079.26 +/- 7.49 | +2.0% | +| tg512 | 19.72 +/- 0.03 | 23.05 +/- 0.27 | +16.9% | +| pp1024 at depth 1024 | 1016.84 +/- 17.64 | 1031.68 +/- 18.71 | +1.5% | +| tg512 at depth 1024 | 19.10 +/- 0.03 | 22.32 +/- 0.03 | +16.9% | + +The native kernels recover part of the generic cache overhead without reintroducing the removed single-slot shortcuts. They do not recover the shortcut baseline's 35.54 tokens/s. Full-cache output writes and the later GDN writeback still remain; changes to those need equally generic slot and rollback semantics. + +Controlled forced-token target calls (same prefix 128, eight warmups, 32 measured calls and hidden outputs as the baseline): + +| Call | Generic median ms | Native median ms | Latency reduction | +| --- | ---: | ---: | ---: | +| 1 token, no snapshots | 49.41 | 42.11 | 14.8% | +| 3 tokens, no snapshots | 62.55 | 55.43 | 11.4% | +| 1 token, snapshots | 76.49 | 60.86 | 20.4% | +| 3 tokens, snapshots | 95.57 | 79.27 | 17.1% | +| 3 tokens, snapshots, reject 2 | 95.67 | 79.58 | 16.8% | + +Actual rejection still adds little: host `seq_rm` median is 0.00746 ms, and rejecting two tokens changes the target median by 0.31 ms. Three-token snapshot-enabled inference is 23.84 ms slower than three-token ordinary inference, down from 33.02 ms before fusion. Increasing ordinary batch width from one to three adds 13.33 ms, essentially unchanged from the earlier 13.14 ms. The speedup therefore primarily removes cache maintenance overhead rather than changing MoE scaling with token count. The final rejection call took 78.55 ms, including 76.91 ms in raw OpenVINO inference. + +Against the previously measured Vulkan reference, native OV remains slower on snapshot-enabled calls (79.27 versus 52.59 ms for controlled three-token verification). Remaining opportunities include fusing GDN snapshot transpose/scatter with final cache writeback, reducing repeated full-cache copies while preserving arbitrary maps, and reducing metadata/layout dispatches. The new kernels are one dispatch per cache group, but do not fuse the convolution itself or GDN computation. + +End-to-end greeting (`Hi`, temperature zero, one slot, cap 192, same target environment): + +| Measurement | Generic | Native | +| --- | ---: | ---: | +| Non-MTP generation | 19.45 tokens/s | 22.95 tokens/s | +| MTP generation, two proposals | 23.21 tokens/s | 27.93 tokens/s | +| Non-MTP one-token target, median | 49.85 ms | 42.39 ms | +| MTP three-token verification, median | 95.62 ms | 77.10 ms | +| MTP draft token, median | 6.09 ms | 6.02 ms | +| MTP three-token catch-up, median | 1.91 ms | 1.79 ms | +| MTP proposals accepted | 95/116 | 95/116 | + +The native non-MTP and MTP runs generated 159 and 154 tokens, respectively, matching the generic runs. MTP improves by 20.3% over its generic path and runs 21.7% faster than native non-MTP on this greeting. Per-round compute is approximately `(77.10 + 2*6.02 + 1.79)/2.64 = 34.44 ms/token`, before remaining host work; measured generation is 35.81 ms/token. These CLI values are one process run per mode with warmed call medians, not independent repeated trials. Startup/loading and prompt compilation are excluded from generation throughput. + +The previous Vulkan greeting reference remains 49.83 tokens/s with 42.56 ms verification, 4.99 ms draft token, and 2.31 ms catch-up. Native OV reduces its verification deficit from approximately 53 to 35 ms per round; it does not yet close the gap. Acceptance differs across the backend runs, so use the forced-token controlled matrix for causal latency comparisons. Vulkan was not rerun for this implementation. + +## Further shape/control/state-update optimization (2026-10-16) + +The subsequent [small-model investigation and plan](OPENVINO-QWEN35-08B-PERF-PLAN.md) identified runtime shape-inference synchronization around the native kernels. The [implementation results](OPENVINO-QWEN35-08B-PERF-RESULTS.md) document active-row shapes, reusable USM host controls, native `RecurrentStateUpdate`, folded matrix layouts, current cache revision 6, and updated target-model measurements. The earlier revision and throughput tables above remain historical baselines. + +The current target is now `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf` with the same OpenVINO configuration. Updated tests and performance are in the [performance report](OPENVINO-QWEN35-08B-PERF-RESULTS.md); all yamini results above remain historical. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 8e39b4cb19a8..517764ae0f84 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1392,6 +1392,13 @@ void GgmlOvDecoder::add_extra_inputs() { if (m_compute_params.s_copy_active_slot_len != -1) { create_1d_input("s_copy_active_slot_len", m_compute_params.s_copy_active_slot_len); + if (m_model_inputs.count("rs_active_rows") != 0) { + // The row-map prefix is rebound with its current length on every compute. + // Shape consumers must not wait for a scalar uploaded to the GPU. + auto & active = m_model_extra_inputs.at("s_copy_active_slot_len"); + active.shape_source = "rs_active_rows"; + active.shape_axis = 3; + } if (m_is_static) { // Number of real tokens in the current prefill chunk. The last chunk is padded with // fabricated token ids; attention masks them out, but the recurrent (GDN/conv) path @@ -1412,6 +1419,56 @@ void GgmlOvDecoder::add_extra_inputs() { create_1d_input("rs_snapshot_stride_" + node_name, writeback.snapshot_stride); } } +#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE + m_compute_params.recurrent_controls.clear(); + if (!m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && + !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_RECURRENT_CACHE")) { +#ifdef GGML_OPENVINO_HAS_STATE_UPDATE + for (int i = 0; i < m_cgraph->n_nodes; ++i) { + const auto node = m_cgraph->nodes[i]; + const auto op_case = m_node_info_list[i].node_op_case; + if (node->op == GGML_OP_CPY && (op_case == 10 || op_case == 12)) { + m_model_extra_inputs["rs_update_" + get_tensor_ov_name(m_cgraph, node)] = + {ov::element::i64, ov::Shape{1, 1, 1, 4}, 0, true, {}, -1}; + } + } +#endif + for (const auto & [name, write] : m_compute_params.rs_writebacks) { + if (write.src_begin >= 0) { + auto & values = m_compute_params.recurrent_controls["rs_offsets_" + name]; + values = {write.slot_begin, write.src_begin}; + m_model_extra_inputs["rs_offsets_" + name] = + {ov::element::i64, ov::Shape{1, 1, 1, 2}, 0, true, {}, -1}; + } + } + for (int i = 0; i < m_cgraph->n_nodes; ++i) { + const auto concat = m_cgraph->nodes[i]; + if (concat->op != GGML_OP_CONCAT || !concat->src[0] || concat->src[0]->op != GGML_OP_RESHAPE || + !concat->src[0]->src[0] || concat->src[0]->src[0]->op != GGML_OP_VIEW || + concat->src[0]->src[0]->src[0]->op != GGML_OP_GET_ROWS) { + continue; + } + std::vector values; + for (int j = i + 1; j < m_cgraph->n_nodes; ++j) { + const auto write = m_cgraph->nodes[j]; + if (is_conv_state_writeback(write) && write->src[0]->src[0] == concat) { + const auto it = m_compute_params.rs_writebacks.find(get_tensor_ov_name(m_cgraph, write)); + if (it == m_compute_params.rs_writebacks.end()) { + values.clear(); + break; + } + values.push_back(it->second.src_begin); + values.push_back(it->second.slot_begin); + } + } + if (!values.empty()) { + const auto name = "rs_windows_" + get_tensor_ov_name(m_cgraph, concat); + m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1, 1, values.size() / 2, 2}, 0, true, {}, -1}; + m_compute_params.recurrent_controls[name] = std::move(values); + } + } + } +#endif for (const auto & [node_name, row] : m_compute_params.sampling_rows) { create_1d_input("sampling_row_" + node_name, row); } @@ -1500,6 +1557,22 @@ void GgmlOvDecoder::compute_model_inputs() { get_graph_input_shape(node, src, m_node_dynamic_dims[src])}; } } + if (!m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && + m_compute_params.s_copy_active_slot_len > 0) { + const ggml_tensor * rows = nullptr; + for (const auto & [name, tensor] : m_inputs) { + if (tensor->type == GGML_TYPE_I32 && is_s_copy_leaf(tensor)) { + if (rows && rows != tensor) { + return; // Different recurrent row maps cannot share one active shape. + } + rows = tensor; + } + } + if (rows && m_compute_params.s_copy_active_slot_len <= ggml_nelements(rows)) { + m_inputs["rs_active_rows"] = const_cast(rows); + m_model_inputs["rs_active_rows"] = {ov::element::i32, ov::PartialShape{1, 1, 1, -1}}; + } + } } void GgmlOvDecoder::compute_model_outputs() { diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 4e029d4aa3f7..6fc0a7b78ca7 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -120,6 +120,7 @@ struct ComputeParams { std::map rs_writebacks; std::map sampling_rows; std::map gdn_attention_rows; + std::map> recurrent_controls; // Destination slot offset of each state cache writeback CPY node, keyed by node name. It // changes with the batch (kv head, active sequence count) and, with rollback enabled // (cparams.n_rs_seq > 0), the conv state is written back once per snapshot slot. Passed to the @@ -147,6 +148,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { void * data_addr; }; + const ggml_cgraph * get_cgraph() const { return m_cgraph; } + // Graph decoder GgmlOvDecoder(ggml_cgraph * cgraph, ModelParams & model_params, @@ -349,12 +352,17 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { ModelParams get_model_params() const { return m_model_params; } - ComputeParams get_compute_params() const { return m_compute_params; } + const ComputeParams & get_compute_params() const { return m_compute_params; } void set_model_params(const ModelParams & model_params) { m_model_params = model_params; } void set_compute_params(const ComputeParams & compute_params) { m_compute_params = compute_params; } + // Per-request storage: scalar runtime controls are host-produced and shape inference + // may read them. USM host allocations let the GPU consume them without tiny uploads. + std::map runtime_input_storage; + std::map runtime_input_tensors; + bool m_is_static = false; bool m_is_stateful = false; bool m_is_prefill = false; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 785ae6f6420c..ec62da9d6b44 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -129,6 +129,7 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_ENABLE_CACHE", "GGML_OPENVINO_DISABLE_CACHE", "GGML_OPENVINO_DISABLE_KV_SLICE", + "GGML_OPENVINO_DISABLE_RECURRENT_CACHE", "GGML_OPENVINO_ENABLE_FALLBACK", "GGML_OPENVINO_MANUAL_GQA_ATTN", "GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN", diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp index 8a79c7c415f4..f68b652601c7 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -1,6 +1,11 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" +#ifdef GGML_OPENVINO_HAS_STATE_UPDATE +# include "recurrent_cache.hpp" + +# include +#endif #include #include @@ -14,8 +19,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -36,6 +41,52 @@ OutputVector translate_cpy(const NodeContext & context) { auto input_shape = context.get_input_shape(0); auto output_shape = context.get_input_shape(1); +#ifdef GGML_OPENVINO_HAS_STATE_UPDATE + if ((op_case == 10 || op_case == 12) && context.has_input("rs_update_" + context.get_name())) { + auto feature = ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{1, 1, -1, output_shape[3].get_length()}); + auto source = context.get_input(0); + int64_t key_size = 0, value_size = 0; + // Direct non-snapshot state is the native GDN state followed by its GGML-layout transpose. + const auto transpose = ov::as_type_ptr(source.get_node_shared_ptr()); + if (op_case == 10 && transpose) { + const auto order = ov::as_type_ptr(transpose->get_input_node_shared_ptr(1)); + const auto shape = transpose->get_input_partial_shape(0); + if (order && order->cast_vector() == std::vector{0, 1, 3, 2} && shape.rank() == 4 && + shape[2].is_static() && shape[3].is_static()) { + source = transpose->input_value(0); + key_size = shape[2].get_length(); + value_size = shape[3].get_length(); + } + } + if (op_case == 12) { + const auto flat = ov::as_type_ptr(source.get_node_shared_ptr()); + const auto selected = + flat ? ov::as_type_ptr(flat->get_input_node_shared_ptr(0)) : nullptr; + const auto permute = + selected ? ov::as_type_ptr(selected->get_input_node_shared_ptr(0)) : nullptr; + if (permute) { + const auto order = ov::as_type_ptr(permute->get_input_node_shared_ptr(1)); + const auto axis = ov::as_type_ptr(selected->get_input_node_shared_ptr(2)); + const auto shape = permute->get_input_partial_shape(0); + if (order && axis && axis->cast_vector() == std::vector{0} && + selected->get_batch_dims() == 0 && + order->cast_vector() == std::vector{0, 1, 2, 4, 3} && shape.rank() == 5 && + shape[3].is_static() && shape[4].is_static()) { + source = std::make_shared(permute->input_value(0), selected->input_value(1), + selected->input_value(2)); + key_size = shape[3].get_length(); + value_size = shape[4].get_length(); + } + } + } + auto states = std::make_shared(source, feature, false); + auto update = std::make_shared( + ov::OutputVector{context.get_input(1), states, context.get_input("rs_update_" + context.get_name())}, + key_size, value_size); + return rename_outputs_with_suffix({update}, context.get_name()); + } +#endif if (op_case == 11 || op_case == 12) { auto base = context.get_input(1); auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {2}); @@ -56,9 +107,9 @@ OutputVector translate_cpy(const NodeContext & context) { ov::op::v0::Constant::create(ov::element::i64, {}, {2})); } auto states = std::make_shared(state_part, feature, false); - auto rows = std::make_shared( - std::make_shared(states, ov::element::i64), axis, - ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto rows = + std::make_shared(std::make_shared(states, ov::element::i64), axis, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); auto indices = std::make_shared( std::make_shared(zero), std::make_shared(rows), std::make_shared(one), ov::element::i64); @@ -173,8 +224,8 @@ OutputVector translate_cpy(const NodeContext & context) { auto src_begin = context.get_input(src_begin_name); std::vector offsets(window_size); std::iota(offsets.begin(), offsets.end(), 0); - auto indices = std::make_shared(src_begin, - ov::op::v0::Constant::create(ov::element::i64, {size_t(window_size)}, offsets)); + auto indices = std::make_shared( + src_begin, ov::op::v0::Constant::create(ov::element::i64, {size_t(window_size)}, offsets)); window = std::make_shared(context.get_input(0), indices, ov::op::v0::Constant::create(ov::element::i64, {}, {3})); } else if (context.has_input("chunk_valid_len")) { @@ -210,16 +261,16 @@ OutputVector translate_cpy(const NodeContext & context) { FRONT_END_OP_CONVERSION_CHECK(feature_begin >= 0 && feature_end <= full_feature_size, "CPY conv state cache update feature range is out of bounds"); - auto partial_feature = ov::op::v0::Constant::create( - ov::element::i64, {4}, std::vector{1, 1, -1, update_feature_size}); + auto partial_feature = ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{1, 1, -1, update_feature_size}); src = std::make_shared(window, partial_feature, false); if (src.get_element_type() != context.get_output_type()) { src = std::make_shared(src, context.get_output_type()); } - auto src_len = std::make_shared( - std::make_shared(src, ov::element::i64), axis, - ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto src_len = + std::make_shared(std::make_shared(src, ov::element::i64), axis, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); auto slot_end = std::make_shared(begin, src_len); auto active_slots = std::make_shared(base, begin, slot_end, one, axis); diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index a3a1957ae4ba..d7323f4d2ef1 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -3,6 +3,9 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" +#ifdef GGML_OPENVINO_HAS_STATE_UPDATE +# include "recurrent_cache.hpp" +#endif #include "ggml-openvino/ggml-openvino-extra.h" #include @@ -20,15 +23,15 @@ #include #include #include -#include #include -#include +#include #include +#include #include #include #include -#include #include +#include #include #include #include @@ -151,7 +154,45 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { // ggml state layout (OV notation): [B, H_v, value_dim, key_dim] // GatedDeltaNet op expects: [B, H_v, key_dim, value_dim] auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{0, 1, 3, 2}); - state = std::make_shared(state, state_perm); + bool gathered_native_layout = false; +#ifdef GGML_OPENVINO_HAS_STATE_UPDATE + // The native gather owns an immutable cache read and a separate prepared-cache output. + // Bypass the redundant active-prefix slice and transpose only for its active output. + const auto reshape = ov::as_type_ptr(state.get_node_shared_ptr()); + auto active = reshape ? reshape->input_value(0) : state; + if (auto slice = ov::as_type_ptr(active.get_node_shared_ptr())) { + if (auto producer = + ov::as_type_ptr(slice->get_input_node_shared_ptr(0))) { + const auto begin = ov::as_type_ptr(slice->get_input_node_shared_ptr(1)); + const auto axis = ov::as_type_ptr(slice->get_input_node_shared_ptr(4)); + const auto stride = ov::as_type_ptr(slice->get_input_node_shared_ptr(3)); + if (begin && axis && stride && stride->cast_vector() == std::vector{1} && + slice->input_value(2) == context.get_input("s_copy_active_slot_len") && + begin->cast_vector() == std::vector{0} && + axis->cast_vector() == std::vector{2} && slice->input_value(0).get_index() == 0) { + active = slice->input_value(0); + } + } + } + const auto gather = ov::as_type_ptr(active.get_node_shared_ptr()); + const auto shape = state.get_partial_shape(); + // Changing the gather's layout is safe only when its active output has this one consumer. + const auto targets = gather ? gather->output(0).get_target_inputs() : std::set>{}; + const bool exclusive = targets.size() == 1; + if (gather && exclusive && active.get_index() == 0 && gather->get_key_size() == 0 && reshape && shape.rank() == 4 && + shape[2].is_static() && shape[3].is_static()) { + const auto key_size = shape[3].get_length(), value_size = shape[2].get_length(); + gather->set_matrix_shape(key_size, value_size); + gather->validate_and_infer_types(); + auto pattern = + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{-1, H_v, key_size, value_size}); + state = std::make_shared(gather->output(0), pattern, false); + gathered_native_layout = true; + } +#endif + if (!gathered_native_layout) { + state = std::make_shared(state, state_perm); + } g = std::make_shared(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); beta = std::make_shared(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); @@ -204,18 +245,18 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { if (snapshot_count > 1) { auto snapshots = std::make_shared( gdn->output(2), ov::op::v0::Constant::create(ov::element::i64, {5}, {0, 1, 2, 4, 3})); - auto token_count = std::make_shared( - std::make_shared(attn_4d, ov::element::i64), - ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), - ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto token_count = + std::make_shared(std::make_shared(attn_4d, ov::element::i64), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); auto valid_count = std::make_shared( token_count, ov::op::v0::Constant::create(ov::element::i64, {1}, {snapshot_count})); auto indices = std::make_shared( ov::op::v0::Constant::create(ov::element::i64, {}, {0}), std::make_shared(valid_count), ov::op::v0::Constant::create(ov::element::i64, {}, {1}), ov::element::i64); - states = std::make_shared( - snapshots, indices, ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + states = std::make_shared(snapshots, indices, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); } auto new_state = std::make_shared(states, flat_shape_1d, false); auto packed = std::make_shared(ov::OutputVector{attn, new_state}, 0); @@ -224,8 +265,10 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { auto res = std::make_shared(packed, out_shape, false); if (context.get_output_names().size() == 3) { - auto flat_states = std::make_shared(states, - ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1, S_v * S_v * H_v}), false); + auto flat_states = std::make_shared( + states, + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1, S_v * S_v * H_v}), + false); return rename_outputs_with_suffix({res, attn_4d, flat_states}, context.get_name()); } return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp new file mode 100644 index 000000000000..b7b09bce759f --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp @@ -0,0 +1,72 @@ +// Copyright (C) 2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 + +#pragma once +#include "openvino/op/op.hpp" + +namespace ov::op::internal { +// Immutable cache [1,1,slots,features]. All indices/offsets are runtime i32/i64 tensors. +// Gather inputs: cache, active source rows, extra source rows, reset begin, reset length, +// extra offsets [destination begin, source begin]. Extra source rows can be +// a nonempty shared row map; the source offset selects its suffix, including empty suffixes. +// Outputs: active rows and reset/reordered cache. Row indices and offsets must be in bounds. +// Positive key_size/value_size transpose each active matrix from [value,key] to [key,value]; +// the prepared full cache keeps its original layout. +// Inputs and outputs must not alias: reorder maps may contain cycles and duplicate sources. +class OPENVINO_API RecurrentStateGather : public ov::op::Op { + public: + OPENVINO_OP("RecurrentStateGather"); + RecurrentStateGather() = default; + RecurrentStateGather(const OutputVector &args, int64_t key_size = 0, int64_t value_size = 0); + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor &visitor) override; + std::shared_ptr clone_with_new_inputs(const OutputVector &args) const override; + int64_t get_key_size() const { return m_key_size; } + int64_t get_value_size() const { return m_value_size; } + void set_matrix_shape(int64_t key_size, int64_t value_size) { + m_key_size = key_size; + m_value_size = value_size; + } + + private: + int64_t m_key_size = 0, m_value_size = 0; +}; +// Immutable cache and flattened state rows [1,1,N,F]; control [1,1,1,4] +// is (destination begin, sequence count, snapshot stride, source row begin). +// Output is the full cache. Later source rows win if destination planes overlap. +// Sequence count must be positive, stride nonnegative, and source begin in [0,N]. +// All selected destination rows must be in bounds. Kernel source/output allocations must not alias. +// Positive matrix dimensions convert source [head,key,value] to cache [head,value,key]. +class OPENVINO_API RecurrentStateUpdate : public ov::op::Op { + public: + OPENVINO_OP("RecurrentStateUpdate"); + RecurrentStateUpdate() = default; + RecurrentStateUpdate(const OutputVector &args, int64_t key_size = 0, int64_t value_size = 0); + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor &visitor) override; + std::shared_ptr clone_with_new_inputs(const OutputVector &args) const override; + int64_t get_key_size() const { return m_key_size; } + int64_t get_value_size() const { return m_value_size; } + + private: + int64_t m_key_size = 0, m_value_size = 0; +}; +// Conv inputs: same six inputs, new QKV [1,batch,channels,tokens], windows [1,1,K,2]. +// Each window is (start column in history+tokens, destination row); writes batch rows. +// Starts must lie in [0,tokens]; caller supplies valid-token windows for padded/short batches. +// Windows are applied in order, so the last overlapping write wins. +// Outputs: convolution input [1,batch,channels,history+tokens] and final cache. +class OPENVINO_API RecurrentConvCache : public ov::op::Op { + public: + OPENVINO_OP("RecurrentConvCache"); + RecurrentConvCache() = default; + RecurrentConvCache(const OutputVector &args, int64_t history); + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor &visitor) override; + std::shared_ptr clone_with_new_inputs(const OutputVector &args) const override; + int64_t get_history() const { return m_history; } + + private: + int64_t m_history = 0; +}; +} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp new file mode 100644 index 000000000000..a5516ecbb877 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp @@ -0,0 +1,203 @@ +#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE +# include "recurrent_cache_fusion.h" + +# include "../ggml-openvino-extra.h" +# include "ggml-impl.h" +# include "op/recurrent_cache.hpp" +# include "utils.h" + +# include +# include +# include +# include +# include + +namespace ov::frontend::ggml { +RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & decoder, + const std::shared_ptr & tensors) : + m_decoder(decoder), + m_tensors(tensors) { + if (!ggml_openvino_is_gpu() || decoder->is_static() || decoder->is_stateful() || decoder->is_splited_model() || + ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_RECURRENT_CACHE")) { + return; + } + auto actual = std::dynamic_pointer_cast(decoder); + if (!actual || !tensors->count("cache_rs_reset_idx") || !tensors->count("cache_rs_reset_len") || + !tensors->count("s_copy_active_slot_len")) { + return; + } + const auto graph = actual->get_cgraph(); + std::map indices; + for (int i = 0; i < graph->n_nodes; ++i) { + indices[graph->nodes[i]] = i; + } + for (int i = 0; i < graph->n_nodes; ++i) { + const auto cp = graph->nodes[i]; + if (cp->op != GGML_OP_CPY || decoder->get_op_case(i) != 3 || !cp->src[0] || cp->src[0]->op != GGML_OP_VIEW || + !cp->src[0]->src[0] || cp->src[0]->src[0]->op != GGML_OP_GET_ROWS) { + continue; + } + const auto gather = cp->src[0]->src[0]; + const auto root = cp->view_src; + if (!root || (root->type != GGML_TYPE_F32 && root->type != GGML_TYPE_F16) || root->ne[2] != 1 || + root->ne[3] != 1 || gather->src[0]->op != GGML_OP_RESHAPE || gather->src[0]->src[0] != root || + gather->src[1]->op != GGML_OP_NONE || gather->src[1]->type != GGML_TYPE_I32) { + continue; + } + Group group; + group.gather = indices.at(gather); + group.remainder = i; + for (int j = 0; j < group.gather; ++j) { + const auto node = graph->nodes[j]; + if (node->op == GGML_OP_SCALE && node->view_src == root && decoder->get_op_case(j) == 1) { + float scale, bias; + memcpy(&scale, node->op_params, sizeof(float)); + memcpy(&bias, node->op_params + 1, sizeof(float)); + if (scale == 0 && bias == 0) { + group.reset = j; + } + } + } + if (group.reset < 0) { + continue; + } + // Find the convolution CONCAT from the active prefix of this gather, then all + // its cache snapshot writes. No tensor names or captured token counts are used. + for (int j = i + 1; j < graph->n_nodes; ++j) { + const auto node = graph->nodes[j]; + if (node->op != GGML_OP_CONCAT || node->op_params[0] != 0 || !node->src[0] || + node->src[0]->op != GGML_OP_RESHAPE) { + continue; + } + const auto active = node->src[0]->src[0]; + if (active && active->op == GGML_OP_VIEW && active->src[0] == gather && active->view_offs == 0 && + node->src[0]->ne[3] == 1 && node->src[0]->ne[0] * node->src[0]->ne[1] == root->ne[0]) { + group.concat = j; + for (int k = j + 1; k < graph->n_nodes; ++k) { + const auto write = graph->nodes[k]; + if (GgmlOvDecoder::is_conv_state_writeback(write) && write->view_src == root && + write->src[0]->src[0] == node && write->src[0]->ne[0] == node->src[0]->ne[0] && + write->src[0]->ne[1] == node->src[0]->ne[1]) { + group.snapshots.push_back(k); + } + } + break; + } + } + if (group.concat >= 0 && group.snapshots.empty()) { + continue; + } + bool complete = tensors->count("rs_slot_begin_" + decoder->get_op_name(i)) && + tensors->count("rs_src_begin_" + decoder->get_op_name(i)); + for (int snapshot : group.snapshots) { + const auto & name = decoder->get_op_name(snapshot); + complete &= tensors->count("rs_slot_begin_" + name) && tensors->count("rs_src_begin_" + name); + } + const int last = group.snapshots.empty() ? i : group.snapshots.back(); + for (int j = group.reset + 1; j <= last && complete; ++j) { + const auto node = graph->nodes[j]; + // An unrelated cache write cannot be crossed by this fusion. Cache aliases and + // reads of the gather stay valid through the normal in-place refresh machinery. + for (int source = 0; source < GGML_MAX_SRC; ++source) { + const auto input = node->src[source]; + if (!input || (input != root && input->view_src != root)) { + continue; + } + const bool alias = node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE; + const bool matched_read = j == group.gather; + const bool destination = node->op == GGML_OP_CPY && source == 1; + if (!alias && !matched_read && !destination) { + complete = false; + } + } + if (node->view_src == root && (node->op == GGML_OP_SCALE || node->op == GGML_OP_CPY) && + j != group.remainder && + std::find(group.snapshots.begin(), group.snapshots.end(), j) == group.snapshots.end()) { + complete = false; + } + } + if (!complete) { + continue; + } + const auto id = m_groups.size(); + for (int n : {group.reset, group.gather, group.remainder}) { + m_nodes[n] = id; + } + if (group.concat >= 0) { + m_nodes[group.concat] = id; + } + for (int n : group.snapshots) { + m_nodes[n] = id; + } + m_groups.push_back(std::move(group)); + } +} + +OutputVector RecurrentCacheFusion::translate(int index, const NodeContext & context) { + const auto it = m_nodes.find(index); + if (it == m_nodes.end()) { + return {}; + } + auto & group = m_groups[it->second]; + using namespace ov::op; + auto constant = [](std::initializer_list shape, std::initializer_list values) { + return v0::Constant::create(element::i64, Shape(shape), std::vector(values)); + }; + auto metadata = [&](const std::string & name) -> Output { + return std::make_shared(context.get_input(name), constant({4}, {1, 1, 1, 1}), false); + }; + if (index == group.reset) { + group.old_cache = context.get_input(0); + return {group.old_cache}; + } + NodeContext gather_context(m_decoder, m_tensors, group.gather); + auto rows = process_view_input_new(gather_context, 1); + const auto remainder_name = m_decoder->get_op_name(group.remainder); + auto offsets = std::make_shared(OutputVector{context.get_input("rs_slot_begin_" + remainder_name), + context.get_input("rs_src_begin_" + remainder_name)}, + 0); + OutputVector inputs{group.old_cache, + rows, + rows, + metadata("cache_rs_reset_idx"), + metadata("cache_rs_reset_len"), + context.has_input("rs_offsets_" + remainder_name) ? + context.get_input("rs_offsets_" + remainder_name) : + std::make_shared(offsets, constant({4}, {1, 1, 1, 2}), false)}; + inputs[1] = context.has_input("rs_active_rows") ? + context.get_input("rs_active_rows") : + std::make_shared(rows, constant({1}, {0}), context.get_input("s_copy_active_slot_len"), + constant({1}, {1}), constant({1}, {3})); + if (index == group.gather) { + auto op = std::make_shared(inputs); + op->set_friendly_name(context.get_name() + "/RecurrentStateGather"); + group.gathered = op->output(0); + group.prepared = op->output(1); + return {group.gathered}; + } + if (index == group.remainder) { + return {group.prepared}; + } + if (index == group.concat) { + inputs.push_back(process_view_input_new(context, 1)); + OutputVector windows; + for (int snapshot : group.snapshots) { + const auto name = m_decoder->get_op_name(snapshot); + auto window = std::make_shared( + OutputVector{context.get_input("rs_src_begin_" + name), context.get_input("rs_slot_begin_" + name)}, 0); + windows.push_back(std::make_shared(window, constant({4}, {1, 1, 1, 2}), false)); + } + inputs.push_back(context.has_input("rs_windows_" + context.get_name()) ? + context.get_input("rs_windows_" + context.get_name()) : + std::make_shared(windows, 2)); + const auto history = context.get_input_shape(0)[3].get_length(); + auto op = std::make_shared(inputs, history); + op->set_friendly_name(context.get_name() + "/RecurrentConvCache"); + group.conv = op->output(0); + group.updated = op->output(1); + return {group.conv}; + } + return {group.updated}; +} +} // namespace ov::frontend::ggml +#endif diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h new file mode 100644 index 000000000000..bf914f0243af --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h @@ -0,0 +1,24 @@ +#pragma once +#include "../ggml-decoder.h" +#include "node_context.h" + +namespace ov::frontend::ggml { +// Match complete build_rs groups before replacing reset/reorder. Unmatched graphs retain +// their ordinary translators, including CPU, static and released-runtime execution. +class RecurrentCacheFusion { +public: + RecurrentCacheFusion(const std::shared_ptr & decoder, const std::shared_ptr & tensors); + OutputVector translate(int index, const NodeContext & context); +private: + struct Group { + int reset = -1, gather = -1, remainder = -1, concat = -1; + std::vector snapshots; + Output old_cache, gathered, prepared, conv, updated; + }; + + std::shared_ptr m_decoder; + std::shared_ptr m_tensors; + std::vector m_groups; + std::map m_nodes; +}; +} // namespace ov::frontend::ggml diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index f3183e27ee44..5dcc9b8e285e 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -5,6 +5,9 @@ #include "ggml-openvino/openvino/node_context.h" #include "ggml-openvino/openvino/utils.h" #include "input_model.h" +#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE +#include "recurrent_cache_fusion.h" +#endif #include "pass/align_eltwise_ranks.h" #include "pass/fuse_argsort_topk.h" #include "pass/fuse_moe_compressed.h" @@ -312,6 +315,9 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo (*tensor_map)[it.first] = it.second; } +#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE + RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map); +#endif auto translate_node = [&](const std::shared_ptr & decoder, int node_idx) { auto operation_type = decoder->get_op_type(node_idx); if (operation_type == "GGML_OP_NONE") { @@ -332,7 +338,13 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(), "Translation for operation type ", operation_type, " is not implemented."); NodeContext node_context(decoder, tensor_map, node_idx, this); - ov::OutputVector converted_outputs = it->second(node_context); + ov::OutputVector converted_outputs; +#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE + converted_outputs = recurrent_fusion.translate(node_idx, node_context); +#endif + if (converted_outputs.empty()) { + converted_outputs = it->second(node_context); + } FRONT_END_OP_CONVERSION_CHECK(node_output_names.size() == converted_outputs.size(), "Number of ", operation_type, " outputs greater than number of converted outputs, which are ", diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 2d76e56164f8..1066977d5207 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -114,7 +114,17 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : ggml_openvino_is_gpu(); - uint64_t extra_cfg = 2; // Generic recurrent reset/reorder/writeback (invalidate older disk-cache blobs). + uint64_t extra_cfg = 6; // Packed native recurrent controls and state layout. +#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE + extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_RECURRENT_CACHE") ? 0u : 1u); +#else + extra_cfg = extra_cfg * 131; +#endif +#ifdef GGML_OPENVINO_HAS_STATE_UPDATE + extra_cfg = extra_cfg * 131 + 1u; +#else + extra_cfg = extra_cfg * 131; +#endif extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_SLICE") ? 1u : 0u); @@ -255,6 +265,10 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph, for (const auto & [name, input] : decoder.get_model_extra_inputs()) { append_string(name); append_string(input.type.get_type_name()); + append(input.shape.size()); + for (auto dim : input.shape) { + append(dim); + } append(input.is_parameter); if (!input.is_parameter) { append(input.value); @@ -471,6 +485,12 @@ ov::Tensor make_contiguous_split_input_tensor(const struct ggml_tensor * ggml_te ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_decoder, const std::string & name) { const auto * ggml_tensor = ggml_decoder->get_input_ggml_tensor(name); + if (name == "rs_active_rows") { + const auto count = ggml_decoder->get_compute_params().s_copy_active_slot_len; + GGML_ASSERT(count > 0 && count <= ggml_nelements(ggml_tensor)); + return ov::Tensor(ov::element::i32, ov::Shape{1, 1, 1, size_t(count)}, ggml_tensor->data); + } + if (auto sliced = try_make_kv_sliced_tensor(ggml_decoder, name, ggml_tensor)) { return *sliced; } @@ -506,8 +526,35 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod ov::Tensor input_tensor; auto extra_input = ggml_decoder->get_model_extra_inputs().find(param_name); if (extra_input != ggml_decoder->get_model_extra_inputs().end()) { - input_tensor = ov::Tensor(extra_input->second.type, extra_input->second.shape); - *input_tensor.data() = extra_input->second.value; + auto & cached = ggml_decoder->runtime_input_tensors[param_name]; + if (!cached || cached.get_element_type() != extra_input->second.type || + cached.get_shape() != extra_input->second.shape) { + if (ggml_openvino_is_gpu() && !ggml_decoder->is_static() && !ggml_decoder->is_stateful()) { + auto context = ggml_openvino_get_remote_context()->as(); + auto storage = context.create_usm_host_tensor(extra_input->second.type, extra_input->second.shape); + cached = ov::Tensor(extra_input->second.type, extra_input->second.shape, storage.get()); + ggml_decoder->runtime_input_storage[param_name] = storage; + } else { + cached = ov::Tensor(extra_input->second.type, extra_input->second.shape); + } + } + input_tensor = cached; + if (param_name.compare(0, 11, "rs_offsets_") == 0 || param_name.compare(0, 11, "rs_windows_") == 0) { + const auto & controls = ggml_decoder->get_compute_params(); + const auto & values = controls.recurrent_controls.at(param_name); + std::copy(values.begin(), values.end(), input_tensor.data()); + } else if (param_name.compare(0, 10, "rs_update_") == 0) { + const auto & controls = ggml_decoder->get_compute_params(); + const auto & write = controls.rs_writebacks.at(param_name.substr(10)); + auto data = input_tensor.data(); + data[0] = write.slot_begin; + data[1] = write.seq_count >= 0 ? write.seq_count : controls.s_copy_active_slot_len; + data[2] = write.snapshot_stride >= 0 ? write.snapshot_stride : data[1]; + // Direct GDN states contain no attention prefix. + data[3] = 0; + } else { + *input_tensor.data() = extra_input->second.value; + } } else { input_tensor = convert_ggml_input_to_ov(ggml_decoder, param_name); } From b6a1c80780fc31c8c710132c86fa2aec4aac205d Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Mon, 19 Oct 2026 07:59:29 +0200 Subject: [PATCH 24/65] openvino: include dense Q8 weights in all INT4 requantization Convert dense Q8_0/Q5_1 under q4_asym64_all while preserving channel-wise INT8 embedding/output overrides and backup for incompatible row widths. Invalidate compiled-model caches from the previous precision policy. Document converted layouts and the five-repeat UD/yamini performance retest: UD tg512 improves from 27.41 to 33.17 tokens/s and matches yamini at 33.21 tokens/s. Release build and CPU/GPU packed-weight conversion checks pass. --- ggml/src/ggml-openvino/README.md | 2 + .../OPENVINO-QWEN35-08B-PERF-RESULTS.md | 107 +++++++++++++++++- .../src/ggml-openvino/ggml-openvino-extra.cpp | 14 ++- ggml/src/ggml-openvino/model-cache.cpp | 4 +- 4 files changed, 121 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 3d26c68d63ae..ce877c462b12 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -8,6 +8,8 @@ Stateless recurrent execution uses the same reset, reorder, and partial cache-wr The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all`, `GGML_OPENVINO_NATIVE_SOFTPLUS=1`, and `GGML_OPENVINO_DISABLE_KV_SLICE=1`. See the [performance report](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) for measurements; the earlier yamini-model results remain historical references. +`q4_asym64_all` converts Q4_K/Q5_K/Q6_K/Q8_0/Q5_1 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. `token_embd.weight` and `output.weight` retain symmetric channel-wise INT8. Q8_0/Q5_1 rows whose width is not divisible by 64 also use channel-wise INT8. This follows the primary/backup precision scheme of NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM` for these supported source types; it requantizes GGUF values rather than the original floating-point model and leaves floating-point weights unchanged. Earlier versions kept dense Q8_0 at INT8/group-32. Repopulate compiled-model caches without cache-only mode after this change; the cache fingerprint invalidates the old precision policy. + See the [recurrent-cache report](dev_doc/OPENVINO-RECURRENT-CACHE.md) for the measured baseline and proposed native cache-operation fusions. # Compiled model cache diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md index e809f3a0b02e..be386e21a59e 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md @@ -1,6 +1,6 @@ # Qwen recurrent-cache optimization results -Date: 2026-10-16. Implementation was measured from the local changes in llama.cpp (`qwen-openvino-generic-cache`, HEAD `73f61e1cb`) and `/home/zijun/openvino` (`qwen-mtp-openvino-checkpoint`, HEAD `21cacac33d`). The matching native OpenVINO changes are committed as `9e08e52ad5` (`intel_gpu: fuse generic recurrent cache maintenance`). Builds use Release `build/MtpOVPerf` and `/home/zijun/openvino-build-mtp`. Unrelated working-tree changes were preserved. Results below exclude load/requantization/graph compilation from generation throughput. No stateful execution is involved. +Original measurements: 2026-10-16; precision-policy retest: 2026-10-19. The original implementation was measured from the local changes in llama.cpp (`qwen-openvino-generic-cache`, HEAD `73f61e1cb`) and `/home/zijun/openvino` (`qwen-mtp-openvino-checkpoint`, HEAD `21cacac33d`). The matching native OpenVINO changes are committed as `9e08e52ad5` (`intel_gpu: fuse generic recurrent cache maintenance`). Builds use Release `build/MtpOVPerf` and `/home/zijun/openvino-build-mtp`. Unrelated working-tree changes were preserved. Results below exclude load/requantization/graph compilation from generation throughput. No stateful execution is involved. From this retest onward, the target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`. GPU, `q4_asym64_all`, native softplus, and disabled KV slicing remain unchanged. The yamini-model tables below retain their original model identity; new measurements are reported separately. @@ -94,7 +94,110 @@ Five repetitions; mean ± benchmark standard deviation: UD decode is 8.4% lower at depth zero and 8.0% lower at depth 1024. This compares different GGUF quantizations under the same optimized backend; it is not a before/after optimization measurement on UD. No pre-optimization or Vulkan UD baseline has been measured. -The quantization mix differs substantially: non-expert/non-MTP weights change from 95 Q6_K, 53 Q4_K, 94 Q8_0 and 10 Q5_K tensors to 1 Q6_K and 251 Q8_0 tensors. Those weights grow from 1.87 GB to 2.56 GB. Trunk MoE expert weights change from 20 Q6_K/100 Q4_K to 3 Q6_K/80 Q4_K/37 Q5_K. The full MTP block changes from 11 Q8_0/7 F32/2 BF16 (898 MB) to 8 Q8_0/7 F32/2 BF16/1 Q5_K/2 Q4_K (529 MB): its three expert tensors changed from Q8_0 to K-quants, while its non-expert tensor types remain the same. The same requantization setting does not make all weights identical: K-quants are processed by that setting while existing Q8_0 tensors retain their separate translation. The denser non-expert weights are a plausible contributor to slower decode, but per-op profiling is needed to attribute the gap quantitatively. +The source quantization mix differs substantially: non-expert/non-MTP weights change from 95 Q6_K, 53 Q4_K, 94 Q8_0 and 10 Q5_K tensors to 1 Q6_K and 251 Q8_0 tensors. Their original GGUF payload grows from 1.87 GB to 2.56 GB; these are source sizes, not converted runtime sizes. Trunk MoE expert weights change from 20 Q6_K/100 Q4_K to 3 Q6_K/80 Q4_K/37 Q5_K. The full MTP block changes from 11 Q8_0/7 F32/2 BF16 (898 MB source payload) to 8 Q8_0/7 F32/2 BF16/1 Q5_K/2 Q4_K (529 MB source payload). + +A metadata-only probe on 2026-10-19 calls the built backend's `ggml_openvino_get_extracted_layout` for every quantized tensor with `q4_asym64_all`. **Before the precision-policy correction below**, this setting converts Q4_K/Q5_K/Q6_K and **3D expert** Q8_0/Q5_1 to asymmetric INT4/group-64. Ordinary **2D Q8_0 remains symmetric INT8/group-32**; `_all` adds Q4_K to the K-quant policy, rather than including every quantization type. Embedding/output take the earlier channel-wise INT8 override. The following layout table and the historical throughput measurements use that earlier policy; the corrected-policy retest is labeled separately below. + +| Converted quantized weights | yamini | UD | +| --- | ---: | ---: | +| Trunk dense INT4/group-64 tensors | 156 | 0 | +| Trunk dense INT8/group-32 tensors | 94 | 250 | +| Trunk dense packed weights + scales + zero points | 862,814,208 bytes | 1,492,910,080 bytes | +| Trunk expert INT4/group-64 tensors | 120 | 120 | +| Trunk expert packed weights + metadata | 17,364,418,560 bytes | 17,364,418,560 bytes | +| Embedding/output channel-wise INT8 packed weights + metadata | 1,018,112,000 bytes | 1,018,112,000 bytes | +| MTP quantized packed weights + metadata | 475,332,608 bytes | 475,332,608 bytes | + +The 156 tensors changing from INT4/group-64 to INT8/group-32 are 30 attention gates, 10 attention output projections, 10 attention Q projections, 30 recurrent QKV projections, 60 shared-expert FFN projections and 16 SSM output projections. UD therefore adds **630,095,872 bytes (630 MB, 73%)** to the converted dense trunk. These counts describe extracted packed constants, excluding nonquantized tensors, allocation padding and plugin repacking; they are not a measurement of GPU traffic or the compiled model's footprint. The expert, embedding/output and MTP layouts match, but the numerical weights can still differ because requantization starts from different source quantizations. The extra dense weight traffic and different INT8 kernels are a concrete explanation for a decode gap that is already present without snapshots; a controlled INT4/INT8 comparison and per-op profiling are needed to attribute it quantitatively. Probe input, code and per-tensor results are in `tmp/ud-layout-20261019/`. + +### Precision-policy correction, 2026-10-19 + +The [native OpenVINO model card](https://huggingface.co/OpenVINO/Qwen3.6-35B-A3B-int4-ov) specifies NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM`. [NNCF's compression guide](https://github.com/openvinotoolkit/nncf/blob/develop/docs/usage/post_training_compression/weights_compression/Usage.md) defines the ratio over eligible weights excluding special layers; embeddings, convolutions and the last linear layer receive backup precision by default. INT8_SYM is channel-wise. The GGUF backend approximates that precision scheme for supported quantized linear tensors, rather than reproducing compression from the original floating-point model; floating-point tensors remain unchanged. + +`q4_asym64_all` now includes ordinary Q8_0/Q5_1 in INT4/group-64 conversion. The default and non-`all` policies keep their existing dense INT8 behavior, including the expert-only GPU workaround. Embedding/output retain channel-wise INT8. Q8_0/Q5_1 rows not divisible by 64 use channel-wise INT8 backup; all affected rows in these Qwen models are divisible by 64. The compiled-model fingerprint version is incremented so old INT8/group-32 blobs cannot silently serve the updated policy. + +The updated metadata probe finds matching layouts for **all 383 quantized tensors** between yamini and UD. Both now have **250 trunk dense INT4/group-64 tensors**, occupying **757,432,320 bytes** including scales/zero points. This also reduces yamini's footprint: its 94 previously retained dense Q8_0 tensors now convert to INT4. Equal layouts do not imply equal numerical weights or expert-routing decisions. + +Release backend build passes. A targeted conversion/MatMul probe validates Q8_0 and Q5_1 on CPU and GPU against an independent reference decoded from the resulting packed INT4 weights, with dynamic token counts 1, 3 and 32. All 12 comparisons pass (maximum normalized squared error 1.19e-7). Policy checks cover default/native/non-`all` behavior, expert conversion, embedding/output overrides, incompatible-width backup and `no_requant`. Artifacts are `tmp/ud-layout-20261019/{validate.cpp,validation.log,layout-after.tsv}`. These checks validate the conversion path; the full-model performance retest is recorded next. Perplexity has not been evaluated with the corrected policy. + +### Full-model retest with corrected dense INT4 policy, 2026-10-19 + +Release llama.cpp build from HEAD `2a978aa9b` plus the dense Q8_0/Q5_1 policy and cache-fingerprint changes; native OpenVINO HEAD `9e08e52ad5` is unchanged. The exact source diff and command manifests are in `tmp/qwen36-allrequant-20261019/`. Runtime settings are GPU, native softplus, disabled KV slicing and `q4_asym64_all`. Compiled-model caching, stateful execution and profiling are unset for benchmark/CLI runs; the controlled target-call matrix enables host timing instrumentation. GPU workloads run serially. + +Five benchmark repetitions, same `-p 1024 -n 512 -d 0,1024` command; mean ± benchmark standard deviation: + +| UD workload | Earlier dense INT8 policy tokens/s | Corrected dense INT4 policy tokens/s | Change | +| --- | ---: | ---: | ---: | +| pp1024 | 1127.99 ± 7.25 | **1130.09 ± 5.11** | +0.2% | +| tg512 | 27.41 ± 0.07 | **33.17 ± 0.12** | **+21.0%** | +| pp1024 at depth 1024 | 1081.64 ± 19.96 | **1082.36 ± 18.15** | +0.1% | +| tg512 at depth 1024 | 26.19 ± 0.04 | **31.55 ± 0.06** | **+20.5%** | + +Both models with the corrected policy: + +| Workload | UD tokens/s | yamini tokens/s | +| --- | ---: | ---: | +| pp1024 | 1130.09 ± 5.11 | 1133.57 ± 7.88 | +| tg512 | **33.17 ± 0.12** | **33.21 ± 0.08** | +| pp1024 at depth 1024 | 1082.36 ± 18.15 | 1074.32 ± 38.38 | +| tg512 at depth 1024 | **31.55 ± 0.06** | **31.54 ± 0.05** | + +The previous 8% UD/yamini decode gap disappears within run variation. Yamini also improves from 29.91 to 33.21 tokens/s (+11.0%) at depth zero and 28.47 to 31.54 (+10.8%) at depth 1024. Together with matching converted layouts, this supports the retained dense INT8/group-32 weights as the main cause of the previous gap. It does not isolate extra weight bandwidth from differences between INT8 and INT4 kernels. + +The controlled matrix repeats the original 128-token prefix, eight warmups, 32 measured calls, hidden output and logits for all tokens. UD median milliseconds: + +| Target call | Earlier policy ms | Corrected policy ms | +| --- | ---: | ---: | +| T1, no snapshots | 35.19 | **29.80** | +| T3, no snapshots | 44.10 | **38.17** | +| T1, snapshots | 43.42 | **36.75** | +| T3, snapshots | 58.83 | **53.38** | +| T3, reject two | 59.42 | **53.28** | + +Ordinary T1→T3 adds **8.37 ms**. Snapshot storage adds **15.21 ms** to T3, versus 14.73 ms previously; these sequential runs do not establish a meaningful change in that overhead. The consistent 5–7 ms target-call improvement comes from the precision-policy change, with recurrent execution unchanged. + +The corrected-policy yamini matrix also closely matches UD: + +| Target call | UD median ms | yamini median ms | +| --- | ---: | ---: | +| T1, no snapshots | 29.80 | 28.79 | +| T3, no snapshots | 38.17 | 38.06 | +| T1, snapshots | 36.75 | 36.77 | +| T3, snapshots | 53.38 | 53.03 | +| T3, reject two | 53.28 | 53.01 | + +The one-slot `Hi` CLI runs use the original context 4096, two CPU threads, greedy sampling and 192-token cap. Each mode is one process run; medians exclude positions below 64. + +| UD CLI measurement | Earlier policy | Corrected policy | +| --- | ---: | ---: | +| Non-MTP generation tokens/s | 27.15 | **33.07** | +| MTP generation tokens/s | 35.93 | **39.04** | +| Non-MTP target T1 median ms | 35.88 | **28.97** | +| MTP verification T3 median ms | 57.74 | **50.52** | +| Draft token median ms | 5.980 | **5.888** | +| Draft catch-up T3 median ms | 1.790 | **1.736** | +| Draft proposals accepted/generated | 114/136 | **119/143** | +| Mean emitted tokens per cycle | 2.68 | **2.65** | + +MTP generation improves 8.7%, and exceeds the new non-MTP run by 18.1%. The MTP result includes a final two-token verification call (90.77 ms) when reaching the cap; the warmed T3 median describes the usual three-token loop. Both corrected-policy runs reach the 192-token cap, versus 182 tokens previously. Requantization changes the greedy continuation, so the fixed-token matrix is the stronger timing comparison; these CLI runs do not establish unchanged model quality or identical non-MTP/MTP output. + +Both models with the corrected policy, same CLI setup: + +| CLI measurement | UD | yamini | +| --- | ---: | ---: | +| Non-MTP generation tokens/s | **33.07** | **33.26** | +| MTP generation tokens/s | **39.04** | **40.95** | +| Non-MTP target T1 median ms | 28.97 | 29.02 | +| MTP verification T3 median ms | 50.52 | 49.31 | +| Draft token median ms | 5.888 | 5.863 | +| Draft catch-up T3 median ms | 1.736 | 1.722 | +| Draft proposals accepted/generated | 119/143 (83.22%) | 106/126 (84.13%) | +| Mean emitted tokens per cycle | 2.65 | 2.68 | +| Generated tokens without/with MTP | 192/192 | 170/170 | + +Yamini's MTP run improves from 38.74 to 40.95 tokens/s (+5.7%) and is 23.1% faster than its new non-MTP run. The remaining 4.7% UD/yamini MTP throughput difference is from single runs with different continuations, slightly different verification latency/acceptance and UD's final T2 cap call; it cannot be attributed to a packed-weight layout difference. The controlled T3 matrix and repeated non-MTP benchmark now closely agree. All eight benchmark/matrix/CLI processes exit successfully; raw logs, command manifests, per-call distributions and `comparison.json` are in `tmp/qwen36-allrequant-20261019/`. Four-slot serving and perplexity were not rerun in this performance-only retest. + +### Target-call timings with the earlier precision policy The forced-token matrix uses a 128-token prefix, eight warmups, 32 measured calls, hidden output enabled, and logits on all input tokens. Median milliseconds: diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index ec62da9d6b44..74ba6251eca8 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -379,12 +379,13 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * // // GGML_OPENVINO_REQUANT_KQUANT selects a 4-bit target instead. Names are // q4_[_all]: says whether a per-group zero point is kept, - // is the group size, and the _all suffix sends Q4_K down the same path (without it only - // Q6_K/Q5_K are touched): + // is the group size. The _all suffix includes Q4_K; q4_asym64_all also includes + // ordinary Q8_0/Q5_1 linear weights, matching the INT4_ASYM/group-64 primary precision + // used by NNCF with ratio=1.0. Embedding/output retain the channel-wise INT8 overrides above: // q4_sym128 Q6_K/Q5_K -> Q4_0_128 (u4, group 128, symmetric) // q4_sym128_all and Q4_K too -- drops Q4_K's per-32 zero point, which costs some accuracy // q4_asym64 Q6_K/Q5_K -> Q4_1_64 (u4, group 64, asymmetric) - // q4_asym64_all Q6_K/Q5_K and Q4_K -> Q4_1_64 (u4, group 64, asymmetric) + // q4_asym64_all Q6_K/Q5_K/Q4_K/Q8_0/Q5_1 -> Q4_1_64 (u4, group 64, asymmetric) // native no requantization at all (keep Q6_K/Q5_K as they are) // // q4_asym64 leaves Q4_K at its native group 32. Use q4_asym64_all to keep the group size uniform. @@ -405,6 +406,13 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * return ExtraQuantType::Q4_1_64; } } + // Include dense Q8_0/Q5_1 in the explicit all-asymmetric policy. Keep the default GPU + // workaround below restricted to MoE experts: ordinary grouped INT8 MatMul is supported. + if (asym64_all && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) { + // A group must fit within each row. Use backup channel-wise INT8 for incompatible + // widths (Q8_0/Q5_1 allow rows of 32 weights); every affected Qwen3.6 row is divisible by 64. + return tensor->ne[0] % 64 == 0 ? ExtraQuantType::Q4_1_64 : ExtraQuantType::Q8_0_C; + } // MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side // equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4 // (gemma-4 26B-A4B keeps its down projection there). Send them to 4 bits under the same diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 278f62a25a52..ba08832ff1f6 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -345,7 +345,9 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, uint64_t extra_cfg, const std::string & graph_signature) { uint64_t h = FNV_OFFSET; - h = fnv1a_u64(h, 2); + // Version 3 includes dense Q8_0/Q5_1 requantization in q4_asym64_all. Older compiled + // graphs keep those weights at INT8/group-32, even with the same source and settings. + h = fnv1a_u64(h, 3); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); From 01fa0b0884e504899799fcc73d891da73a10e175 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Mon, 19 Oct 2026 10:36:56 +0200 Subject: [PATCH 25/65] openvino: use two GDN outputs for snapshots --- ggml/src/ggml-openvino/README.md | 2 +- .../OPENVINO-QWEN35-08B-PERF-RESULTS.md | 26 +++++++++++++++++++ ggml/src/ggml-openvino/model-cache.cpp | 7 ++--- .../openvino/op/gated_delta_net.cpp | 12 ++++----- .../openvino/op/gated_delta_net.hpp | 10 +++++-- 5 files changed, 45 insertions(+), 12 deletions(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index ce877c462b12..9ef57d7be058 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -1,6 +1,6 @@ # Qwen MTP -Dynamic GPU execution supports Qwen MTP sampling and recurrent state snapshots. Build against the OpenVINO runtime and GPU plugin that provide ordinary `GatedDeltaNet` with `snapshot_count` and a third snapshot output. The backend and runtime must be rebuilt together. +Dynamic GPU execution supports Qwen MTP sampling and recurrent state snapshots. Build against the OpenVINO runtime and GPU plugin that provide ordinary `GatedDeltaNet` with `snapshot_count` and the two-output contract: output 0 is attention; output 1 is the final state when `snapshot_count=1`, or newest-first snapshots when it is greater than one. Snapshot entry 0 is the final state and entry i is the state after token T-i; only min(K,T) entries are valid. The initial state before the batch is not included. The backend and runtime must be rebuilt together. Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. CPU snapshot execution, NPU execution, and forced static MTP are not supported. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md index be386e21a59e..f71fc81018df 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md @@ -291,3 +291,29 @@ Commands, environments, profiles, model responses, and intermediate/final logs a - Further cache kernel tuning has a limited budget on ordinary 0.8B decode; dense matmul dominates the current profile. Remaining kernel/reorder fusion should be driven by measured latency rather than node count alone. - Logits still cross to host for sampling, and hidden/norm outputs remain per the caller's output contract. Removing them requires caller-aware output selection; their presence is not a full-cache host-copy problem. - Vulkan's 57.91 t/s remains ahead; the final 56.21 t/s small-model repeat meets the ≥55 t/s target. Target-model MTP also includes draft/catch-up and acceptance effects that cannot be inferred from the 0.8B target-call matrix. + +## GatedDeltaNet two-output snapshots (2026-10-19) + +The internal OpenVINO `GatedDeltaNet` now has exactly two outputs for every `snapshot_count`. Output 0 is attention. Output 1 is the final recurrent state `[B,H_v,D_k,D_v]` when `K=1`, and the newest-first snapshot tensor `[K,B,H_v,D_k,D_v]` when `K>1`. Snapshot entry `i` contains the state after token `T-i`; entry 0 is the final state. Only `min(K,T)` entries are valid, and the pre-batch state is not included. + +In snapshot mode, the GPU kernel writes the final state into snapshot entry 0 and no longer writes a second copy into the input state buffer. This removes one state matrix write and one operator output per GDN layer and active batch. The input state remains unchanged, which is needed when speculative verification later rolls back. The llama.cpp translation consumes output 1 directly and selects the valid newest snapshot for its existing cache update. Ordinary `K=1` execution keeps its existing GPU state update behavior. Transformations that reconstruct GDN preserve `snapshot_count`; paged GDN fusion skips snapshot mode. The model-cache fingerprint revision is now 4. + +The UD target was measured with the same GPU, `q4_asym64_all`, native softplus, and disabled KV slicing. The ordinary benchmark uses five repeats. The MTP CLI comparison is one warmed run per mode, and the controlled target-call matrix uses the same forced-token stream, prefix, warmups, and measured calls as the previous UD run. + +| Measurement | Previous three-output path | Two-output path | +| --- | ---: | ---: | +| `llama-bench` tg512 | 33.17 ± 0.12 t/s | 33.34 ± 0.06 t/s | +| `llama-bench` tg512 at depth 1024 | 31.55 ± 0.06 t/s | 31.61 ± 0.03 t/s | +| Greeting, non-MTP | 33.07 t/s | 33.29 t/s | +| Greeting, MTP with two proposals | 39.04 t/s | 41.63 t/s | +| Ordinary T3 target call, no snapshots | 38.167 ms | 38.161 ms | +| T3 target call with snapshots | 53.382 ms | 52.853 ms | +| T3 target call with snapshots and two rejected tokens | 53.278 ms | 53.005 ms | +| MTP draft token median | 5.888 ms | 5.892 ms | +| MTP T3 verification median | 50.520 ms | 48.627 ms | +| MTP catch-up T3 median | 1.736 ms | 1.773 ms | +| Accepted proposals | 119 / 143 | 121 / 140 | + +Ordinary decode and the controlled snapshot matrix are within run variation. The one MTP CLI run is 6.6% faster, with verification about 1.9 ms shorter and a somewhat higher acceptance rate; treat this as an encouraging run rather than an isolated causal speedup estimate. Draft generation is unchanged. The structural gain is one fewer GDN state-matrix write per layer and active batch, not an expected large change to total model throughput. + +Validation for this change: the native GDN reference checks cover `K=1/3`, dynamic batches and token widths, optimized and fallback dimensions, valid snapshot ordering, unchanged initial state, and compiled-model export/import. All 21 native GPU GDN unit cases pass. Core type/visitor and transformation tests pass (17 tests), including `FuseL2NormIntoGDN`, `FuseGroupedQueryIntoGDN`, and paged-fusion snapshot preservation. The native recurrent-cache suite passes 7/7; the Qwen3.5-0.8B GPU slot replay and hidden-output rollback checks pass. UD `llama-server -np 4` passes 12/12 requests both without MTP and with two-token MTP, including concurrent requests, slot reuse/reset, and cached continuation. Logs are in `tmp/gdn-two-output-20261019/`. diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index ba08832ff1f6..1c3184675e67 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -345,9 +345,10 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, uint64_t extra_cfg, const std::string & graph_signature) { uint64_t h = FNV_OFFSET; - // Version 3 includes dense Q8_0/Q5_1 requantization in q4_asym64_all. Older compiled - // graphs keep those weights at INT8/group-32, even with the same source and settings. - h = fnv1a_u64(h, 3); + // Version 3 includes dense Q8_0/Q5_1 requantization in q4_asym64_all. + // Version 4 uses GatedDeltaNet output 1 for snapshots in snapshot mode; older + // graphs use the incompatible three-output contract. + h = fnv1a_u64(h, 4); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index d7323f4d2ef1..8fe5607f825b 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -225,14 +225,12 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { auto gdn = std::make_shared(q, k, v, state, g, beta, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); auto attn_4d = gdn->output(0); - auto state_4d = gdn->output(1); // [B, H_v, key_dim, value_dim] // std::cout << "GatedDeltaNet output shapes: attn=" << gdn->output(0).get_partial_shape() // << ", new_state=" << gdn->output(1).get_partial_shape() << std::endl; - // Transpose output state back to ggml layout [B, H_v, value_dim, key_dim] - auto state_transposed = std::make_shared(state_4d, state_perm); - if (context.get_output_names().size() == 2) { + if (snapshot_count == 1 && context.get_output_names().size() == 2) { + auto state_transposed = std::make_shared(gdn->output(1), state_perm); // The canonical graph consumes the packed GGML result only through separate attention // and state VIEWs. Publish the native outputs under those VIEW names to avoid // flatten -> concat -> reshape -> slice -> reshape chains. This also works for B > 1. @@ -241,10 +239,10 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { auto flat_shape_1d = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}); auto attn = std::make_shared(attn_4d, flat_shape_1d, false); - Output states = state_transposed; + Output states; if (snapshot_count > 1) { auto snapshots = std::make_shared( - gdn->output(2), ov::op::v0::Constant::create(ov::element::i64, {5}, {0, 1, 2, 4, 3})); + gdn->output(1), ov::op::v0::Constant::create(ov::element::i64, {5}, {0, 1, 2, 4, 3})); auto token_count = std::make_shared(std::make_shared(attn_4d, ov::element::i64), ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), @@ -257,6 +255,8 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { ov::op::v0::Constant::create(ov::element::i64, {}, {1}), ov::element::i64); states = std::make_shared(snapshots, indices, ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + } else { + states = std::make_shared(gdn->output(1), state_perm); } auto new_state = std::make_shared(states, flat_shape_1d, false); auto packed = std::make_shared(ov::OutputVector{attn, new_state}, 0); diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp index f547078ebcad..239e81f47b9d 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp @@ -26,7 +26,10 @@ class OPENVINO_API GatedDeltaNet : public ov::op::Op { /// \param fuse_qk_l2norm Enables fusing q/k L2-normalization into this op. /// \param q_l2_norm_eps Epsilon used for query L2-normalization when fusion is enabled. /// \param k_l2_norm_eps Epsilon used for key L2-normalization when fusion is enabled. - /// \param snapshot_count Number of newest-first states; adds output [K, B, H_v, D_k, D_v] when K > 1. + /// \param snapshot_count Number of newest-first states. Output 1 is the final state when K = 1; + /// when K > 1 it is [K, B, H_v, D_k, D_v], where entry i is the state after token T-i. + /// Entry 0 is the final state; only min(K, token_count) entries are valid. The initial + /// state before processing token 0 is not included. GatedDeltaNet(const Output& query, const Output& key, const Output& value, @@ -44,7 +47,10 @@ class OPENVINO_API GatedDeltaNet : public ov::op::Op { /// \param fuse_qk_l2norm Enables fusing q/k L2-normalization into this op. /// \param q_l2_norm_eps Epsilon used for query L2-normalization when fusion is enabled. /// \param k_l2_norm_eps Epsilon used for key L2-normalization when fusion is enabled. - /// \param snapshot_count Number of newest-first states; adds output [K, B, H_v, D_k, D_v] when K > 1. + /// \param snapshot_count Number of newest-first states. Output 1 is the final state when K = 1; + /// when K > 1 it is [K, B, H_v, D_k, D_v], where entry i is the state after token T-i. + /// Entry 0 is the final state; only min(K, token_count) entries are valid. The initial + /// state before processing token 0 is not included. GatedDeltaNet(const ov::OutputVector& args, const bool fuse_qk_l2norm = false, const float q_l2_norm_eps = 1e-6F, From 96301435fa7b97db5fc02fa23da7dd14fe91f59b Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 20 Oct 2026 06:58:50 +0200 Subject: [PATCH 26/65] docs: explain native OpenVINO recurrent cache contracts --- .../OPENVINO-QWEN35-08B-PERF-RESULTS.md | 2 +- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md index f71fc81018df..41b43b8d6c7c 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md @@ -294,7 +294,7 @@ Commands, environments, profiles, model responses, and intermediate/final logs a ## GatedDeltaNet two-output snapshots (2026-10-19) -The internal OpenVINO `GatedDeltaNet` now has exactly two outputs for every `snapshot_count`. Output 0 is attention. Output 1 is the final recurrent state `[B,H_v,D_k,D_v]` when `K=1`, and the newest-first snapshot tensor `[K,B,H_v,D_k,D_v]` when `K>1`. Snapshot entry `i` contains the state after token `T-i`; entry 0 is the final state. Only `min(K,T)` entries are valid, and the pre-batch state is not included. +The internal OpenVINO `GatedDeltaNet` now has exactly two outputs for every `snapshot_count`. Output 0 is attention. Output 1 is the final recurrent state `[B,H_v,D_k,D_v]` when `K=1`, and the newest-first snapshot tensor `[K,B,H_v,D_k,D_v]` when `K>1`. Snapshot entry `i` contains the state after zero-based token `T-1-i`; entry 0 is the final state. Only `min(K,T)` entries are valid, and the pre-batch state is not included. In snapshot mode, the GPU kernel writes the final state into snapshot entry 0 and no longer writes a second copy into the input state buffer. This removes one state matrix write and one operator output per GDN layer and active batch. The input state remains unchanged, which is needed when speculative verification later rolls back. The llama.cpp translation consumes output 1 directly and selects the valid newest snapshot for its existing cache update. Ordinary `K=1` execution keeps its existing GPU state update behavior. Transformations that reconstruct GDN preserve `snapshot_count`; paged GDN fusion skips snapshot mode. The model-cache fingerprint revision is now 4. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index cee316861101..041d24be98b1 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -192,3 +192,28 @@ The previous Vulkan greeting reference remains 49.83 tokens/s with 42.56 ms veri The subsequent [small-model investigation and plan](OPENVINO-QWEN35-08B-PERF-PLAN.md) identified runtime shape-inference synchronization around the native kernels. The [implementation results](OPENVINO-QWEN35-08B-PERF-RESULTS.md) document active-row shapes, reusable USM host controls, native `RecurrentStateUpdate`, folded matrix layouts, current cache revision 6, and updated target-model measurements. The earlier revision and throughput tables above remain historical baselines. The current target is now `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf` with the same OpenVINO configuration. Updated tests and performance are in the [performance report](OPENVINO-QWEN35-08B-PERF-RESULTS.md); all yamini results above remain historical. + + +## Native operator contracts (2026-10-20 review) + +The historical graph-node ranges above explain the first prototype. The current native API has three internal OpenVINO operations. They fuse cache data movement; GDN attention and SSM convolution arithmetic remain separate operations. Each cache is a full `[1,1,S,F]` tensor, where `S` is the allocated slot count and `F` is the flattened per-slot state size. Cache/QKV/state inputs support F16/F32; each metadata input supports I32/I64. All input ranks are four, while dimensions and metadata values may change between requests. + +| Operation | Ordered input ports (zero-based) | Output ports | +| --- | --- | --- | +| `RecurrentStateGather` | `cache`, `active_rows`, `extra_rows`, `reset_begin`, `reset_length`, `extra_offsets` | 0: active states `[1,1,B,F]`; 1: full reset/reordered cache | +| `RecurrentConvCache` | the same six inputs, then `qkv [1,B,C,T]`, `windows [1,1,K,2]`; attribute `history=H>0`, `F=C*H` | 0: convolution input `[1,B,C,H+T]`; 1: full cache after window writes | +| `RecurrentStateUpdate` | `prepared_cache`, `states [1,1,N,F]`, `control [1,1,1,4]` | 0: full updated cache | + +Gather logically clears the source interval `[reset_begin, reset_begin+reset_length)` before reading either row map. Active rows are selected from that cleared source, before reorder. `extra_offsets=(destination_begin, source_begin)` selects the suffix `extra_rows[source_begin:]` and copies it to consecutive destination rows. The input allocation stays immutable, which preserves cyclic maps such as `[1,0]` and duplicate sources. Rows outside the reset/reorder ranges are preserved. The active output feeds GDN; the full prepared-cache output feeds StateUpdate. + +Convolution-cache output 0 concatenates gathered per-channel history with projected QKV. Each window `(start_column,destination_row)` copies `H` consecutive columns into `B` cache rows. Valid starts lie in `[0,T]`; the caller supplies valid-token windows for short or padded batches. Window writes occur after reset/reorder and later overlapping windows win. Output 0 uses QKV precision; output 1 uses cache precision. A mixed-precision window write rounds through output-0 precision before converting to cache precision, matching a materialized convolution-input slice. + +StateUpdate control is `(destination_begin, sequence_count, snapshot_stride, source_begin)`. Selected source row `source_begin+r` writes destination row `destination_begin + (r/sequence_count)*snapshot_stride + r%sequence_count`, using integer division. Later source rows win for overlapping planes, including `snapshot_stride=0`; `source_begin=N` is an empty update. For example, two sequences with stride 4 and destination begin 1 write six source rows to `[1,2,5,6,9,10]`. + +Positive `key_size`/`value_size` attributes fold the matrix-layout conversion into gather and update. Gather converts `[head,value,key]` cache matrices to native GDN `[head,key,value]`; StateUpdate converts back. Both attributes default to zero, which disables transpose. They must either both be zero or both positive, with their product dividing `F`. + +GDN has two outputs. Output 0 is attention. Output 1 is `[B,H_v,D_k,D_v]` for `snapshot_count=1`, or `[K,B,H_v,D_k,D_v]` for `K>1`. Snapshot entry `i` is the state after zero-based token `T-1-i`; only `min(K,T)` entries are valid. Entry 0 already contains the final state, so no additional final-state output is needed. Snapshot mode leaves the input matrix state unchanged. + +All runtime indices, reset ranges, windows, and destination rows must be in bounds. The OpenCL kernels use distinct source/output allocations; the GPU runtime may stage a caller's shared remote input/output tensor to preserve immutable reads. This supports multi-slot reset/reorder and speculative rollback without single-slot assumptions. + +The OpenVINO operation specifications are in `docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/`: `recurrent-state-gather.rst`, `recurrent-conv-cache.rst`, `recurrent-state-update.rst`, and `gated-delta-net.rst`. The corresponding C++ developer headers also document every port, attribute, and precedence rule. From 049f55449b4bbc016e61b9f0235e2fef46d3f53d Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 20 Oct 2026 07:08:35 +0200 Subject: [PATCH 27/65] docs: clarify Qwen3.5 purpose of native OpenVINO cache ops --- .../ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md | 2 ++ ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md index 41b43b8d6c7c..2d2578b5ce7e 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md @@ -294,6 +294,8 @@ Commands, environments, profiles, model responses, and intermediate/final logs a ## GatedDeltaNet two-output snapshots (2026-10-19) +The GatedDeltaNet snapshot extension was added to support Qwen3.5 (`qwen35`/`qwen35moe`) in llama.cpp's OpenVINO backend, including the current Qwen3.6 target. MTP verification can reject a draft after processing later tokens in the same batch; llama.cpp needs the earlier recurrent `cache_s` state to roll back to the accepted prefix. Snapshots provide that state without recomputing the recurrence. + The internal OpenVINO `GatedDeltaNet` now has exactly two outputs for every `snapshot_count`. Output 0 is attention. Output 1 is the final recurrent state `[B,H_v,D_k,D_v]` when `K=1`, and the newest-first snapshot tensor `[K,B,H_v,D_k,D_v]` when `K>1`. Snapshot entry `i` contains the state after zero-based token `T-1-i`; entry 0 is the final state. Only `min(K,T)` entries are valid, and the pre-batch state is not included. In snapshot mode, the GPU kernel writes the final state into snapshot entry 0 and no longer writes a second copy into the input state buffer. This removes one state matrix write and one operator output per GDN layer and active batch. The input state remains unchanged, which is needed when speculative verification later rolls back. The llama.cpp translation consumes output 1 directly and selects the valid newest snapshot for its existing cache update. Ordinary `K=1` execution keeps its existing GPU state update behavior. Transformations that reconstruct GDN preserve `snapshot_count`; paged GDN fusion skips snapshot mode. The model-cache fingerprint revision is now 4. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 041d24be98b1..870e166d6290 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -196,6 +196,8 @@ The current target is now `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD- ## Native operator contracts (2026-10-20 review) +These native OpenVINO operations and the GatedDeltaNet snapshot extension were introduced specifically to support Qwen3.5 in llama.cpp's OpenVINO backend. The integration covers the GGML `qwen35` and `qwen35moe` architectures used by Qwen3.5 and the current Qwen3.6 target. `cache_r` holds convolution history and `cache_s` holds recurrent matrix state. Fusing their maintenance reduces data-movement overhead while preserving `llama-server` multi-slot reset/reorder and speculative MTP rollback behavior. + The historical graph-node ranges above explain the first prototype. The current native API has three internal OpenVINO operations. They fuse cache data movement; GDN attention and SSM convolution arithmetic remain separate operations. Each cache is a full `[1,1,S,F]` tensor, where `S` is the allocated slot count and `F` is the flattened per-slot state size. Cache/QKV/state inputs support F16/F32; each metadata input supports I32/I64. All input ranks are four, while dimensions and metadata values may change between requests. | Operation | Ordered input ports (zero-based) | Output ports | From 86c6480cb4e21ee7e6b6808cbc15d4f641a39313 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 10:30:41 +0200 Subject: [PATCH 28/65] llama: skip unallocated hybrid graph inputs Assisted-by: Codex --- src/llama-graph.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 1112ad885493..11599cb589a8 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -172,7 +172,7 @@ bool llm_graph_input_embd_h::can_reuse(const llm_graph_params & params) { } void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) { - if (ubatch->pos && pos) { + if (ubatch->pos && pos && pos->buffer) { const int64_t n_tokens = ubatch->n_tokens; ggml_backend_tensor_set(pos, ubatch->pos, 0, n_tokens*n_pos_per_embd*ggml_element_size(pos)); @@ -1124,10 +1124,16 @@ void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) { } void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { - mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); - mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { + mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); + } + if (inp_attn->self_v_idxs && inp_attn->self_v_idxs->buffer) { + mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); + } - mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); + if (inp_attn->self_kq_mask && inp_attn->self_kq_mask->buffer) { + mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); + } if (inp_attn->self_k_rot) { mctx->get_attn()->set_input_k_rot(inp_attn->self_k_rot); @@ -1139,7 +1145,7 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { const int64_t n_rs = mctx->get_recr()->get_n_rs(); - if (inp_rs->s_copy) { + if (inp_rs->s_copy && inp_rs->s_copy->buffer) { GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); int32_t * data = (int32_t *) inp_rs->s_copy->data; From 0364e7a1189186ba5e676f54c5662121725b5235 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 10:30:41 +0200 Subject: [PATCH 29/65] quantize: preserve Qwen hybrid layer metadata when pruning Assisted-by: Codex --- src/llama-quant.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 821b4798c20d..296e3a8d7878 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -1068,6 +1068,27 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: } if (!prune_list.empty()) { gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), blk_id); + + if (model->arch == LLM_ARCH_QWEN35 || model->arch == LLM_ARCH_QWEN35MOE) { + std::vector recurrent_layers; + uint32_t n_layer_nextn = 0; + + for (uint32_t il = 0; il < model->hparams.n_layer_all; ++il) { + if (std::find(prune_list.begin(), prune_list.end(), il) != prune_list.end()) { + continue; + } + + recurrent_layers.push_back(model->hparams.is_recr(il)); + n_layer_nextn += il >= model->hparams.n_layer(); + } + + gguf_set_arr_data(ctx_out.get(), ml.llm_kv(LLM_KV_ATTENTION_RECURRENT_LAYERS).c_str(), GGUF_TYPE_BOOL, + recurrent_layers.data(), recurrent_layers.size()); + + if (model->hparams.n_layer_nextn > 0) { + gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_NEXTN_PREDICT_LAYERS).c_str(), n_layer_nextn); + } + } } // keep_split requires that the weights are sorted by split index From 490cbf3a2c19f586db179bb9032e3fb2d652321d Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 10:33:26 +0200 Subject: [PATCH 30/65] openvino: emit fused recurrent computation and rotate device caches Replace the three native cache ops with direct complete-group fusion. Support separate staged Update ops, resolve cache views and checkpoints through buffer-owned USM banks, and document both paths. Assisted-by: Codex --- ggml/src/ggml-openvino/CMakeLists.txt | 32 +- ggml/src/ggml-openvino/README.md | 10 + .../OPENVINO-QWEN35-08B-PERF-RESULTS.md | 14 + .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 153 +++- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 817 ++++++++++++++++++ ggml/src/ggml-openvino/ggml-decoder.cpp | 6 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 7 +- ggml/src/ggml-openvino/ggml-openvino-extra.h | 7 + ggml/src/ggml-openvino/ggml-openvino.cpp | 109 ++- ggml/src/ggml-openvino/openvino/op/cpy.cpp | 52 -- .../openvino/op/gated_delta_net.cpp | 82 +- .../openvino/op/gated_delta_net.hpp | 8 + .../openvino/op/recurrent_cache.hpp | 86 +- .../openvino/op/recurrent_cache_update.hpp | 69 ++ ggml/src/ggml-openvino/openvino/op_table.h | 3 + .../openvino/recurrent_cache_fusion.cpp | 145 +++- .../openvino/recurrent_cache_fusion.h | 4 +- .../openvino/translate_session.cpp | 6 +- ggml/src/ggml-openvino/utils.cpp | 76 +- tests/test-backend-sampler.cpp | 13 + 20 files changed, 1486 insertions(+), 213 deletions(-) create mode 100644 ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md create mode 100644 ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index 845b7c0740da..21997fc5b251 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -32,29 +32,35 @@ if (GGML_OPENVINO) endif() endif() -# Keep released runtimes working through the existing primitive translations. +# Released runtimes retain the ordinary cache translators. include(CheckCXXSourceCompiles) -unset(GGML_OPENVINO_HAS_RECURRENT_CACHE CACHE) +unset(GGML_OPENVINO_HAS_FUSED_RECURRENCE CACHE) set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op") check_cxx_source_compiles("#include -int main() { auto gather = std::make_shared(ov::OutputVector{}); - auto conv = std::make_shared(ov::OutputVector{}, 3); }" - GGML_OPENVINO_HAS_RECURRENT_CACHE) +int main() { + auto conv = std::make_shared(ov::OutputVector{}, 3); + auto gdn = std::make_shared(ov::OutputVector{}); +}" + GGML_OPENVINO_HAS_FUSED_RECURRENCE) unset(CMAKE_REQUIRED_LIBRARIES) unset(CMAKE_REQUIRED_INCLUDES) -if(GGML_OPENVINO_HAS_RECURRENT_CACHE) - target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_RECURRENT_CACHE=1) +if(GGML_OPENVINO_HAS_FUSED_RECURRENCE) + target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_FUSED_RECURRENCE=1) endif() -unset(GGML_OPENVINO_HAS_STATE_UPDATE CACHE) +# Separate Update ops permit staged in-place cache mutation on compatible runtimes. +unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE) set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op") -check_cxx_source_compiles("#include -int main() { auto update = std::make_shared(ov::OutputVector{}); }" - GGML_OPENVINO_HAS_STATE_UPDATE) +check_cxx_source_compiles("#include +int main() { + auto conv = std::make_shared(ov::OutputVector{}, 3); + auto gdn = std::make_shared(ov::OutputVector{}); +}" + GGML_OPENVINO_HAS_CACHE_UPDATE) unset(CMAKE_REQUIRED_LIBRARIES) unset(CMAKE_REQUIRED_INCLUDES) -if(GGML_OPENVINO_HAS_STATE_UPDATE) - target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_STATE_UPDATE=1) +if(GGML_OPENVINO_HAS_CACHE_UPDATE) + target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1) endif() diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 9ef57d7be058..26a2402e3497 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -6,6 +6,16 @@ Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP w Stateless recurrent execution uses the same reset, reorder, and partial cache-writeback paths at every slot capacity, including one slot without MTP. `test-backend-sampler --test recurrent_slots` compares four-slot reset, copy, inactive-slot preservation, and rollback against independently replayed sequences. +The matched stateless GPU path emits two fused operations per recurrent layer: +`RecurrentConvCache` and `RecurrentGatedDeltaNet`. Each computes its result and +returns the full updated cache. Device-USM cache banks rotate by default; +`GGML_OPENVINO_RECURRENT_CACHE_INPLACE=1` selects the separate staged Update ops +on a compatible runtime. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` selects the +ordinary GGML decomposition. The older three-op native path is removed. +The [integration report](dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md#direct-frontend-integration-and-branch-split-2026-10-22) +records the required OpenVINO branches and tests. Rebuild both repos and regenerate +compiled-model blobs after this translation change (revision 10). + The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all`, `GGML_OPENVINO_NATIVE_SOFTPLUS=1`, and `GGML_OPENVINO_DISABLE_KV_SLICE=1`. See the [performance report](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) for measurements; the earlier yamini-model results remain historical references. `q4_asym64_all` converts Q4_K/Q5_K/Q6_K/Q8_0/Q5_1 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. `token_embd.weight` and `output.weight` retain symmetric channel-wise INT8. Q8_0/Q5_1 rows whose width is not divisible by 64 also use channel-wise INT8. This follows the primary/backup precision scheme of NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM` for these supported source types; it requantizes GGUF values rather than the original floating-point model and leaves floating-point weights unchanged. Earlier versions kept dense Q8_0 at INT8/group-32. Repopulate compiled-model caches without cache-only mode after this change; the cache fingerprint invalidates the old precision policy. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md index 2d2578b5ce7e..acd17a4acaae 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md @@ -319,3 +319,17 @@ The UD target was measured with the same GPU, `q4_asym64_all`, native softplus, Ordinary decode and the controlled snapshot matrix are within run variation. The one MTP CLI run is 6.6% faster, with verification about 1.9 ms shorter and a somewhat higher acceptance rate; treat this as an encouraging run rather than an isolated causal speedup estimate. Draft generation is unchanged. The structural gain is one fewer GDN state-matrix write per layer and active batch, not an expected large change to total model throughput. Validation for this change: the native GDN reference checks cover `K=1/3`, dynamic batches and token widths, optimized and fallback dimensions, valid snapshot ordering, unchanged initial state, and compiled-model export/import. All 21 native GPU GDN unit cases pass. Core type/visitor and transformation tests pass (17 tests), including `FuseL2NormIntoGDN`, `FuseGroupedQueryIntoGDN`, and paged-fusion snapshot preservation. The native recurrent-cache suite passes 7/7; the Qwen3.5-0.8B GPU slot replay and hidden-output rollback checks pass. UD `llama-server -np 4` passes 12/12 requests both without MTP and with two-token MTP, including concurrent requests, slot reuse/reset, and cached continuation. Logs are in `tmp/gdn-two-output-20261019/`. + + +## Generic convolution/GDN fusion (2026-10-21) + +The subsequent [fusion report](OPENVINO-RECURRENT-FUSION-PERF.md) implements two +native GPU computation/cache operations per recurrent layer for Qwen3.5/Qwen3.6 +in llama.cpp. It includes matched four-slot UD server results, runtime copy/kernel +profiling, MTP rejection/rollback validation, and remaining cache-output traffic. +The small-model vectorization experiment's GPU `llama-bench -p 1024 -n 128 -r 3` +run measured **58.71 ± 0.09 decode tokens/s** and **7,375.10 ± 82.23 prompt tokens/s**. +GDN vectorization was subsequently reverted; these are experiment results, not a +measurement of the final retained kernel. This is +a different workload from the original `-p 0` table above and has no freshly rerun +Vulkan control. The older measurements retain their original meaning. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 870e166d6290..222082f4cd4f 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -189,7 +189,7 @@ The previous Vulkan greeting reference remains 49.83 tokens/s with 42.56 ms veri ## Further shape/control/state-update optimization (2026-10-16) -The subsequent [small-model investigation and plan](OPENVINO-QWEN35-08B-PERF-PLAN.md) identified runtime shape-inference synchronization around the native kernels. The [implementation results](OPENVINO-QWEN35-08B-PERF-RESULTS.md) document active-row shapes, reusable USM host controls, native `RecurrentStateUpdate`, folded matrix layouts, current cache revision 6, and updated target-model measurements. The earlier revision and throughput tables above remain historical baselines. +The subsequent [small-model investigation and plan](OPENVINO-QWEN35-08B-PERF-PLAN.md) identified runtime shape-inference synchronization around the native kernels. The [implementation results](OPENVINO-QWEN35-08B-PERF-RESULTS.md) document active-row shapes, reusable USM host controls, native `RecurrentStateUpdate`, folded matrix layouts, historical cache revision 6, and updated target-model measurements. The earlier revision and throughput tables above remain historical baselines. The current target is now `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf` with the same OpenVINO configuration. Updated tests and performance are in the [performance report](OPENVINO-QWEN35-08B-PERF-RESULTS.md); all yamini results above remain historical. @@ -219,3 +219,154 @@ GDN has two outputs. Output 0 is attention. Output 1 is `[B,H_v,D_k,D_v]` for `s All runtime indices, reset ranges, windows, and destination rows must be in bounds. The OpenCL kernels use distinct source/output allocations; the GPU runtime may stage a caller's shared remote input/output tensor to preserve immutable reads. This supports multi-slot reset/reorder and speculative rollback without single-slot assumptions. The OpenVINO operation specifications are in `docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/`: `recurrent-state-gather.rst`, `recurrent-conv-cache.rst`, `recurrent-state-update.rst`, and `gated-delta-net.rst`. The corresponding C++ developer headers also document every port, attribute, and precedence rule. + +## Fused computation and cache writeback (2026-10-21) + +The dynamic stateless GPU path now optionally emits **two recurrent operations per +Qwen3.5/Qwen3.6 layer**, covering both ordinary multi-slot serving and MTP: + +- `RecurrentConvCache` with optional input 8 (depthwise weights) performs reset, + active-history reads, convolution, reorder and ordered history writeback. Output 0 + is `[1,B,T,C]`; output 1 is the complete updated `cache_r`. +- `RecurrentGatedDeltaNet` performs active-state reads from the logically reset + original cache, GDN computation, reorder and ordered snapshot writeback. Output 0 + is attention `[B,T,H,V]`; output 1 is the complete updated `cache_s`. + +The fused GDN has inputs Q, K, V, original cache, gate, beta, active rows, extra rows, +reset begin, reset length, extra offsets, and write control, in that order. Row maps +and controls retain the contracts above. It inherits GDN's normalization attributes +and `snapshot_count`; only the newest `min(snapshot_count,T)` states are written. +Later source planes win overlaps. No active-state, prepared-cache or standalone +snapshot intermediate is allocated. All reads use immutable original cache storage, +so cyclic maps, duplicate rows, inactive slots and rollback remain supported. + +The GPU precision pass preserves cache I/O precision. The kernels perform the +original computation-precision rounding internally, including preserved cache rows, +so a global FP16 execution policy does not require whole-cache F32→F16→F32 +conversions. Convolution uses FP32 accumulation, with small differences possible +from the standard convolution kernel's accumulation order. The existing six-input +GDN contract and eight-input convolution-cache contract remain available. + +The frontend matches exclusive state consumers and the exact depthwise convolution +layout. For snapshots it matches only the valid newest-first prefix. Unmatched +graphs keep the generic path. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` disables +the computation fusion; `GGML_OPENVINO_DISABLE_CACHE_PREPARE_FUSION=1` also disables +the preceding prepared-cache elimination in that historical implementation. Capability checks preserve the old path +with runtimes lacking these extensions. Translation cache revision is 8; regenerate +compiled blobs once rather than loading old cache-only artifacts. + +Caller caches already use device USM allocations. The fused cache output ports now +also request device USM for internal GPU staging, while retaining lockable memory +when a CPU consumer needs it. Previously the dynamic iGPU output policy selected +host USM, introducing a full host-USM→device cache copy. A full device→device +writeback copy can still occur; binding the same allocation as input and output +requires immutable source reads. Fewer IR `Result` kernels does not establish +zero-copy execution. The detailed measurements +and remaining opportunities are in [the fusion performance report](OPENVINO-RECURRENT-FUSION-PERF.md). + +## Device cache output ownership + +The Qwen3.5/Qwen3.6 stateless GPU backend uses two device-USM allocations for +each eligible full recurrent cache root. GGML tensor addresses remain logical +and stable. Tensor I/O and cache views resolve the current allocation; the next +inference binds that allocation as input and the spare allocation as output. +Only successful inference swaps current and spare. Checkpoint export/import, +sequence copies and full-buffer clears use the same buffer-owned mapping. + +The GPU plugin binds fused cache output port 1 directly only when the output is +a compatible dynamic device-USM Result with no overlap with kernel or graph inputs. +Aliased callers retain private staging and final copying, preserving immutable +reads for cyclic maps and duplicate sources. Returning from direct binding to +aliasing detaches borrowed output storage before allocation reuse. Static, +stateful, split, noncontiguous and partial-root cases retain their existing path. +`GGML_OPENVINO_DISABLE_CACHE_ROTATION=1` disables backend rotation for comparison. +The extra spare capacity equals the full eligible recurrent cache size. + +This removes a final output copy; it does not remove the full-cache kernel +read/write needed to materialize reset, reorder and retained rows, nor change +computation-precision rounding. See +[the performance report](OPENVINO-RECURRENT-FUSION-PERF.md) for measurements. + + +## Separate in-place Update operations (2026-10-22) + +The experimental `GGML_OPENVINO_RECURRENT_CACHE_INPLACE=1` path adds independent +`RecurrentConvCacheUpdate` and `RecurrentGatedDeltaNetUpdate` operations for +Qwen3.5/Qwen3.6 in llama.cpp. This round adds no changes to existing OpenVINO +operation contracts or computation kernels. Shared plugin changes register the +new operations, preserve their cache precision, and allow their safe output +binding. Earlier local changes to existing ops remain separate prior work. + +Each recurrent layer still emits two operations and two full-cache Results. +Eligible caches bind **one device-USM allocation as both Parameter and Result**; +there is no spare bank or final full-cache copy. The plugin accepts this binding +only for a compatible dynamic cache layout with an exclusive reader and no +other overlapping inputs. Static/stateful/split cases retain their existing +paths. If the new op capability is unavailable, the opt-in has no effect on +normal cache rotation. + +Each new GPU operation uses two kernel launches when aliased: + +1. Gather active source rows and nonidentity reorder sources into private + **device** scratch, applying logical source reset and compute-precision + rounding. The stage completes before any cache writes. Identity suffix rows + require no scratch write. Scratch capacity still uses the active-map plus + full extra-map lengths; total memory is not guaranteed to shrink merely by + removing the spare bank. Arbitrary cycles and duplicate rows remain safe. +2. Compute convolution/GDN and write the cache in its original allocation. + Destination elements have one owner, with the original reset → reorder → + ordered writeback precedence. GDN retained-row workers skip destinations + written by recurrence/snapshot owners. Already rounded retained values need + no write, but retained rows are still read to preserve existing rounding. + +Distinct allocations use one immutable-source compute/writeback kernel. Shared +cache readers and incompatible/overlapping output bindings use private output +storage and any required final copy. The alias optimization is therefore an +allocation choice; it does not require single-slot/no-rollback assumptions. +Checkpoint operations continue to access the buffer-owned current allocation. +A failed GPU inference can leave an aliased cache partly updated; callers must +clear or restore it before retrying. + +The computation retains the established fused FP32 accumulation, FP16/F32 +conversion, GDN K128/vector-four path, and sequential token recurrence. These +new operations do not yet substitute the optimized paged GDN/causal-convolution +implementations. Command replay is conservatively disabled for these ops; +the normal dynamic graph already cannot use full command replay. + +Capability detection and cache revision **9** distinguish the new translation. +Regenerate old compiled-model blobs. The full contracts, buffer conditions, +shape rules, and snapshot precedence are documented in OpenVINO's new +`recurrent-conv-cache-update.rst` and `recurrent-gated-delta-net-update.rst`. + +For the target UD model with `q4_asym64_all`, `llama-server -np 4 -c 8192`, +1,024 prompt tokens and 512 generated tokens, three-request means are: + +| Path | Non-MTP decode tokens/s | Two-token MTP decode tokens/s | +| --- | ---: | ---: | +| Default rotation | 27.875 | 46.345 | +| In-place Update | 29.001 | 45.014 | + +Both modes eliminate all full-cache device copies on the eligible alias path, +and output/acceptance match the rotation controls. Ten new native/core/visitor +tests, twelve existing regressions, and fifty four-slot replay comparisons pass. +The MTP slowdown keeps this path experimental and opt-in. See +[the performance report](OPENVINO-RECURRENT-FUSION-PERF.md) for prompt timings, +transfer evidence, measurement limits, and remaining work. + +## Current frontend path (2026-10-22 cleanup) + +llama.cpp now emits nine-input `RecurrentConvCache` and twelve-input +`RecurrentGatedDeltaNet` directly, or their separate Update counterparts when +in-place execution is requested. The standalone native gather/update path and +its declaration mirrors, capability checks and prepared-cache pass are removed. +The historical contracts above explain the earlier experiments. + +Complete reset/reorder/compute/writeback groups must match before any cache +mutation is replaced. Shared state readers and unsupported groups retain ordinary +GGML translations. Only the full updated caches become Results; intermediate +state and snapshot outputs are eliminated. Rotation still publishes a spare USM +bank only after successful inference; the opt-in Update path stages original rows +before writing the caller's allocation. Translation revision is **10**. + +The [fusion report](OPENVINO-RECURRENT-FUSION-PERF.md#direct-frontend-integration-and-branch-split-2026-10-22) +records the stacked OpenVINO branches and validation. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md new file mode 100644 index 000000000000..04e6095f805e --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -0,0 +1,817 @@ +# Qwen3.5/Qwen3.6 generic recurrent fusion performance + +2026-10-21. This work supports Qwen3.5 and Qwen3.6 (`qwen35`/`qwen35moe`) in +llama.cpp's OpenVINO backend, including multi-slot llama-server and draft-MTP +verification/rollback. It implements the two computation/cache boundaries proposed +in [the recurrent-cache design](OPENVINO-RECURRENT-CACHE.md). No stateful or +single-slot/no-rollback shortcut is used. + +## Implementation + +Each recurrent layer uses two native GPU operations on the matched graph: + +1. Nine-input `RecurrentConvCache`: logical reset, active history read, depthwise + convolution, reorder, and ordered history-window writes. It returns convolution + output plus the full updated `cache_r`. The existing eight-input history-only + form is retained. +2. `RecurrentGatedDeltaNet`: logical reset, active state read, GDN computation, + reorder, and ordered final-state/MTP snapshot writes. It returns attention plus + the full updated `cache_s`. The existing six-input GDN is retained. + +All metadata remains runtime input: active/extra row maps, reset ranges, source and +destination offsets, and ordered write controls. Original cache reads are immutable; +cyclic/duplicate maps are valid. Later overlapping writes have the original ordered +precedence. Only the initialized newest `min(snapshot_count,T)` states participate +in MTP writeback. The frontend requires the exact valid-prefix selection before +fusing snapshot mode. Cache layout is `[head,value,key]`, avoiding standalone state +transpose/gather/update intermediates. + +A GPU precision pass keeps F32 cache inputs and outputs while selecting the normal +FP16 computation policy. Kernels explicitly retain the former computation-precision +rounding, including preserved rows. Convolution accumulates in FP32. For long +prefill, adjacent convolution lanes read adjacent tokens from channel-major QKV; +short batches favor contiguous channel output writes. GDN vectorization and moving +snapshot destination checks out of per-element +writes were also evaluated. They improved the isolated graph but the first UD +non-MTP retest slowed down, so they were reverted because a full-model benefit was not established. +Grouping multiple preserved rows into each subgroup +was tried and removed because it provided no clear additional improvement. + +`RecurrentStateGather(prepare_cache=false)` and seven-input `RecurrentStateUpdate` +provide the preceding, independently usable prepared-cache elimination. Capability +checks keep older runtimes on the existing path. CPU/static/stateful/split translation +paths are outside this fusion. Compiled-model cache revision is **8**. + +## Matched server measurements + +Device: Intel Arc B390 (PTL), Core Ultra X7 358H. Release `build/MtpOVPerf`, +OpenVINO `/home/zijun/openvino-build-mtp`. llama.cpp base HEAD `049f55449` plus +local backend changes; unrelated existing worktree changes were preserved. + +Target: `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`. +Environment: + +```sh +GGML_OPENVINO_DEVICE=GPU +GGML_OPENVINO_NATIVE_SOFTPLUS=1 +GGML_OPENVINO_DISABLE_KV_SLICE=1 +GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all +``` + +Server arguments are `-np 4 -c 8192 -t 2 -tb 2`. One active `/completion` request +uses exactly **1,024 saved prompt token IDs**, `temperature=0`, `top_k=1`, +`n_predict=512`, `ignore_eos=true`, `cache_prompt=false`, and nonstreaming output. +An eight-token warmup uses the same prompt. MTP adds +`--spec-type draft-mtp --spec-draft-n-max 2`. GPU workloads run serially. Disk +compiled-model caching and stateful execution are unset. Load/requantization, +compilation and warmup are excluded from server generation timings. + +The final comparison uses a control from the same current build with both +`GGML_OPENVINO_DISABLE_CACHE_PREPARE_FUSION=1` and +`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1`. This preserves the original native +cache ops, GDN and convolution, while disabling this round's transformations. +The repeated control averages **26.497 tokens/s** decode and **905.70 tokens/s** +prompt processing. The final fused/device-USM build averages **27.631 tokens/s** +decode and **912.09 tokens/s** prompt processing: **4.28% faster decode** than the +repeated control, reducing the average token cost from about **37.74 to 36.19 ms**. +This remains below the requested 30 tokens/s target. The primary content +matches the control exactly, as do the two fused repeats. All four concurrent +functional requests completed 96 output tokens. + +| Final build / mode | Decode tokens/s, three requests | Mean decode tokens/s | Mean prompt tokens/s | +| --- | ---: | ---: | ---: | +| Both new fusions disabled | 26.529 / 26.509 / 26.453 | 26.497 | 905.70 | +| Two-op fusion, device-USM cache staging | 27.702 / 27.614 / 27.577 | 27.631 | 912.09 | +| Two-op fusion, device-USM, two-token MTP | 43.450 / 43.353 / 42.528 | 43.110 | 651.87 | + +The final non-MTP comparison keeps the same pre-vector GDN kernel. The disabled +control and fused run share the new runtime allocation policy, but the control +has no fused cache port to select it. This comparison measures the combined +translation/kernel/allocation change; it does not isolate the device-USM policy's +individual contribution. MTP is 56.0% faster than final non-MTP on this particular +prompt, with **340/340 draft tokens accepted in each request**. This is a +high-acceptance example, not a general MTP speedup estimate. Its primary content +matches non-MTP. The four varied concurrent cases complete 96 tokens each and +accept 47/94, 58/74, 55/79 and 54/81 proposals. The whole-model transfer probe +passed with a rebuilt probe linked to the current OpenVINO 2026.5.0 runtime; +its transfer evidence is detailed below. An earlier probe attempt linked the stale +2026.4.1 runtime alongside the server's current runtime and crashed during startup; +it is excluded from performance evidence. + +Earlier stages are recorded below to expose variation across kernel/runtime changes; +they are not substitutes for the final repeated control. + +| Earlier stage | Decode tokens/s | Prompt tokens/s | +| --- | ---: | ---: | +| Early disabled-fusion control, one request | 25.216 | 889.18 | +| Initial computation fusion, before coalesced convolution reads | 27.662 | 622.18 | +| Coalesced convolution, three requests | 27.836 / 27.659 / 27.650 | 925.43 / 914.67 / 913.28 | +| MTP, coalesced convolution, three requests | 39.974 / 40.240 / 40.086 | 480.96 / 674.80 / 583.10 | +| Vectorization experiment, non-MTP | 25.818 / 25.893 / 25.908 | 945.45 / 939.82 / 935.92 | +| Vectorization experiment, MTP | 40.427 / 40.098 / 40.866 | 511.95 / 672.78 / 668.92 | +| Vectorization reverted, before device-USM staging | 23.608 / 23.540 / 23.621 | 882.17 / 864.90 / 870.09 | + +Coalesced convolution restored prompt processing after the initial fusion's prefill +regression. The early repeated non-MTP mean was 27.715 tokens/s. The subsequent +vectorization retest averaged 25.873, but reverting it then measured 23.590: the +continued drop does not establish vectorization as its cause. The retained build +uses the pre-vector GDN kernel; the final repeated control is the basis for assessing +its combined changes. Initial fused and early disabled-fusion content is identical. + +Every measured MTP request in the table accepted **340/340 draft tokens**. The +saved prompt is repetitive, so these are high-acceptance results, not a representative +MTP speedup claim. MTP prompt rates remain lower and more variable than non-MTP; +they include draft-context processing and snapshot paths. Four varied concurrent +prompts exercised rejection: the coalesced run accepted 47/94, 58/72, 54/80, 54/81, +and the vectorized experiment accepted 47/94, 58/74, 55/79, 54/81. No current-build +control with MTP and these transformations disabled was measured. + +Historical 2026-10-20 server results were 31.107 tokens/s at explicit `-np 1`, +26.4955 at explicit `-np 4`, and 27.2554 with implicit four slots/unified KV. +They explain the original investigation but are not matched controls for this +worktree. Do not compare those directly to attribute the entire difference to this +patch. Context/slot cache storage and the number of active sequences are separate +variables. The logs allocate four recurrent rows (251.25 MiB cache_r/cache_s) +without MTP and twelve rows (753.75 MiB) for two rollback tokens with MTP. +Thus snapshot mode triples recurrent cache storage even at one active request. + +## What profiling establishes + +The full-model execution graph contains **30 `RecurrentConvCache` and 30 +`RecurrentGatedDeltaNet` operations**, replacing separate gather/GDN/update cache +stages. The 0.8B graph has 18 of each. Fewer nodes alone do not establish lower +latency or zero-copy execution. + +The full-model CSV diagnostics below are sums of OpenVINO **cumulative average** +operator times, including preceding prefill calls. In particular, prefill strongly +contaminates fused computation times. These are graph/traffic clues, **not pure +decode costs**. Profiling substantially slows throughput and was disabled for the +server results. + +| Operator class, summed diagnostic ms | Before np1 | Before unified np4 | Prepared-cache elimination np4 | Initial computation fusion np4 | +| --- | ---: | ---: | ---: | ---: | +| RecurrentStateGather | 1.139 | 2.220 | 0.929 | 0 | +| RecurrentStateUpdate | 0.902 | 1.815 | 2.075 | 0 | +| RecurrentConvCache | 0.585 | 0.682 | 0.694 | 4.084 | +| GatedDeltaNet | 3.771 | 3.842 | 3.802 | 0 | +| RecurrentGatedDeltaNet | 0 | 0 | 0 | 6.613 | +| Convert | 1.251 | 2.487 | 2.484 | 0.124 | +| Result | 0.468 | 1.105 | 1.110 | 0.005 | + +The before np1/np4 profiles show similar GDN arithmetic times but substantially +larger gather/update/precision traffic at four slots. The generic full-cache +contract causes work proportional to stored rows even when one sequence is active. +The fused profile's Result average is not proof that runtime output copying vanished. + +### Isolated GDN/cache experiment + +A standalone dynamic graph uses the target state geometry: 32 value heads, +16 key heads, K=V=128, F32 device-USM cache, FP16 Q/K/V/gate/beta, one active +sequence, no reset/reorder, and either 4 or 12 allocated rows. The legacy reference +explicitly materializes the original FP16 cache/gather/GDN/update/F32 writeback. +The row-count comparison isolates storage work, excluding MoE, quantization, full attention +or llama-server scheduling. Fifty inferences follow eight warmups; all data tensors +are device USM and metadata is constant. These microbenchmarks are not full-model +latency estimates. + +| Snapshot count / tokens / rows | Materialized, caller alias ms | Initial fused, caller alias ms | Vectorized fused, caller alias ms | +| --- | ---: | ---: | ---: | +| 1 / 1 / 4 | 0.402 | 0.319 | 0.313 | +| 1 / 1 / 12 | 1.081 | 0.881 | 0.840 | +| 3 / 3 / 4 | 0.575 | 0.324 | 0.278 | +| 3 / 3 / 12 | 1.260 | 0.869 | 0.800 | + +A separate profiling run at 3 snapshots / 3 tokens / 12 rows records about +**0.30 ms in fused GDN and 0.38 ms in the cache Result reorder/copy kernel**. +A distinct output allocation has similar costs to caller input/output aliasing. +Thus this remaining copy cannot be attributed solely to caller aliasing. Runtime +execution-graph port metadata reports both GDN outputs using the first port's +precision/shape, while the actual caller cache output is F32 with the full cache +size. Changing the cache row dimension from static to dynamic eliminates the Result +kernel in a follow-up micrograph, while end-to-end latency remains approximately +0.86 ms with caller aliasing. This establishes a static/dynamic output-ownership +difference, not a universal Result-copy cause in llama.cpp (whose caches use +dynamic rows). A per-port precision override in the op factory did not remove the +static-graph copy and was reverted. + +OpenCL interception in this isolated graph finds two kernel submissions and one +small host-USM→device upload (24,576 bytes at T=3); it finds no explicit large +cache `clEnqueueMemcpyINTEL` transfer. That does **not** mean no cache copy: the +static-graph Result kernel performs a full device-memory pass. The dynamic-rows +case shows **two host-USM→device copies totaling 25,190,400 bytes per call**: +24,576 bytes of ordinary staging plus the 25,165,824-byte cache. Thus the dynamic +output's internal allocation is host USM even with a device-USM caller destination. +This is direct evidence of cache staging traffic, missed by operator-only profiling. +Ordinary llama.cpp caller cache buffers already use device USM. The runtime output +policy is changed for the fused cache port to +allocate device USM, retaining lockable memory when CPU consumers require it. +A rebuilt probe linked only to OpenVINO 2026.5.0 confirms one 25,165,824-byte +**device→device** copy plus the 24,576-byte ordinary upload. This removes host +cache staging but retains the full-cache copy to the caller. The current-runtime +micrograph with caller aliasing averages **0.779 ms** for 50 measured calls; +Using a distinct output averages 0.885 ms in the same diagnostic run. The final +whole-model comparison above measures the combined patch; it does not isolate +this allocation change. + +### Whole-model device-memory transfer check + +A separate shortened UD non-MTP run uses the final backend, `-np 4 -c 8192`, +1,024 saved prompt tokens, an eight-token warmup, and 16 output tokens. It uses +OpenCL/InferRequest interception, not operator profiling. Throughput from this +short instrumented run is not used in the performance table. + +All 60 recurrent cache input ports and 60 recurrent cache output ports bind USM +buffers. Exact cache-root names account for **263,454,720 bytes (251.25 MiB)** +on each side: 11,796,480 bytes for `cache_r` and 251,658,240 bytes for `cache_s`. +Each warmed one-token call records: + +| Intercepted operation | Calls | Bytes | +| --- | ---: | ---: | +| Device→device memcpy | 60 | 263,454,720 | +| Ordinary host→device metadata uploads | 8 | 2,608 | +| Host-USM→device uploads | 20 | 320 | +| Host-USM→host output copies | 3 | 1,009,664 | +| NDRange submissions | 1,020 | — | +| `clFinish` | 21 | — | + +The large memcpy volume matches the 60 final cache outputs exactly. There is no +large host-USM→device cache transfer in the current-runtime probe. The execution +graph contains 30 recurrent-cache primitives and 30 GDN primitives for the fused +ops. It has no separate RecurrentStateGather/StateUpdate stage. This confirms +that reducing those nodes does not remove runtime full-output copying. + +In the last twelve instrumented calls, `infer()` takes about 33.5–33.6 ms, +including 14.2–14.8 ms spent inside `clFinish`. Those waits synchronize queued +GPU work, so their durations are **not additional kernel costs** and cannot be +added to operator times or attributed solely to cache copies. The graph still +submits 1,020 kernels for all layers, projections, MoE, attention and conversions; +two recurrent ops per layer does not mean two kernels for the whole layer. + +Artifacts are `device-cache-probe-rebuilt/`, `micro-probe-current/`, and +`transfer-summary.json`. The initial full-model probe used a stale shared-library +soname and crashed before inference; the successful rebuilt probe supersedes it. +The earlier host-staging microprobe also used that older soname and should be +regarded as diagnostic evidence of the allocation path; the final D2D copy counts +above are verified with the current runtime. + +## Validation + +Both repositories' final builds and `git diff --check` pass. Native core +shape/type/clone/attribute suite: **9/9 pass**. Native GPU suite: **8/8 pass**, +including original APIs, deferred preparation, fused convolution versus GroupConv, +fused GDN versus materialized reference, export/import, mixed FP16/F32, cyclic and +duplicate maps, reset-before-gather, source offsets, ordered overlaps, empty window +lists and device-USM caller input/output aliasing. Both K128 and fallback K8/V7 +GDN paths are covered. Final prefill extensions exercise T=16/17/33, and short +T=1/2 snapshot batches select only initialized states. An additional checked-in +transformation regression passes, ensuring six-input GDN fusion passes leave the +cache-aware runtime-input contract intact. + +Small-model `test-backend-sampler --test recurrent_slots --device gpu` passes +40 comparisons across four sequences with reset/copy/reuse and rollback 0/2; +maximum reported relative logit error is below 0.003. Full UD non-MTP and MTP +server runs each include four concurrent varied prompts, all completing 96 tokens. +The final MTP acceptance is 47/94, 58/74, 55/79 and 54/81 in those cases, +exercising rejection and rollback. Their per-request concurrent rates are functional evidence and are +not comparable to single-active throughput. + +CPU/static/stateful execution was not tested in this round. The fusion is GPU +stateless only; no new support for those modes is claimed. + +## Remaining optimization opportunities + +1. The dynamic full-cache output copy is addressed by the follow-up below; + the initial opportunity was to eliminate the remaining copy to the caller. + Static cache output uses + a Result kernel; dynamic cache output uses runtime memcpy after inference. + Internal staging is now device USM, but both paths still move the full cache. + Caller aliasing still requires + immutable original reads: use device buffer rotation or correct staging rather + than unsafe in-place cyclic reorder. Validate changing shapes, exported graphs, + overlapping windows and four-slot MTP rollback before accepting a speedup. + A concrete implementation needs output-port ownership, not just an op-wide + output-buffer flag: keep cache port 1 in the caller's device allocation when + it is distinct from all reads; for aliases, rotate two device cache buffers and + bind the previous result as the next input. The latter also requires updating + GGML root/view ownership so checkpoints and sequence operations read the current + allocation. Multiple live cache readers must finish before storage reuse. +2. Reduce full-cache preservation traffic. Fusion removes intermediates but still + reads/writes inactive rows. A generic runtime/cache representation that maintains + untouched rows without a full materialization could save more bandwidth; it must + support arbitrary runtime reset/reorder and snapshots, not a single-slot exception. +3. Remove repeated precision roundtrips only after defining and validating the desired + cache numerical contract. Preserving F32 inactive rows changes the old FP16 GPU + behavior and can alter logits/acceptance, so it is not a free optimization. +4. Improve long-token GDN/snapshot prefill and measure draft-prefill separately. + MTP prompt timings are still lower than non-MTP. Use fresh steady-shape profiling, + not mixed prefill/decode cumulative averages, to select the next kernel change. +5. Benchmark representative MTP prompts and compare synchronized T1/T3 trunk and + draft latencies after cache fixes. Remaining MoE/weight/attention work also matters; + node fusion alone does not guarantee the non-MTP 30 tokens/s target. + +## Reproduction and artifacts + +Scratch directory: `tmp/recurrent-fusion-20261021/`. `bench.py` wraps the saved +server harness in `tmp/server-ud-20261020/run_benchmark.py`; `kernel_bench.cpp` +and its before/vector/profile logs contain the isolated experiment. `profile-summary.json` +and per-stage CSV45 files contain the cumulative-average diagnostics. Correctness +logs and final build logs are in the same directory. + +Use response `timings.predicted_per_second` and `timings.prompt_per_second`. +The harness's outer `wall_seconds` includes the two repeat requests and four-slot +checks before returning the primary response; it must not be used as that request's +throughput. Metrics are annotated with this caveat. + +## Follow-up: direct cache output binding (2026-10-21) + +The subsequent optimization implements caller-owned cache output port 1 and +current/spare device-USM rotation. GGML root addresses stay stable; tensor I/O, +views, checkpoints and clears resolve buffer-owned current storage. A successful +inference commits the swap. The plugin only borrows a compatible dynamic Result +destination disjoint from its inputs; switching to an aliased destination detaches +the borrowed bank and restores staging. The backend opt-out is +`GGML_OPENVINO_DISABLE_CACHE_ROTATION=1`. Static/stateful/split and partial-root +cases retain the existing path. Extra device capacity is one full recurrent cache +set: 251.25 MiB without MTP or 753.75 MiB for two rollback tokens at four slots. +This storage replaces the need for private cache-output staging on the direct path. + +The native suites pass 9 core, 8 GPU, and 1 transformation tests. Extended GPU +cases alternate distinct and aliased caller outputs on one request and check +unchanged distinct-input cache contents, dynamic B/T, cyclic/duplicate maps, reset, +ordered overlaps, short snapshots, long prefill, and export/import. The small-model +slot test now passes **50 comparisons**, including checkpoint export/import and +full cache clear with rollback 0/2. + +A current-runtime intercepted dynamic GDN micrograph (T=3, S=12, one active +sequence, K=V=128, 32 value heads) has **zero large D2D copies** for distinct +outputs. Aliased fallback still makes one 25,165,824-byte copy. An unprofiled run +measures 0.488 ms distinct and 0.763 ms aliased; this isolated comparison does not +include other model operations. The small 0.8B server likewise has zero large D2D +cache copies in warmed calls, with 474 NDRange submissions and one clFinish. +Its instrumented short output is functional/traffic evidence, not a benchmark. + +### Computation kernel comparison + +The fused GDN uses the ordinary `gated_delta_net_ref.cl` recurrence, including +K128 float8 per-lane state and four value columns per subgroup. It does **not** +use the newer paged GDN optimized subgroup block-read/write path. The latter +distributes keys interleaved across subgroup lanes for contiguous transactions; +changing the key distribution also changes floating-point reduction order. +Vector cache load/store and hoisting snapshot destination calculations can preserve +the existing arithmetic while reducing addressing and memory instructions. + +Fused convolution computes a direct FP32 dot product over H+1 taps per output. +The separate GroupConvolution selects a device convolution implementation; paged +causal convolution instead keeps history/weights in registers across a sequence's +tokens. Those are different schedules. Register reuse across short token batches +and explicit expansion of the JIT-constant tap loop are candidate improvements; +long prefill must retain sufficient parallelism and coalesced channel-major reads. +Neither fused kernel should be described as already equivalent in performance to +the optimized paged operators. Full-cache preserved-row traffic remains after +copy removal, alongside MoE/projection and ordinary attention costs. + +Follow-up artifacts: `tmp/recurrent-rotation-20261021/`. The matched server harness +uses the same UD model/config, saved 1,024-token prompt, 512 outputs, warmup, +three repeated single-active requests and four varied concurrent slot checks. + +The direct-binding follow-up's matched unprofiled non-MTP control disables only +rotation, keeping the same fused arithmetic and runtime build. All requests +evaluate exactly 1,024 prompt tokens and emit 512 outputs. + +| Rotation setting | Decode tokens/s, three requests | Mean decode tokens/s | Mean prompt tokens/s | +| --- | ---: | ---: | ---: | +| Disabled, private device-USM staging | 28.107 / 28.098 / 28.027 | 28.077 | 758.09 | +| Enabled, direct cache port 1 | 29.148 / 28.965 / 28.651 | 28.921 | 924.84 | + +This is **3.01% higher decode throughput**, about 35.62 to 34.58 ms per +output token. It remains below 30 tokens/s. All primary/repeated content matches +across modes; four concurrent varied requests complete 96 tokens each. Prompt +timings in the control vary considerably and should not be used to isolate +prompt-processing benefit from this short sample. + +Rotation-enabled MTP measures **47.873 / 48.218 / 47.715 tokens/s**, mean +**47.935**, with mean prompt processing 804.76 tokens/s. All three requests +accept 340/340 draft tokens and their content matches non-MTP. Four concurrent +varied requests complete 96 tokens each with acceptance 49/90, 54/82, 55/79, +and 54/81, exercising rejection and rollback. This is not a matched MTP +rotation-disabled comparison; prior staging MTP averaged 43.110 in an earlier +round, so that historical difference alone does not isolate rotation's effect. + +The full UD transfer probe confirms **zero large D2D cache copies** in each +warmed one-token call, removing all 60 copies / 263,454,720 bytes. Ordinary +uploads remain 8/2,608 bytes plus 20/320 bytes, with 1,020 NDRange submissions +and 21 clFinish calls unchanged. Twelve calls average 30.629 ms raw instrumented +infer versus about 33.6 ms in the prior staging probe; these separate shortened +instrumented runs are traffic evidence, not the matched throughput comparison. +The independent-input alias guard also passes the 8 GPU tests and leaves +the isolated distinct GDN latency unchanged (0.491 ms versus 0.491 ms before). + +An unprofiled standalone convolution/cache micrograph (C=8192,H=3, one active +sequence, F32 cache and FP16 computation, distinct device outputs) measures: + +| T / stored rows | Cache preparation + GroupConv ms | Fused convolution/cache ms | +| --- | ---: | ---: | +| 1 / 4 | 0.066 | 0.067 | +| 1 / 12 | 0.125 | 0.089 | +| 3 / 4 | 0.119 | 0.063 | +| 3 / 12 | 0.092 | 0.070 | +| 128 / 4 | 0.226 | 0.302 | +| 128 / 12 | 0.251 | 0.311 | + +The fused three-token path is competitive, but long-prefill arithmetic scheduling +needs improvement. This comparison includes cache preparation/output ownership +differences and is not a pure convolution-kernel comparison. + +A follow-up compute experiment retains GDN's per-lane key distribution and +arithmetic/reduction order, using contiguous eight-element cache loads/stores +and calculating each snapshot destination once per timestep. It passes the +eight native GPU tests with exact GDN/reference state comparison. The same +isolated T3/S12 graph falls from 0.491 to **0.419 ms** for distinct outputs and +0.765 to 0.714 ms for aliased outputs. Explicit unrolling of the JIT-constant +convolution tap loop helps some short shapes (T1/S4 0.067 to 0.052 ms); +T128 stays near 0.302/0.313 ms. This does not resolve long-prefill convolution +scheduling. These short microbenchmarks motivate a full-model retest; they are +not evidence of a proportional model throughput gain. + +The full UD non-MTP compute experiment subsequently measures +28.454 / 27.903 / 27.460 tokens/s (mean **27.939**) with unchanged primary +content, versus rotation-only mean 28.921. Prompt mean is 962.45 tokens/s. +Throughput declines across repetitions, so this does not isolate the experiment +as the cause; however, it does not establish a full-model decode benefit. The +experiment is excluded from the retained optimization pending stronger evidence. + +The MTP compute experiment also provides no established decode benefit: +47.677 / 47.564 / 46.849 tokens/s, mean **47.364**, versus rotation-only +47.935. Output matches and all requests accept 340/340 tokens. Both vector +GDN and convolution-unrolling experiments are **reverted** in the retained +build. Their source and measurements remain under the scratch directory. +A different GDN memory schedule and a long-prefill convolution schedule remain +useful opportunities, but isolated speedups must be confirmed in matched model +runs before adoption. + +Final retained sources restore the original computation kernels, retain direct +cache binding with whole-network input-overlap checks, and correct shared-view +wrapper resolution through the base tensor. Both builds and diff checks pass; +the final native GPU suite passes 8/8 and the final small-model slot/checkpoint +suite passes all 50 comparisons. + +The final restored-kernel confirmation (including shared-view correction and +whole-network input-overlap guard) measures **29.013 / 27.983 / 27.103 +tokens/s**, mean **28.033**, with mean prompt processing 933.60 tokens/s. +All primary/repeated output matches rotation-only/control, and four concurrent +requests complete 96 tokens. It shows the same declining-throughput pattern as +the compute experiment after its kernels were reverted. Thus the earlier 3.01% +rotation comparison is a measured sample, **not an established sustained gain** +for the final build; nor can the compute experiment's decline be confidently +attributed to its kernel changes. Copy removal is independently verified, but +the desired stable 30 tokens/s non-MTP target is not achieved. GPU power/clock, +thermal state and other run variation were not captured; those are possible +confounders, not proven causes. Keep the simpler original compute kernels until +a controlled repeated comparison establishes a model-scale benefit. + +Next concrete kernel work should compare fresh steady T1/T3/T128 profiles after +copy removal, separate active recurrence from preserved-row traffic, then test +a coalesced GDN state schedule and a tiled convolution prefill schedule. Capture +GPU frequency/power alongside interleaved controls. Retain arbitrary reset, +reorder, snapshot and immutable-read semantics throughout. + +## 2026-10-22: MTP prefill path and Vulkan comparison + +The retained implementation still uses two native operations per recurrent layer, +with 30 of each in the target trunk. `RecurrentConvCache` fuses reset/history +read/convolution/reorder/window writeback; `RecurrentGatedDeltaNet` fuses +reset/state read/GDN/reorder/snapshot writeback. Their second outputs are the +complete updated caches. Current/spare device-USM binding removes the separate +large output-to-caller cache copies, but the kernels still read and materialize +preserved cache rows. This is generic stateless execution, including multiple +slots, arbitrary runtime metadata and rollback. + +The computation schedules have not been replaced with the optimized paged +kernels: GDN uses the reference K=128, float8, four-value-block recurrence with +a sequential token loop, and convolution uses direct FP32 accumulation over +the history taps. Long-prefill convolution has coalesced token reads. The later +vector cache load/store and convolution-unrolling experiments remain reverted; +their isolated improvements did not establish a whole-model decode benefit. + +### What enabling MTP adds during prefill + +For Qwen3.5/Qwen3.6 in llama.cpp, the single trained MTP block has a separate +context and attention cache. It is reused autoregressively to produce two +proposals; there are not two independent trained MTP blocks. During prefill: + +1. The target evaluates the prompt and exports every `h_nextn` hidden row. + `llama_set_embeddings_nextn(ctx_tgt, true, false)` requests unmasked rows. + `src/llama-context.cpp` extracts them into a host F32 buffer through + `ggml_backend_tensor_get_async`. At width 2048, 1024 tokens total **8 MiB**. +2. `common_speculative_impl_draft_mtp::process` pairs each token with the + preceding target hidden row, copies these rows into the draft batch, and runs + `llama_process(ctx_dft, DECODE, ...)` over the processed prompt. This catches + up the separate MTP cache and executes its projection, attention and MoE. + Prompt catch-up does not request vocabulary logits for every position. +3. The target recurrent graph also enables rollback storage throughout prefill. + With two draft tokens, `build_recurrent_attn` requests three snapshot slots + and writes only the newest `min(T,3)` states; convolution similarly keeps + three windows. Four allocated recurrent rows become twelve, increasing the + cache payload from **251.25 to 753.75 MiB**. The fused full-cache contract + therefore retains extra preservation/writeback work even during prefill. + +Both modes currently default to fused GDN. The slowdown should not be described +as non-MTP choosing chunked GDN while MTP alone switches to sequential GDN. +Nor does snapshot mode save all 1024 intermediate states: it keeps only the +newest three. Export/catch-up and snapshot/cache work are established extra +operations; their individual contributions to prompt latency have not yet been +isolated with phase-specific timing. + +The response JSON `timings.prompt_ms` ends at first-token sampling: +`server-context.cpp` updates `slot.stats` after `common_speculative_process`. +It includes target prefill, draft catch-up, hidden transfers, checkpoint work +and first sampling. The earlier `metrics_post_decode` update precedes draft +catch-up, so aggregate server metrics have a different timing boundary. Use +response timings consistently for this comparison. Cold compilation/first-use +effects are separate from warmed inference; one short warmup does not prove all +subsequent shape/state costs are warm. + +### Measurements + +Vulkan was rebuilt as **Release** in `build/VulkanPerf08` from the current +worktree (base HEAD `049f55449`). The matched server uses the same UD GGUF, +saved 1024-token prompt, `-np 4 -c 8192 -t 2 -tb 2`, batch 2048/ubatch 512, +automatic flash attention, one active request, eight-token warmup and three +512-output requests. Every measured response reports `cache_n=0`, +`prompt_n=1024`, `predicted_n=512`. GPU tests run serially. + +The local Vulkan source contains an unconditional `dump_cgraph` call on every +graph execution. A benchmark-only `LD_PRELOAD` shim replaces that function with +a no-op, leaving source files unchanged. No graph dump is produced in these +primary runs. This avoids including diagnostic file formatting/I/O in the +comparison. Initial runs with dumping enabled are retained as diagnostics: +non-MTP averaged 504.64 prompt / 21.60 decode tokens/s, MTP 500.96 / 37.05. +Decode varied substantially without the shim; these separate runs cannot +attribute that entire difference solely to dumping. + +| Backend / mode | Prompt tokens/s, three requests | Mean prompt tokens/s | Mean prompt ms | Mean decode tokens/s | +| --- | ---: | ---: | ---: | ---: | +| OV, rotation-only non-MTP, previous round | 932.34 / 922.52 / 919.67 | 924.84 | 1107.25 | 28.921 | +| OV, rotation-only MTP, previous round | 675.62 / 865.54 / 873.12 | 804.76 | 1290.51 | 47.935 | +| OV, final restored-kernel non-MTP, previous round | 940.44 / 934.08 / 926.27 | 933.60 | 1096.88 | 28.033 | +| Vulkan, graph dump disabled, non-MTP | 523.23 / 522.04 / 521.28 | 522.18 | 1961.00 | 31.281 | +| Vulkan, graph dump disabled, MTP | 499.93 / 502.76 / 504.07 | 502.25 | 2038.85 | 46.325 | + +Rates are arithmetic means of per-request rates. OV's rotation-only comparison +has about **13.0% lower mean prompt throughput** with MTP; comparing just its +later two requests gives about **5.6%**, with approximately 66 ms extra mean +prompt time. The first measured MTP request takes 1515.64 ms versus +1183.08/1172.81 ms later, so it materially affects the three-request average; +its precise cause was not instrumented. Vulkan's mean prompt throughput drops +about **3.8%**, adding about 78 ms. Thus additional MTP prefill work exists in +both backends, while this sample does not establish how much of OV's larger +average drop belongs to kernels, transfers, or residual first-use costs. + +Vulkan MTP accepts **323/376** proposals in each measured request versus +OV's **340/340** on this repetitive passage. Each mode's repeated content is +identical. These are the same GGUF but different internal weights: OV uses +`q4_asym64_all` requantization and Vulkan uses the original mixed GGUF types. +They also use different arithmetic. Decode and acceptance are therefore not +a controlled comparison of exactly the same numerical model. OV numbers are +from the preceding round, not newly interleaved controls. + +A separate Vulkan `llama-bench -p 1024 -n 0 -r 3` with the same Release build, +model, default batch/ubatch and graph-dump shim measures **703.79 +/- 6.55 +tokens/s** (samples 711.19/698.74/701.44). This is raw non-MTP trunk prefill +with llama-bench's prompt and single-sequence context, without server checkpoint +and first-sampling overhead; it is not the server's 522 tokens/s metric. +The server creates two context checkpoints per request. Their logged durations +can include waiting for asynchronous inference, so they must not be interpreted +as isolated checkpoint-copy costs. + +Artifacts: `tmp/prefill-comparison-20261022/`, including `comparison.json`, +effective server commands, response JSON, repeated results, logs, raw benchmark +output and the benchmark-only graph-dump shim. The next prefill investigation +should time target inference, hidden extraction, draft catch-up and checkpoint +synchronization separately before assigning the gap to a particular kernel. + + +## Independent in-place cache ops (2026-10-22) + +The opt-in `GGML_OPENVINO_RECURRENT_CACHE_INPLACE=1` adds +`RecurrentConvCacheUpdate` and `RecurrentGatedDeltaNetUpdate` for +Qwen3.5/Qwen3.6 in llama.cpp. The corrected non-MTP path measures **29.001 +rather than 27.875 decode tokens/s (+4.0%)**, with practically unchanged prompt +throughput. With two-token MTP it measures **45.014 rather than 46.345 tokens/s +(-2.9%)**, despite eliminating full-cache copies. The default remains +immutable-source cache rotation. + +This round adds independent op classes, registration, a GPU primitive and +kernels, type/serialization tests, and operation specifications. Existing +OpenVINO op contracts and computation kernels receive no further modifications. +Shared plugin code adds safe output binding and cache precision preservation +for the new primitive; earlier local work on existing ops is preserved. + +### Implementation and buffer ownership + +Each recurrent layer emits two ops with computation output 0 and full-cache +output 1. Eligible Parameter and Result bindings share one caller-owned **GPU +device-USM allocation**. The new ops write that allocation directly, eliminating +the spare output bank and final full-cache copy. An exclusive chain of optimized, +memory-identical cache views/Reshapes is allowed. Independent readers of the +cache root, incompatible layouts, or unrelated/partial input overlaps reject +alias binding and use private output storage with any required final copy. +Static/stateful/split paths retain their existing handling. + +Two ordered kernels execute for each aliased op: + +1. Gather active original rows and nonidentity reorder sources into private + device scratch, applying logical source reset and computation-precision + rounding. All reads finish before cache writes begin. Identity reorder + rows require no scratch write. This supports arbitrary cycles and duplicate + sources without imposing single-slot or no-rollback assumptions. +2. Compute convolution/GDN and perform reset, reorder, and ordered writeback in + the original cache. Each destination element has one writer; GDN retained-row + workers skip snapshot destinations written by recurrence owners. Later + windows/snapshots retain their original precedence. Distinct input/output + allocations use one immutable-source computation/writeback kernel. + +Preserved values still round through computation precision. Untouched rows +therefore remain **read**, while already canonical values avoid stores. This +is not yet an implementation that touches only modified rows. Scratch capacity +is conservatively based on active-map plus full extra-map lengths; removing +one spare bank does not by itself establish lower total allocation size. + +The computation retains the earlier K128/vector-four GDN with a sequential +loop over tokens, and fused FP32 convolution accumulation. It does not yet +substitute the optimized paged GDN or causal-convolution kernels. The plugin +already has input-mutating implementations for paged GDN, paged causal +convolution, and KV updates; this work supplies the generic llama.cpp map/cache +contract and binding. Command replay is conservatively disabled for these new +ops because stage selection depends on runtime aliasing; the normal dynamic +graph already cannot use full command replay. A failed aliased inference may +partly update the cache, so callers must restore or clear it before retrying. + +### Matched target-model measurements + +All runs use `Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, GPU, `q4_asym64_all`, native +softplus and disabled KV slicing; `llama-server -np 4 -c 8192 -t 2 -tb 2` receives +the same saved 1,024 prompt token IDs and generates exactly 512 greedy tokens. +Prompt caching is disabled and EOS ignored. An eight-token request warms the +same prompt length, followed by three sequential timed requests and four varied +concurrent 96-token requests. These are single-active-request throughput results +on a four-slot server; the concurrent requests are functional checks. + +| Final path | Decode tokens/s, three requests | Mean decode tokens/s | Mean prompt tokens/s | +| --- | ---: | ---: | ---: | +| Default rotation, non-MTP | 28.565 / 27.901 / 27.157 | 27.875 | 925.35 | +| Corrected in-place, non-MTP | 29.044 / 28.945 / 29.013 | 29.001 | 922.12 | +| Default rotation, two-token MTP | 46.593 / 47.063 / 45.380 | 46.345 | 865.50 | +| Corrected in-place, two-token MTP | 44.975 / 44.963 / 45.102 | 45.014 | 839.60 | + +MTP acceptance is **340/340** in all three requests in both paths, and greedy +content matches the rotation control. Mean MTP prompt latency is 1,219.66 ms +in-place versus 1,183.14 ms rotation (+3.1%). Both modes complete the four +concurrent requests. The in-place path remains opt-in because its modest +non-MTP benefit is accompanied by a small MTP regression. + +Cold model loading and +requantization take several minutes and are excluded from these response +timings. The runs are separate process-level samples, so the modest non-MTP +gain should not be treated as an exact kernel-only speedup. **30 non-MTP +tokens/s has not been reached.** + +### Transfer evidence and alias-view correction + +The corrected full-model decode probe finds **zero device-to-device cache +copies**, compared with **60 copies / 263,454,720 bytes (251.25 MiB)** when the +new ops fall back to private output storage. It observes 1,080 kernel submissions +per trunk decode rather than 1,020: removing the copies adds 60 gather kernels +(two recurrent ops in each of 30 recurrent layers). Small metadata transfers +and 21 `clFinish` calls remain. Ordinary warmed non-MTP decode uploads are eight +host metadata copies totaling 2,608 bytes and twenty host-USM copies totaling +320 bytes; three host output copies total 1,009,664 bytes. Eliminating cache +copies does not eliminate all transfers or synchronization. + +The MTP probe also finds **zero device-to-device cache copies**, across all 26 +instrumented trunk/draft inferences. All 60 recurrent cache roots have identical +input/output USM addresses in both modes. The runtime graph contains 60 Update +primitives in the trunk; the Qwen MTP layer uses full attention and has no +recurrent Update primitive. Warmed three-token trunk verification observes +1,131 kernel submissions and about 46.0–46.9 ms raw inference; each single-token +draft inference observes 68 submissions and about 6.2–6.4 ms. The interleaved +58-submission / 1.8–1.9 ms draft graph catches up the accepted hidden states. +These diagnostic timings come from a short probe request and are not substituted +for the three measured response timings. + +The extra gather launches, retained-row reads, and scratch traffic mean that +zero final copies need not yield higher MTP t/s. The isolated larger-cache GDN +gain below does not explain or predict the full-model regression by itself; +the current measurements do not isolate its exact cause. + +The first full-model opt-in samples were **fallback execution**, despite native +tests exercising real aliasing. llama.cpp inserts an optimized cache Reshape; +the initial overlap check incorrectly classified its root Parameter as an +unrelated overlapping input. The corrected check follows only exclusive, +memory-identical optimized alias steps and still vetoes independent root +readers. Native tests and a full-model device transfer probe cover this case. + +For provenance, the pre-fix samples were 28.625 non-MTP and 42.600 MTP decode +tokens/s, and a later pre-fix armed non-MTP sample was 27.774. Their measurements +remain in the artifacts, but **they do not measure true in-place execution** +and are excluded from the final comparison table. + +### Correctness and isolated kernel checks + +Ten new native/core/visitor tests pass. They compare against separate immutable +reference graphs and cover cyclic maps, duplicates, identity suffixes, +reset-before-gather, overlapping windows/snapshots, snapshot counts 1/3, +changing batches/token counts, I32/I64 controls, F16/F32 caches and computation, +alternating aliased/distinct bindings, export/import, unrelated input overlaps, +and exclusive cache Reshapes with shared-root rejection. Twelve existing native +regression tests also pass after the final shared binding change. + +The four-slot small-model replay suite passes **50 comparisons**, including +reset/copy, rollback depths 0/2, checkpoint export/import, and clears. Maximum +relative logit error is **0.003044** against the existing 0.01 threshold. The +corrected full-model non-MTP and MTP samples have identical greedy content to +their rotation controls and all four concurrent 96-token requests complete. + +An isolated GDN sweep uses H32/K128/V128, device-USM input/output, separate +output storage for rotation and identical input/output storage for Update, +eight warmups and 200 inferences. Values begin in the computation-precision +canonical form. The large model was loading on CPU, with no concurrent model +generation during the sweep. + +| Stored rows / tokens / snapshot count | Rotation ms | In-place Update ms | +| --- | ---: | ---: | +| 4 / 1 / 1 | 0.1904 | 0.1711 | +| 4 / 3 / 1 | 0.1807 | 0.1790 | +| 12 / 3 / 3 | 0.4309 | 0.3278 | + +The twelve-row snapshot case improves about 24%; the four-row/three-token case +has little gain. This single synthetic wall-time sweep supports the expected +memory-traffic benefit for larger caches, without predicting whole-model t/s. + +### Remaining opportunities and reproduction + +The next independent-op improvements should target full retained-row scans and +scratch capacity, coalesced state accesses/register pressure in GDN, and +prefill-appropriate computation. Any precision change must explicitly account +for retained-row rounding and MTP acceptance. Small metadata transfers and host +synchronization remain separate costs. Improvements to the new kernels should +be benchmarked with reset/reorder/rollback intact. + +Artifacts are in `tmp/recurrent-inplace-20261022/`: `bench.py`, effective commands, +response/repeat/parallel JSON, logs, `comparison.json`, native/replay tests, +`microbench-final.log`, and transfer probes/runtime graphs. The probe is armed +only after all three timed requests; primary timings contain no transfer +recording or runtime graph dumps. Reproduce the corrected measurements with: + +```sh +python3 tmp/recurrent-inplace-20261022/bench.py fixed-inplace-normal-armed +python3 tmp/recurrent-inplace-20261022/bench.py fixed-inplace-mtp-armed +python3 tmp/recurrent-inplace-20261022/summary.py +``` + +For direct use, retain the established model/environment settings and add: + +```sh +export GGML_OPENVINO_RECURRENT_CACHE_INPLACE=1 +``` + +Capability detection and translation cache revision 9 require regeneration of +older compiled-model blobs. Detailed operation contracts are in OpenVINO's +`recurrent-conv-cache-update.rst` and `recurrent-gated-delta-net-update.rst`. + +## Direct frontend integration and branch split (2026-10-22) + +The current backend emits the two fused recurrent operations directly from +complete GGML reset/reorder/computation/writeback groups. It no longer emits +`RecurrentStateGather`, `RecurrentStateUpdate`, or the eight-input history-only +`RecurrentConvCache`, and the prepared-cache elimination pass is removed. +The dated measurements above describe the preceding implementations, not new +measurements of this cleanup. + +The matcher verifies exclusive state consumers, depthwise convolution geometry, +ordered history windows and canonical GDN state writeback. Unmatched groups, +CPU/static/stateful/split execution and runtimes without the fused operations +use the ordinary GGML op translations. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` +selects that decomposition for debugging. The old `DISABLE_RECURRENT_CACHE` and +`DISABLE_CACHE_PREPARE_FUSION` switches have been removed. Rotation is the default; +`GGML_OPENVINO_RECURRENT_CACHE_INPLACE=1` selects the separate Update operations +when the runtime supports them. Translation revision **10** invalidates old blobs. + +OpenVINO branches start at clean upstream master `178d03e210`: + +- `qwen-mtp-recurrent-fused-rotation`: `8568b33cf4`, rotation and its snapshot foundation. +- `qwen-mtp-recurrent-fused-inplace`: `3023daedef`, stacked on rotation, adding Update ops. +- `qwen-mtp-openvino-checkpoint`: the combined in-place tip used by `build/MtpOVPerf`. + +The in-place change depends on rotation's core shape validation and reference +operations; it is a stacked alternative rather than an independent master branch. +The earlier checkpoint is preserved as +`backup/qwen-mtp-openvino-checkpoint-20261022` (`934cd6492f`). + +After rebasing, the Release CPU/GPU plugins build and all **27** core, attribute +and GPU tests pass (17 rotation, 10 in-place). Both frontend paths pass **50** +four-slot small-model comparisons with reset, copy, checkpoint export/import, +clear, changing batches and rollback depths 0/2. The rotation IR contains 18 +`RecurrentConvCache` and 18 `RecurrentGatedDeltaNet` operations and no standalone +native gather/update operations. Logs are in `tmp/ov-branch-split-20261022/` and +`tmp/qwen-finalize-20261022/`. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 517764ae0f84..4154e10111e2 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1419,11 +1419,10 @@ void GgmlOvDecoder::add_extra_inputs() { create_1d_input("rs_snapshot_stride_" + node_name, writeback.snapshot_stride); } } -#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE m_compute_params.recurrent_controls.clear(); if (!m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && - !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_RECURRENT_CACHE")) { -#ifdef GGML_OPENVINO_HAS_STATE_UPDATE + !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { for (int i = 0; i < m_cgraph->n_nodes; ++i) { const auto node = m_cgraph->nodes[i]; const auto op_case = m_node_info_list[i].node_op_case; @@ -1432,7 +1431,6 @@ void GgmlOvDecoder::add_extra_inputs() { {ov::element::i64, ov::Shape{1, 1, 1, 4}, 0, true, {}, -1}; } } -#endif for (const auto & [name, write] : m_compute_params.rs_writebacks) { if (write.src_begin >= 0) { auto & values = m_compute_params.recurrent_controls["rs_offsets_" + name]; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 74ba6251eca8..bb648eae1388 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -129,7 +129,9 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_ENABLE_CACHE", "GGML_OPENVINO_DISABLE_CACHE", "GGML_OPENVINO_DISABLE_KV_SLICE", - "GGML_OPENVINO_DISABLE_RECURRENT_CACHE", + "GGML_OPENVINO_DISABLE_FUSED_RECURRENCE", + "GGML_OPENVINO_DISABLE_CACHE_ROTATION", + "GGML_OPENVINO_RECURRENT_CACHE_INPLACE", "GGML_OPENVINO_ENABLE_FALLBACK", "GGML_OPENVINO_MANUAL_GQA_ATTN", "GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN", @@ -673,7 +675,8 @@ ggml_openvino_tensor_extra * ggml_openvino_create_tensor_extra(const ggml_tensor if (is_remote) { GGML_ASSERT(ggml_openvino_is_gpu()); auto gpu_context = remote_context->as(); - auto usm_tensor = gpu_context.create_tensor(element_type, shape, tensor->data); + auto usm_tensor = gpu_context.create_tensor(element_type, shape, + ggml_openvino_buffer_resolve_data(tensor, 0, ggml_nbytes(tensor))); ov_tensor = std::make_shared(std::move(usm_tensor)); } else { ov_tensor = std::make_shared(element_type, shape, tensor->data); diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 9b42ac721068..4379a1f27dad 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -220,6 +220,13 @@ ggml_openvino_tensor_extra * ggml_openvino_create_tensor_extra(const ggml_tensor // Check if a tensor's buffer uses remote (device) memory (e.g. GPU USM) bool ggml_openvino_buffer_is_remote(const ggml_tensor * tensor); +// Logical GGML addresses remain stable when recurrent GPU cache allocations rotate. +// Resolve root/view ranges through the owning buffer, including checkpoint I/O. +void * ggml_openvino_buffer_resolve_data(const ggml_tensor * tensor, size_t offset = 0, size_t size = 0); +void * ggml_openvino_buffer_resolve_address(const ggml_tensor * tensor, const void * logical, size_t size); +std::optional ggml_openvino_buffer_prepare_cache_output(ggml_tensor * tensor); +void ggml_openvino_buffer_commit_cache_output(ggml_tensor * tensor); + // Register an extra with the tensor's OpenVINO buffer context for proper lifetime management. // This sets tensor->extra and tracks the extra in the buffer context for cleanup. void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_extra_base * extra); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 1efa1b30aac2..a9ebfa8cd76e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -80,6 +80,31 @@ struct ggml_backend_openvino_buffer_context { // Wrapping of the buffer std::shared_ptr ov_buffer; + // Stable logical GGML address -> current/spare immutable device cache storage. + // Kept by the buffer, not an InferRequest, so checkpoints, views and a newly + // compiled graph all see the latest state. Publish only after successful infer. + struct cache_storage { + size_t size; + ov::intel_gpu::ocl::USMTensor current; + ov::intel_gpu::ocl::USMTensor spare; + bool pending = false; + }; + + std::map cache_allocations; + + void * resolve(const void * logical, size_t bytes) { + const auto address = reinterpret_cast(logical); + auto it = cache_allocations.upper_bound(address); + if (it != cache_allocations.begin()) { + --it; + const auto delta = address - it->first; + if (delta <= it->second.size && bytes <= it->second.size - delta) { + return static_cast(it->second.current.get()) + delta; + } + } + return const_cast(logical); + } + // Track all extras for cleanup std::map tensor_extras; std::map weight_fingerprints; @@ -394,8 +419,8 @@ static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buf auto mem_fill_fn = ggml_openvino_get_clEnqueueMemFillINTEL(); if (mem_fill_fn != nullptr) { uint8_t pattern = value; - cl_int err = mem_fill_fn(queue, (char *) tensor->data + offset, &pattern, sizeof(pattern), size, 0, nullptr, - nullptr); + cl_int err = mem_fill_fn(queue, ctx->resolve((char *) tensor->data + offset, size), &pattern, + sizeof(pattern), size, 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemFillINTEL failed with error %d\n", __func__, err); } @@ -499,8 +524,8 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer cl_command_queue queue = ggml_openvino_get_cl_queue(); auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL(); if (mem_cpy_fn != nullptr) { - cl_int err = - mem_cpy_fn(queue, CL_TRUE, (char *) tensor->data + offset, data, size, 0, nullptr, nullptr); + cl_int err = mem_cpy_fn(queue, CL_TRUE, ctx->resolve((char *) tensor->data + offset, size), data, size, + 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL failed with error %d\n", __func__, err); } @@ -544,8 +569,8 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer cl_command_queue queue = ggml_openvino_get_cl_queue(); auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL(); if (mem_cpy_fn != nullptr) { - cl_int err = - mem_cpy_fn(queue, CL_TRUE, data, (const char *) tensor->data + offset, size, 0, nullptr, nullptr); + cl_int err = mem_cpy_fn(queue, CL_TRUE, data, ctx->resolve((const char *) tensor->data + offset, size), + size, 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL failed with error %d\n", __func__, err); } @@ -574,7 +599,8 @@ static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer } // Can copy from host to device if (ggml_backend_buffer_is_host(src->buffer)) { - cl_int err = mem_cpy_fn(queue, CL_TRUE, dst->data, src->data, ggml_nbytes(src), 0, nullptr, nullptr); + cl_int err = mem_cpy_fn(queue, CL_TRUE, ggml_openvino_buffer_resolve_data(dst, 0, ggml_nbytes(src)), + src->data, ggml_nbytes(src), 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL (host-to-device) failed with error %d\n", __func__, err); return false; @@ -586,7 +612,9 @@ static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer ggml_backend_openvino_buffer_context * src_ctx = (ggml_backend_openvino_buffer_context *) src->buffer->context; if (src_ctx->is_remote) { - cl_int err = mem_cpy_fn(queue, CL_TRUE, dst->data, src->data, ggml_nbytes(src), 0, nullptr, nullptr); + cl_int err = mem_cpy_fn(queue, CL_TRUE, ggml_openvino_buffer_resolve_data(dst, 0, ggml_nbytes(src)), + ggml_openvino_buffer_resolve_data(src, 0, ggml_nbytes(src)), ggml_nbytes(src), + 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL (device-to-device) failed with error %d\n", __func__, err); return false; @@ -618,6 +646,17 @@ static void ggml_backend_openvino_buffer_clear(ggml_backend_buffer_t buffer, uin GGML_LOG_WARN("%s: clEnqueueMemFillINTEL failed with error %d\n", __func__, err); } clFinish(queue); + // The original allocation remains the logical address space, while + // current rotated roots may live elsewhere. Clear both banks too. + for (auto & [address, storage] : ctx->cache_allocations) { + for (auto bank : {storage.current, storage.spare}) { + mem_fill_fn(queue, bank.get(), &pattern, sizeof(pattern), storage.size, 0, nullptr, nullptr); + } + storage.pending = false; + } + if (!ctx->cache_allocations.empty()) { + clFinish(queue); + } } else { GGML_LOG_WARN("%s: clEnqueueMemFillINTEL not available for GPU buffer clear\n", __func__); } @@ -809,6 +848,60 @@ bool ggml_openvino_buffer_is_remote(const ggml_tensor * tensor) { return ctx->is_remote; } +void * ggml_openvino_buffer_resolve_data(const ggml_tensor * tensor, size_t offset, size_t size) { + const auto * logical = static_cast(tensor->data) + offset; + return ggml_openvino_buffer_resolve_address(tensor, logical, size); +} + +void * ggml_openvino_buffer_resolve_address(const ggml_tensor * tensor, const void * logical, size_t size) { + if (!ggml_openvino_buffer_is_remote(tensor)) { + return const_cast(logical); + } + auto * ctx = static_cast(tensor->buffer->context); + return ctx->resolve(logical, size); +} + +std::optional ggml_openvino_buffer_prepare_cache_output(ggml_tensor * tensor) { + if (!ggml_openvino_buffer_is_remote(tensor) || tensor->view_src || !ggml_is_contiguous(tensor) || + !GgmlOvDecoder::is_recurrent_cache(tensor) || ggml_nbytes(tensor) == 0) { + return std::nullopt; + } + auto * ctx = static_cast(tensor->buffer->context); + const auto address = reinterpret_cast(tensor->data); + const auto bytes = ggml_nbytes(tensor); + auto found = ctx->cache_allocations.find(address); + if (found == ctx->cache_allocations.end()) { + // Reject overlapping logical roots; views are resolved within one root. + for (const auto & [begin, storage] : ctx->cache_allocations) { + if (address <= begin ? begin - address < bytes : address - begin < storage.size) { + return std::nullopt; + } + } + auto context = ggml_openvino_get_remote_context()->as(); + const auto type = GgmlOvDecoder::get_ov_type(tensor); + const auto shape = GgmlOvDecoder::get_shape(tensor); + auto current = context.create_tensor(type, shape, tensor->data); + auto spare = context.create_usm_device_tensor(type, shape); + found = ctx->cache_allocations + .emplace(address, ggml_backend_openvino_buffer_context::cache_storage{bytes, current, spare}) + .first; + } + auto & storage = found->second; + if (storage.size != bytes) { + return std::nullopt; + } + storage.pending = true; + return storage.spare; +} + +void ggml_openvino_buffer_commit_cache_output(ggml_tensor * tensor) { + auto * ctx = static_cast(tensor->buffer->context); + auto & storage = ctx->cache_allocations.at(reinterpret_cast(tensor->data)); + GGML_ASSERT(storage.pending); + std::swap(storage.current, storage.spare); + storage.pending = false; +} + void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_extra_base * extra) { GGML_ASSERT(tensor != nullptr); GGML_ASSERT(tensor->buffer != nullptr); diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp index f68b652601c7..31605ca54126 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -1,12 +1,6 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" -#ifdef GGML_OPENVINO_HAS_STATE_UPDATE -# include "recurrent_cache.hpp" - -# include -#endif - #include #include #include @@ -41,52 +35,6 @@ OutputVector translate_cpy(const NodeContext & context) { auto input_shape = context.get_input_shape(0); auto output_shape = context.get_input_shape(1); -#ifdef GGML_OPENVINO_HAS_STATE_UPDATE - if ((op_case == 10 || op_case == 12) && context.has_input("rs_update_" + context.get_name())) { - auto feature = ov::op::v0::Constant::create(ov::element::i64, {4}, - std::vector{1, 1, -1, output_shape[3].get_length()}); - auto source = context.get_input(0); - int64_t key_size = 0, value_size = 0; - // Direct non-snapshot state is the native GDN state followed by its GGML-layout transpose. - const auto transpose = ov::as_type_ptr(source.get_node_shared_ptr()); - if (op_case == 10 && transpose) { - const auto order = ov::as_type_ptr(transpose->get_input_node_shared_ptr(1)); - const auto shape = transpose->get_input_partial_shape(0); - if (order && order->cast_vector() == std::vector{0, 1, 3, 2} && shape.rank() == 4 && - shape[2].is_static() && shape[3].is_static()) { - source = transpose->input_value(0); - key_size = shape[2].get_length(); - value_size = shape[3].get_length(); - } - } - if (op_case == 12) { - const auto flat = ov::as_type_ptr(source.get_node_shared_ptr()); - const auto selected = - flat ? ov::as_type_ptr(flat->get_input_node_shared_ptr(0)) : nullptr; - const auto permute = - selected ? ov::as_type_ptr(selected->get_input_node_shared_ptr(0)) : nullptr; - if (permute) { - const auto order = ov::as_type_ptr(permute->get_input_node_shared_ptr(1)); - const auto axis = ov::as_type_ptr(selected->get_input_node_shared_ptr(2)); - const auto shape = permute->get_input_partial_shape(0); - if (order && axis && axis->cast_vector() == std::vector{0} && - selected->get_batch_dims() == 0 && - order->cast_vector() == std::vector{0, 1, 2, 4, 3} && shape.rank() == 5 && - shape[3].is_static() && shape[4].is_static()) { - source = std::make_shared(permute->input_value(0), selected->input_value(1), - selected->input_value(2)); - key_size = shape[3].get_length(); - value_size = shape[4].get_length(); - } - } - } - auto states = std::make_shared(source, feature, false); - auto update = std::make_shared( - ov::OutputVector{context.get_input(1), states, context.get_input("rs_update_" + context.get_name())}, - key_size, value_size); - return rename_outputs_with_suffix({update}, context.get_name()); - } -#endif if (op_case == 11 || op_case == 12) { auto base = context.get_input(1); auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {2}); diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index 8fe5607f825b..1a18a659bd3d 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -3,8 +3,11 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" -#ifdef GGML_OPENVINO_HAS_STATE_UPDATE -# include "recurrent_cache.hpp" +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#include "recurrent_cache.hpp" +#endif +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE +#include "recurrent_cache_update.hpp" #endif #include "ggml-openvino/ggml-openvino-extra.h" @@ -99,7 +102,7 @@ static bool match_gdn_l2_norm(const Output & normalized, Output & in return true; } -OutputVector translate_gated_delta_net(const NodeContext & context) { +static OutputVector translate_gdn(const NodeContext & context, const OutputVector * cache_inputs) { auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v] auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k] @@ -154,43 +157,7 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { // ggml state layout (OV notation): [B, H_v, value_dim, key_dim] // GatedDeltaNet op expects: [B, H_v, key_dim, value_dim] auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{0, 1, 3, 2}); - bool gathered_native_layout = false; -#ifdef GGML_OPENVINO_HAS_STATE_UPDATE - // The native gather owns an immutable cache read and a separate prepared-cache output. - // Bypass the redundant active-prefix slice and transpose only for its active output. - const auto reshape = ov::as_type_ptr(state.get_node_shared_ptr()); - auto active = reshape ? reshape->input_value(0) : state; - if (auto slice = ov::as_type_ptr(active.get_node_shared_ptr())) { - if (auto producer = - ov::as_type_ptr(slice->get_input_node_shared_ptr(0))) { - const auto begin = ov::as_type_ptr(slice->get_input_node_shared_ptr(1)); - const auto axis = ov::as_type_ptr(slice->get_input_node_shared_ptr(4)); - const auto stride = ov::as_type_ptr(slice->get_input_node_shared_ptr(3)); - if (begin && axis && stride && stride->cast_vector() == std::vector{1} && - slice->input_value(2) == context.get_input("s_copy_active_slot_len") && - begin->cast_vector() == std::vector{0} && - axis->cast_vector() == std::vector{2} && slice->input_value(0).get_index() == 0) { - active = slice->input_value(0); - } - } - } - const auto gather = ov::as_type_ptr(active.get_node_shared_ptr()); - const auto shape = state.get_partial_shape(); - // Changing the gather's layout is safe only when its active output has this one consumer. - const auto targets = gather ? gather->output(0).get_target_inputs() : std::set>{}; - const bool exclusive = targets.size() == 1; - if (gather && exclusive && active.get_index() == 0 && gather->get_key_size() == 0 && reshape && shape.rank() == 4 && - shape[2].is_static() && shape[3].is_static()) { - const auto key_size = shape[3].get_length(), value_size = shape[2].get_length(); - gather->set_matrix_shape(key_size, value_size); - gather->validate_and_infer_types(); - auto pattern = - ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{-1, H_v, key_size, value_size}); - state = std::make_shared(gather->output(0), pattern, false); - gathered_native_layout = true; - } -#endif - if (!gathered_native_layout) { + if (!cache_inputs) { state = std::make_shared(state, state_perm); } @@ -223,6 +190,31 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { // << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape() // << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl; +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE + if (cache_inputs) { + OutputVector args{q, k, v, (*cache_inputs)[0], g, beta}; + args.insert(args.end(), cache_inputs->begin() + 1, cache_inputs->end()); + std::shared_ptr fused; +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE + if (ggml_openvino_getenv_int("GGML_OPENVINO_RECURRENT_CACHE_INPLACE")) { + fused = std::make_shared( + args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); + } else +#endif + { + fused = std::make_shared( + args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); + } + fused->set_friendly_name(context.get_name() + "/RecurrentGatedDeltaNet"); + // The matched state VIEW is consumed only by the overridden full-cache + // writeback. Route that cache directly instead of materializing snapshots. + if (context.get_output_names().size() == 3) { + return {fused->output(0), fused->output(0), fused->output(1)}; + } + return {fused->output(0), fused->output(1)}; + } +#endif + auto gdn = std::make_shared(q, k, v, state, g, beta, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); auto attn_4d = gdn->output(0); @@ -274,6 +266,16 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { return rename_outputs_with_suffix({res}, context.get_name()); } +OutputVector translate_gated_delta_net(const NodeContext & context) { + return translate_gdn(context, nullptr); +} + +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs) { + return translate_gdn(context, &cache_inputs); +} +#endif + static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { num_inputs_check(context, 6, 6); diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp index 239e81f47b9d..6e68482591a4 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.hpp @@ -76,6 +76,14 @@ class OPENVINO_API GatedDeltaNet : public ov::op::Op { m_snapshot_count = snapshot_count; } +protected: + // Initialize the inherited attributes before validating the cache-aware variant. + void initialize_attributes(bool norm, float qe, float ke, int64_t count) { + m_fuse_qk_l2norm = norm; + m_q_l2_norm_eps = qe; + m_k_l2_norm_eps = ke; + m_snapshot_count = count; + } private: bool m_fuse_qk_l2norm = false; float m_q_l2_norm_eps = 1e-6F; diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp index b7b09bce759f..ef2f217d2a93 100644 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp @@ -2,71 +2,43 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once +#include "gated_delta_net.hpp" #include "openvino/op/op.hpp" +// Internal OpenVINO developer API mirror for Qwen3.5/Qwen3.6 in llama.cpp. +// Keep declarations and class layouts in sync with the patched OpenVINO runtime. +// Port/precedence contracts: dev_doc/OPENVINO-RECURRENT-CACHE.md and OV developer header. namespace ov::op::internal { -// Immutable cache [1,1,slots,features]. All indices/offsets are runtime i32/i64 tensors. -// Gather inputs: cache, active source rows, extra source rows, reset begin, reset length, -// extra offsets [destination begin, source begin]. Extra source rows can be -// a nonempty shared row map; the source offset selects its suffix, including empty suffixes. -// Outputs: active rows and reset/reordered cache. Row indices and offsets must be in bounds. -// Positive key_size/value_size transpose each active matrix from [value,key] to [key,value]; -// the prepared full cache keeps its original layout. -// Inputs and outputs must not alias: reorder maps may contain cycles and duplicate sources. -class OPENVINO_API RecurrentStateGather : public ov::op::Op { - public: - OPENVINO_OP("RecurrentStateGather"); - RecurrentStateGather() = default; - RecurrentStateGather(const OutputVector &args, int64_t key_size = 0, int64_t value_size = 0); - void validate_and_infer_types() override; - bool visit_attributes(AttributeVisitor &visitor) override; - std::shared_ptr clone_with_new_inputs(const OutputVector &args) const override; - int64_t get_key_size() const { return m_key_size; } - int64_t get_value_size() const { return m_value_size; } - void set_matrix_shape(int64_t key_size, int64_t value_size) { - m_key_size = key_size; - m_value_size = value_size; - } - - private: - int64_t m_key_size = 0, m_value_size = 0; -}; -// Immutable cache and flattened state rows [1,1,N,F]; control [1,1,1,4] -// is (destination begin, sequence count, snapshot stride, source row begin). -// Output is the full cache. Later source rows win if destination planes overlap. -// Sequence count must be positive, stride nonnegative, and source begin in [0,N]. -// All selected destination rows must be in bounds. Kernel source/output allocations must not alias. -// Positive matrix dimensions convert source [head,key,value] to cache [head,value,key]. -class OPENVINO_API RecurrentStateUpdate : public ov::op::Op { - public: - OPENVINO_OP("RecurrentStateUpdate"); - RecurrentStateUpdate() = default; - RecurrentStateUpdate(const OutputVector &args, int64_t key_size = 0, int64_t value_size = 0); - void validate_and_infer_types() override; - bool visit_attributes(AttributeVisitor &visitor) override; - std::shared_ptr clone_with_new_inputs(const OutputVector &args) const override; - int64_t get_key_size() const { return m_key_size; } - int64_t get_value_size() const { return m_value_size; } - - private: - int64_t m_key_size = 0, m_value_size = 0; -}; -// Conv inputs: same six inputs, new QKV [1,batch,channels,tokens], windows [1,1,K,2]. -// Each window is (start column in history+tokens, destination row); writes batch rows. -// Starts must lie in [0,tokens]; caller supplies valid-token windows for padded/short batches. -// Windows are applied in order, so the last overlapping write wins. -// Outputs: convolution input [1,batch,channels,history+tokens] and final cache. +// Inputs: original cache, active/extra rows, reset begin/length, extra offsets, +// QKV [1,B,C,T], ordered (window start,destination row) pairs and depthwise +// weights [1,1,C,H+1]. Outputs: convolution [1,B,T,C] and full updated cache_r. +// Original cache reads remain immutable for cyclic row maps. class OPENVINO_API RecurrentConvCache : public ov::op::Op { - public: +public: OPENVINO_OP("RecurrentConvCache"); RecurrentConvCache() = default; - RecurrentConvCache(const OutputVector &args, int64_t history); + RecurrentConvCache(const OutputVector & args, int64_t history); void validate_and_infer_types() override; - bool visit_attributes(AttributeVisitor &visitor) override; - std::shared_ptr clone_with_new_inputs(const OutputVector &args) const override; + bool visit_attributes(AttributeVisitor & visitor) override; + std::shared_ptr clone_with_new_inputs(const OutputVector & args) const override; + int64_t get_history() const { return m_history; } - private: +private: int64_t m_history = 0; }; -} // namespace ov::op::internal + +// Attention and full updated cache_s; generic reset/reorder and MTP snapshot writes. +class OPENVINO_API RecurrentGatedDeltaNet : public GatedDeltaNet { +public: + OPENVINO_OP("RecurrentGatedDeltaNet", "internal", GatedDeltaNet); + RecurrentGatedDeltaNet() = default; + RecurrentGatedDeltaNet(const OutputVector & args, + bool fuse_qk_l2norm = false, + float q_eps = 1e-6f, + float k_eps = 1e-6f, + int64_t snapshot_count = 1); + void validate_and_infer_types() override; + std::shared_ptr clone_with_new_inputs(const OutputVector & args) const override; +}; +} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp new file mode 100644 index 000000000000..4eb79c16d467 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp @@ -0,0 +1,69 @@ +// Copyright (C) 2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include "openvino/op/op.hpp" + +namespace ov::op::internal { +/// Qwen3.5/Qwen3.6 llama.cpp convolution and generic cache_r maintenance. +/// Inputs match the nine-input RecurrentConvCache: original cache, active rows, +/// extra rows, reset begin/length, extra offsets, QKV, windows, depthwise weights. +/// Outputs are convolution [1,B,T,C] and the complete updated [1,1,S,C*history] cache. +/// GPU execution may reuse a caller's identical input/output device allocation only +/// when it is the exclusive cache reader. Required original rows are gathered into +/// device scratch before any reset, reorder or window write, preserving cycles, +/// duplicate sources and later-window precedence. Other bindings retain immutable +/// input semantics. Preserved rows retain the existing computation-precision rounding. +/// A failed in-place inference may partially modify the cache; the caller must +/// clear or restore it before retrying. +class OPENVINO_API RecurrentConvCacheUpdate : public Op { +public: + OPENVINO_OP("RecurrentConvCacheUpdate", "internal"); + RecurrentConvCacheUpdate() = default; + RecurrentConvCacheUpdate(const OutputVector & args, int64_t history); + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor &) override; + std::shared_ptr clone_with_new_inputs(const OutputVector &) const override; + + int64_t get_history() const { return m_history; } + +private: + int64_t m_history = 0; +}; + +/// Qwen3.5/Qwen3.6 llama.cpp GDN and generic cache_s maintenance. +/// Inputs match the twelve-input RecurrentGatedDeltaNet: Q/K/V, cache, gate/beta, +/// active/extra rows, reset begin/length, extra offsets, ordered write control. +/// Outputs are attention [B,T,H,V] and the complete [1,1,S,H*V*K] updated cache. +/// snapshot_count saves only the newest min(T,count) states, newest first. +/// Required active/nonidentity rows are staged on device before computation; +/// identity reorder sources need no scratch copy. +/// GPU input/output aliasing uses staged original rows as described above; +/// distinct allocations keep the immutable-source implementation. Runtime maps, +/// reset, duplicate sources, cycles and overlapping snapshot writes are supported. +class OPENVINO_API RecurrentGatedDeltaNetUpdate : public Op { +public: + OPENVINO_OP("RecurrentGatedDeltaNetUpdate", "internal"); + RecurrentGatedDeltaNetUpdate() = default; + RecurrentGatedDeltaNetUpdate(const OutputVector & args, + bool fuse_qk_l2norm = false, + float q_l2_norm_eps = 1e-6f, + float k_l2_norm_eps = 1e-6f, + int64_t snapshot_count = 1); + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor &) override; + std::shared_ptr clone_with_new_inputs(const OutputVector &) const override; + + bool get_fuse_qk_l2norm() const { return m_fuse_qk_l2norm; } + + float get_q_l2_norm_eps() const { return m_q_l2_norm_eps; } + + float get_k_l2_norm_eps() const { return m_k_l2_norm_eps; } + + int64_t get_snapshot_count() const { return m_snapshot_count; } + +private: + bool m_fuse_qk_l2norm = false; + float m_q_l2_norm_eps = 1e-6f, m_k_l2_norm_eps = 1e-6f; + int64_t m_snapshot_count = 1; +}; +} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index fd2b50d2fabe..ead87a567a4e 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -49,6 +49,9 @@ GGML_OP_CONVERTER(translate_clamp); GGML_OP_CONVERTER(translate_pad); GGML_OP_CONVERTER(translate_ssm_conv); GGML_OP_CONVERTER(translate_gated_delta_net); +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); +#endif GGML_OP_CONVERTER(translate_repeat); GGML_OP_CONVERTER(translate_cumsum); GGML_OP_CONVERTER(translate_fill); diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp index a5516ecbb877..d75a590d787a 100644 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp @@ -1,9 +1,13 @@ -#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE # include "recurrent_cache_fusion.h" # include "../ggml-openvino-extra.h" # include "ggml-impl.h" # include "op/recurrent_cache.hpp" +# include "op_table.h" +# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE +# include "op/recurrent_cache_update.hpp" +# endif # include "utils.h" # include @@ -18,7 +22,7 @@ RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & m_decoder(decoder), m_tensors(tensors) { if (!ggml_openvino_is_gpu() || decoder->is_static() || decoder->is_stateful() || decoder->is_splited_model() || - ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_RECURRENT_CACHE")) { + ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { return; } auto actual = std::dynamic_pointer_cast(decoder); @@ -84,7 +88,56 @@ RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & break; } } - if (group.concat >= 0 && group.snapshots.empty()) { + if (group.concat >= 0) { + if (group.snapshots.empty()) { + continue; + } + for (int j = group.concat + 1; j < graph->n_nodes; ++j) { + const auto node = graph->nodes[j]; + if (node->op == GGML_OP_SSM_CONV && node->src[0] == graph->nodes[group.concat] && node->src[1] && + node->src[1]->op == GGML_OP_NONE && + node->src[1]->ne[0] == graph->nodes[group.concat]->src[0]->ne[0] + 1 && + node->src[1]->ne[1] == graph->nodes[group.concat]->src[0]->ne[1] && node->src[1]->ne[2] == 1 && + node->src[1]->ne[3] == 1) { + if (group.compute >= 0) { + group.compute = -1; + break; + } + group.compute = j; + } + } + } else { + for (int j = i + 1; j < graph->n_nodes; ++j) { + const auto node = graph->nodes[j]; + if (node->op != GGML_OP_GATED_DELTA_NET || !node->src[5] || node->src[5]->op != GGML_OP_RESHAPE) { + continue; + } + const auto active = node->src[5]->src[0]; + if (!active || active->op != GGML_OP_VIEW || active->src[0] != gather || active->view_offs != 0 || + node->src[5]->ne[0] * node->src[5]->ne[1] * node->src[5]->ne[2] != root->ne[0] || + decoder->get_output_names(j).size() < 2) { + continue; + } + group.compute = j; + for (int k = j + 1; k < graph->n_nodes; ++k) { + const auto write = graph->nodes[k]; + if (write->op == GGML_OP_CPY && write->view_src == root && write->src[0] && + write->src[0]->op == GGML_OP_VIEW && write->src[0]->src[0] == node && + (decoder->get_op_case(k) == 10 || decoder->get_op_case(k) == 12)) { + if (group.writeback >= 0) { + group.writeback = -1; + break; + } + group.writeback = k; + } + } + break; + } + if (group.writeback < 0 || !tensors->count("rs_update_" + decoder->get_op_name(group.writeback))) { + continue; + } + } + if (group.compute < 0) { continue; } bool complete = tensors->count("rs_slot_begin_" + decoder->get_op_name(i)) && @@ -93,7 +146,7 @@ RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & const auto & name = decoder->get_op_name(snapshot); complete &= tensors->count("rs_slot_begin_" + name) && tensors->count("rs_src_begin_" + name); } - const int last = group.snapshots.empty() ? i : group.snapshots.back(); + const int last = group.concat < 0 ? group.writeback : std::max(group.compute, group.snapshots.back()); for (int j = group.reset + 1; j <= last && complete; ++j) { const auto node = graph->nodes[j]; // An unrelated cache write cannot be crossed by this fusion. Cache aliases and @@ -111,11 +164,48 @@ RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & } } if (node->view_src == root && (node->op == GGML_OP_SCALE || node->op == GGML_OP_CPY) && - j != group.remainder && + j != group.remainder && j != group.writeback && std::find(group.snapshots.begin(), group.snapshots.end(), j) == group.snapshots.end()) { complete = false; } } + // Every read of the gathered state or convolution input must belong to + // this recurrence. Shared readers retain the ordinary GGML translation. + const auto compute = graph->nodes[group.compute]; + const auto active = group.concat >= 0 ? graph->nodes[group.concat]->src[0]->src[0] : compute->src[5]->src[0]; + const auto reshaped = group.concat >= 0 ? graph->nodes[group.concat]->src[0] : compute->src[5]; + for (int j = group.gather + 1; j < graph->n_nodes && complete; ++j) { + const auto node = graph->nodes[j]; + for (int source = 0; source < GGML_MAX_SRC; ++source) { + const auto input = node->src[source]; + if (!input) { + continue; + } + if (input == gather && node != active && node != graph->nodes[group.remainder]->src[0]) { + complete = false; + } + if (input == active && node != reshaped) { + complete = false; + } + if (input == reshaped && node != (group.concat >= 0 ? graph->nodes[group.concat] : compute)) { + complete = false; + } + if (group.concat >= 0 && input == graph->nodes[group.concat] && node != compute) { + bool window = false; + for (int snapshot : group.snapshots) { + window |= node == graph->nodes[snapshot]->src[0]; + } + complete &= window; + } + if (input == compute && group.concat < 0 && node->op != GGML_OP_VIEW) { + complete = false; + } + if (group.concat < 0 && input == graph->nodes[group.writeback]->src[0] && + node != graph->nodes[group.writeback]) { + complete = false; + } + } + } if (!complete) { continue; } @@ -126,6 +216,10 @@ RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & if (group.concat >= 0) { m_nodes[group.concat] = id; } + m_nodes[group.compute] = id; + if (group.writeback >= 0) { + m_nodes[group.writeback] = id; + } for (int n : group.snapshots) { m_nodes[n] = id; } @@ -169,14 +263,12 @@ OutputVector RecurrentCacheFusion::translate(int index, const NodeContext & cont std::make_shared(rows, constant({1}, {0}), context.get_input("s_copy_active_slot_len"), constant({1}, {1}), constant({1}, {3})); if (index == group.gather) { - auto op = std::make_shared(inputs); - op->set_friendly_name(context.get_name() + "/RecurrentStateGather"); - group.gathered = op->output(0); - group.prepared = op->output(1); - return {group.gathered}; + // Ordinary nodes keep intermediate translation shapes valid. They become + // unreachable once the complete recurrence is replaced by its fused op. + return op::translate_get_rows(context); } if (index == group.remainder) { - return {group.prepared}; + return {group.old_cache}; } if (index == group.concat) { inputs.push_back(process_view_input_new(context, 1)); @@ -191,11 +283,32 @@ OutputVector RecurrentCacheFusion::translate(int index, const NodeContext & cont context.get_input("rs_windows_" + context.get_name()) : std::make_shared(windows, 2)); const auto history = context.get_input_shape(0)[3].get_length(); - auto op = std::make_shared(inputs, history); - op->set_friendly_name(context.get_name() + "/RecurrentConvCache"); - group.conv = op->output(0); - group.updated = op->output(1); - return {group.conv}; + NodeContext compute_context(m_decoder, m_tensors, group.compute); + const auto channels = context.get_input_shape(0)[2].get_length(); + inputs.push_back(std::make_shared(compute_context.get_input(1), + constant({4}, {1, 1, channels, history + 1}), false)); + std::shared_ptr fused; +# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE + if (ggml_openvino_getenv_int("GGML_OPENVINO_RECURRENT_CACHE_INPLACE")) { + fused = std::make_shared(inputs, history); + } else +# endif + { + fused = std::make_shared(inputs, history); + } + fused->set_friendly_name(compute_context.get_name() + "/RecurrentConvCache"); + group.conv = fused->output(0); + group.updated = fused->output(1); + return op::translate_concat(context); + } + if (index == group.compute) { + if (group.concat >= 0) { + return {group.conv}; + } + inputs.push_back(context.get_input("rs_update_" + m_decoder->get_op_name(group.writeback))); + auto outputs = op::translate_recurrent_gated_delta_net(context, inputs); + group.updated = outputs.back(); + return outputs; } return {group.updated}; } diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h index bf914f0243af..0a2234f89b5f 100644 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h @@ -11,9 +11,9 @@ class RecurrentCacheFusion { OutputVector translate(int index, const NodeContext & context); private: struct Group { - int reset = -1, gather = -1, remainder = -1, concat = -1; + int reset = -1, gather = -1, remainder = -1, concat = -1, compute = -1, writeback = -1; std::vector snapshots; - Output old_cache, gathered, prepared, conv, updated; + Output old_cache, conv, updated; }; std::shared_ptr m_decoder; diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index 5dcc9b8e285e..3bf8d3fbdba5 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -5,7 +5,7 @@ #include "ggml-openvino/openvino/node_context.h" #include "ggml-openvino/openvino/utils.h" #include "input_model.h" -#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE #include "recurrent_cache_fusion.h" #endif #include "pass/align_eltwise_ranks.h" @@ -315,7 +315,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo (*tensor_map)[it.first] = it.second; } -#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map); #endif auto translate_node = [&](const std::shared_ptr & decoder, int node_idx) { @@ -339,7 +339,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo " is not implemented."); NodeContext node_context(decoder, tensor_map, node_idx, this); ov::OutputVector converted_outputs; -#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE converted_outputs = recurrent_fusion.translate(node_idx, node_context); #endif if (converted_outputs.empty()) { diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 1066977d5207..851cef0474d3 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -114,14 +114,14 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : ggml_openvino_is_gpu(); - uint64_t extra_cfg = 6; // Packed native recurrent controls and state layout. -#ifdef GGML_OPENVINO_HAS_RECURRENT_CACHE - extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_RECURRENT_CACHE") ? 0u : 1u); + uint64_t extra_cfg = 10; // Direct fused recurrent computation and full-cache writeback. +#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE + extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ? 0u : 1u); #else extra_cfg = extra_cfg * 131; #endif -#ifdef GGML_OPENVINO_HAS_STATE_UPDATE - extra_cfg = extra_cfg * 131 + 1u; +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE + extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_RECURRENT_CACHE_INPLACE") ? 1u : 0u); #else extra_cfg = extra_cfg * 131; #endif @@ -405,18 +405,25 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr & ggml_d } } - // The sliced path above covers eligible KV outputs. This also covers recurrent state and full-size KV fallbacks. + // Resolve rotated roots/views before consulting an extra built for another bank. if (!ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS") && !ggml_decoder->is_static() && - !ggml_decoder->is_splited_model() && ggml_openvino_buffer_is_remote(ggml_tensor) && - ggml_tensor->extra != nullptr) { - auto * extra_base = static_cast(ggml_tensor->extra); - if (extra_base->type == ggml_openvino_extra_base::Type::TENSOR) { - auto * tensor_extra = static_cast(extra_base); - if (tensor_extra->tensor != nullptr && tensor_extra->tensor->get_element_type() == output_type && - tensor_extra->tensor->get_shape() == output_shape) { - return *tensor_extra->tensor; + !ggml_decoder->is_splited_model() && ggml_openvino_buffer_is_remote(ggml_tensor)) { + auto resolved = ggml_openvino_buffer_resolve_address(ggml_tensor, output_data, + ov::shape_size(output_shape) * output_type.size()); + if (ggml_tensor->extra != nullptr) { + auto * base = static_cast(ggml_tensor->extra); + if (base->type == ggml_openvino_extra_base::Type::TENSOR) { + auto & cached = static_cast(base)->tensor; + if (cached && cached->get_element_type() == output_type && cached->get_shape() == output_shape) { + auto remote = cached->as(); + if (remote.get() == resolved) { + return *cached; + } + } } } + auto context = ggml_openvino_get_remote_context()->as(); + return context.create_tensor(output_type, output_shape, resolved); } ov::Tensor output_tensor(output_type, output_shape, output_data); @@ -500,6 +507,24 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_ if (extra_base->type == ggml_openvino_extra_base::Type::TENSOR) { // GGML_LOG_DEBUG("Using ggml_tensor->extra as ov::Tensor for input: %s\n", name.c_str()); auto * tensor_extra = static_cast(extra_base); + if (ggml_openvino_buffer_is_remote(ggml_tensor)) { + auto tensor = tensor_extra->tensor->as(); + // Extras may retain a prior bank after a checkpoint write. + const auto shape = tensor.get_shape(); + const auto type = tensor.get_element_type(); + // Noncontiguous views can share a base extra. Preserve that + // binding's original base/window while selecting its current bank. + const auto * bound_tensor = ggml_tensor; + while (bound_tensor->view_src && bound_tensor->extra == bound_tensor->view_src->extra) { + bound_tensor = bound_tensor->view_src; + } + auto resolved = ggml_openvino_buffer_resolve_data(bound_tensor, 0, tensor.get_byte_size()); + if (tensor.get() == resolved) { + return *tensor_extra->tensor; + } + auto context = ggml_openvino_get_remote_context()->as(); + return context.create_tensor(type, shape, resolved); + } return *tensor_extra->tensor; } } @@ -1363,6 +1388,11 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share } } + bool recurrent_cache_inplace = false; +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE + recurrent_cache_inplace = ggml_openvino_getenv_int("GGML_OPENVINO_RECURRENT_CACHE_INPLACE") != 0; +#endif + std::vector rotated_outputs; for (size_t i = 0; i < ov_output_names.size(); i++) { // Debug-only outputs added via GGML_OPENVINO_DEBUG_NODE (see // translate_session.cpp) have no corresponding ggml tensor; leave @@ -1378,12 +1408,28 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share if (ggml_nbytes(ggml_tensor) == 0) { continue; } - auto output_tensor = create_ov_output_tensor(ggml_decoder, infer_request, i, ggml_tensor); + std::optional rotated; + if (cache_enabled && !is_static && !r_ctx->stateful && !ggml_decoder->is_splited_model() && + !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS") && + !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE_ROTATION") && + (!recurrent_cache_inplace || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) && + ggml_decoder->get_model_inputs().count(ov_output_names[i]) && + ggml_decoder->get_input_ggml_tensor(ov_output_names[i]) == ggml_tensor) { + rotated = ggml_openvino_buffer_prepare_cache_output(ggml_tensor); + } + auto output_tensor = + rotated ? *rotated : create_ov_output_tensor(ggml_decoder, infer_request, i, ggml_tensor); + if (rotated) { + rotated_outputs.push_back(ggml_tensor); + } infer_request->set_output_tensor(i, output_tensor); } ov_raw_infer_start = ggml_time_us(); infer_request->infer(); + for (auto * tensor : rotated_outputs) { + ggml_openvino_buffer_commit_cache_output(tensor); + } infer_end_time = ggml_time_us(); if (stateful_recurrent) { const auto * inp_pos = get_inp_pos_tensor(cgraph); diff --git a/tests/test-backend-sampler.cpp b/tests/test-backend-sampler.cpp index c6fdaf1ffab1..72e1da8215ad 100644 --- a/tests/test-backend-sampler.cpp +++ b/tests/test-backend-sampler.cpp @@ -1227,6 +1227,15 @@ static void test_backend_recurrent_slots(const test_params & params) { auto memory = llama_get_memory(ctx.ctx.get()); run({3, 3, 3, 3}); run({0, 0, 1, 0}); + // Export/import after both cache banks have been used. Checkpoint reads + // and writes must resolve the current storage rather than logical data. + const size_t checkpoint_size = llama_state_seq_get_size(ctx.ctx.get(), 2); + GGML_ASSERT(checkpoint_size > 0); + std::vector checkpoint(checkpoint_size); + GGML_ASSERT(llama_state_seq_get_data(ctx.ctx.get(), checkpoint.data(), checkpoint.size(), 2) == checkpoint_size); + GGML_ASSERT(llama_memory_seq_rm(memory, 2, 0, -1)); + GGML_ASSERT(llama_state_seq_set_data(ctx.ctx.get(), checkpoint.data(), checkpoint.size(), 2) == checkpoint_size); + run({0, 0, 1, 0}); GGML_ASSERT(llama_memory_seq_rm(memory, 1, 0, -1)); history[1].clear(); run({0, 2, 0, 0}); @@ -1244,6 +1253,10 @@ static void test_backend_recurrent_slots(const test_params & params) { history[1] = history[2]; run({0, 2, 1, 0}); run({1, 1, 1, 1}); + llama_memory_clear(memory, true); + for (auto & tokens : history) + tokens.clear(); + run({1, 1, 1, 1}); } printf("backend recurrent slot reset/copy/rollback test PASSED\n"); } From 4747851076d1bb6096d5803a0fd1d04deaae32a0 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 10:34:23 +0200 Subject: [PATCH 31/65] openvino: limit KV slicing to attention caches and share compiled blobs Keep recurrent cache banks full and treat live-prefix K/V slicing as a runtime binding choice. Document large-context measurements and supported layouts. Assisted-by: Codex --- ggml/src/ggml-openvino/README.md | 8 +- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 132 ++++++++++++++++++ ggml/src/ggml-openvino/model-cache.cpp | 3 +- ggml/src/ggml-openvino/utils.cpp | 23 ++- 4 files changed, 154 insertions(+), 12 deletions(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 26a2402e3497..5c80a9e61e91 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -16,7 +16,7 @@ The [integration report](dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md#direct-fronte records the required OpenVINO branches and tests. Rebuild both repos and regenerate compiled-model blobs after this translation change (revision 10). -The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all`, `GGML_OPENVINO_NATIVE_SOFTPLUS=1`, and `GGML_OPENVINO_DISABLE_KV_SLICE=1`. See the [performance report](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) for measurements; the earlier yamini-model results remain historical references. +The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_DISABLE_KV_SLICE` unset to use live-prefix attention cache bindings where supported. The [large-context comparison](dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md#large-context-attention-kv-slicing-2026-10-22) measures the benefit and documents the single-stream restriction. Earlier [performance measurements](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) used disabled slicing; yamini-model results remain historical references. `q4_asym64_all` converts Q4_K/Q5_K/Q6_K/Q8_0/Q5_1 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. `token_embd.weight` and `output.weight` retain symmetric channel-wise INT8. Q8_0/Q5_1 rows whose width is not divisible by 64 also use channel-wise INT8. This follows the primary/backup precision scheme of NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM` for these supported source types; it requantizes GGUF values rather than the original floating-point model and leaves floating-point weights unchanged. Earlier versions kept dense Q8_0 at INT8/group-32. Repopulate compiled-model caches without cache-only mode after this change; the cache fingerprint invalidates the old precision policy. @@ -31,7 +31,6 @@ One directory can hold blobs for different models and compilation settings. Run ```sh GGML_OPENVINO_DEVICE=GPU \ GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ -GGML_OPENVINO_DISABLE_KV_SLICE=1 \ GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \ ./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1 @@ -44,7 +43,6 @@ On later runs, supply the same compilation settings and enable `GGML_OPENVINO_CO ```sh GGML_OPENVINO_DEVICE=GPU \ GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ -GGML_OPENVINO_DISABLE_KV_SLICE=1 \ GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ @@ -53,7 +51,9 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally. -Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. +Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. + +`GGML_OPENVINO_DISABLE_KV_SLICE` is a runtime binding option and can differ between cache population and cache-only runs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Slicing is enabled by default for contiguous ordinary K/V roots with one allocated stream, one active sequence at offset zero, and no sliding-window attention. Recurrent convolution/GDN caches and their rollback snapshots always retain their full stored row bank. Other layouts use full bindings. Repopulate caches made before this option was removed from the fingerprint once without cache-only mode. A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md index 04e6095f805e..1a045fdb5924 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -815,3 +815,135 @@ clear, changing batches and rollback depths 0/2. The rotation IR contains 18 `RecurrentConvCache` and 18 `RecurrentGatedDeltaNet` operations and no standalone native gather/update operations. Logs are in `tmp/ov-branch-split-20261022/` and `tmp/qwen-finalize-20261022/`. + +## Large-context attention KV slicing (2026-10-22) + +Leave `GGML_OPENVINO_DISABLE_KV_SLICE` **unset** for the next benchmarks. On the +target UD model with a 65,536-token allocation and one active sequence, default +attention K/V slicing improves mean decode from **23.048 to 33.480 tokens/s +(+45.26%)**. All six measured greedy outputs match exactly. This comparison +uses non-MTP; it does not establish an MTP gain or throughput at a 64K *filled* +history. + +### Method and results + +Same Release `build/MtpOVPerf`, OpenVINO build, device and model as above. Server: +`-np 1 -c 65536 -t 2`; batch and batch-thread settings retain their defaults. +Both processes use GPU, `q4_asym64_all`, native softplus, the same standalone +compiled-model cache, and cache-only loading. Stateful and recurrent in-place +execution remain unset. Each process handles an eight-token warmup, then three +sequential requests with the same saved 1,024-token passage, exactly 512 greedy +generated tokens, ignored EOS and prompt caching disabled (`cache_n=0`). +Requests reset and reuse the recurrent state. Startup/import and warmup are +excluded. GPU workloads run serially. The transfer/runtime-graph probe is armed +only after the three primary requests. + +| Attention cache binding | Decode tokens/s, three requests | Mean decode tokens/s | Prompt tokens/s, three requests | Mean prompt tokens/s | +| --- | ---: | ---: | ---: | ---: | +| Full capacity (`GGML_OPENVINO_DISABLE_KV_SLICE=1`) | 22.851 / 23.265 / 23.027 | 23.048 | 513.29 / 425.67 / 265.77 | 401.57 | +| Live prefix (default, variable unset) | 33.565 / 33.422 / 33.452 | 33.480 | 945.60 / 936.54 / 935.69 | 939.28 | + +The full-capacity prompt samples vary substantially and memory usage grows +during the run. The decode difference is stable across the three samples; +the prompt means should not be treated as an isolated kernel speedup. + +The first cold run used `-c 262144`, allocated 5,120 MiB attention KV, exported +the graph, and completed the eight-token warmup. The next request entered +heavy memory pressure and stalled in `xe_vm_bind_ioctl`; it was terminated. +Driver teardown eventually released the allocations without a reset. That +run supplies the exported blob but **no valid 512-token benchmark sample**. +Both reported modes instead use a 64K allocation and cache-only loading to +avoid retaining the requantized host weights. The target's maximum-context +full-cache performance remains unmeasured. + +### Bindings and likely source of the cost + +The helper changes the shape of an `ov::Tensor` over the original storage; it +does not shrink the allocated GGML cache or copy its contents when binding. +The probe confirms USM bindings in both modes, with each attention root using +the same input/output address. At the first 508-token prefill chunk: + +| Bound cache roots | Full capacity | Live prefix | +| --- | ---: | ---: | +| 20 attention K/V inputs, and separately their 20 outputs | `[1,1,65536,512]`, total 1,280 MiB | `[1,1,512,512]`, total 10 MiB | +| 30 recurrent convolution inputs/outputs | `[1,1,1,24576]`, total 2.8125 MiB | Identical | +| 30 recurrent GDN inputs/outputs | `[1,1,1,524288]`, total 60 MiB | Identical | + +Attention prefix length increases with the live, padded attention length. +It is not fixed to the initial 512 rows. Recurrent inputs/outputs preserve +their complete row banks, including rollback storage when present. The +slicing helper now explicitly admits only contiguous ordinary attention +`cache_k_l*` / `cache_v_l*` roots and rejects recurrent roots independently of +the broader cache-buffer classifier. + +Steady short-probe trunk decode observes **1,058 kernel submissions** with +full capacity versus **1,038** with slicing; median raw inference over probe +indices 8–17 is **38.930 versus 26.759 ms**. These diagnostic timings are +separate from the table. There is no bulk cache memcpy API call in these +steady decode traces: both have eight host-metadata uploads totaling 2,608 +bytes, twenty host-USM uploads totaling 320 bytes, and three host-output copies +totaling 1,009,664 bytes. Shape changes during prefill and the first decode do +trigger larger transfers and allocations, especially with full bindings. + +The extra 20 launches are consistent with a full-sized initialization/copy +stage for each attention `ScatterUpdate`; the GPU reference implementation +dispatches that stage over the whole bound cache unless it recognizes an +in-place update. Copies performed by kernels are not included in memcpy API +counts. Thus the measured gap is consistent with full-cache GPU work and +temporary storage rather than a host upload on every token. The present probe +does not time or attribute each kernel individually. Recurrent cache shapes +and the compiled graph are unchanged by the toggle. + +### Compiled-model sharing and limits + +Removed `GGML_OPENVINO_DISABLE_KV_SLICE` from both the raw compilation-settings +fingerprint in `model-cache.cpp` and the extra translation-settings hash in +`utils.cpp`. It affects only runtime bindings: dynamic attention Parameters +already accept either context dimension. The full-cache 262K export and both +64K cache-only runs use the exact same file: +`tmp/kv-slice-20261022/model-cache/77952f8eea1a9c89.blob`. Both measured logs +contain `model cache HIT` for that blob and no new exports. Compilation cache +entries made before this fingerprint change require one regeneration. MTP, +different port sets, and different recurrent slot/snapshot layouts may still +require additional entries independently of attention slicing. + +Slicing currently requires **one allocated attention stream**, one active +sequence at offset zero, the supported contiguous root layout, and a +non-SWA dynamic/stateless path. Ordinary partitioned `-np 4` has roots shaped +`[1,4,ctx_per_seq,F]` and falls back to full bindings even with one request; +removing the variable alone does not optimize that layout. Unified KV can +have one physical stream, but these measurements do not validate its +multi-sequence/offset cases. Extending prefix/window binding to partitioned +streams, or teaching a new attention cache-update op to modify only written +rows safely, remain separate opportunities. No OpenVINO op was changed in +this comparison. + +### Reproduction + +After populating a compatible compiled cache, both modes use: + +```sh +MODEL="$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_NATIVE_SOFTPLUS=1 +export GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all +export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR="$(pwd)/tmp/kv-slice-20261022/model-cache" +export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 + +# Start each server separately, then send the same measured requests. +GGML_OPENVINO_DISABLE_KV_SLICE=1 \ + build/MtpOVPerf/bin/llama-server -m "$MODEL" -np 1 -c 65536 -t 2 + +unset GGML_OPENVINO_DISABLE_KV_SLICE +build/MtpOVPerf/bin/llama-server -m "$MODEL" -np 1 -c 65536 -t 2 +``` + +The matched harness, effective commands, all response JSON, buffer tables, +transfer traces, and summary are saved in `tmp/kv-slice-20261022/`. Reproduce +the requests and comparison with the existing populated cache: + +```sh +python3 tmp/kv-slice-20261022/bench.py on 65536 +python3 tmp/kv-slice-20261022/bench.py off-cached 65536 +python3 tmp/kv-slice-20261022/summary.py 65536 +``` diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 1c3184675e67..c6b4b5d5c175 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -167,7 +167,8 @@ bool ggml_openvino_model_cache_only() { static const char * cache_settings[] = { "GGML_OPENVINO_REQUANT_KQUANT", "GGML_OPENVINO_NATIVE_SOFTPLUS", - "GGML_OPENVINO_DISABLE_KV_SLICE", + // GGML_OPENVINO_DISABLE_KV_SLICE only changes runtime bindings. Dynamic + // attention graphs accept either shape and share the same compiled blob. "GGML_OPENVINO_MANUAL_GQA_ATTN", "GGML_OPENVINO_STATEFUL_EXECUTION", "GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT", diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 851cef0474d3..c8040c96c35d 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -40,19 +40,19 @@ #include namespace { -// For a KV cache input, return an ov::Tensor sized to n_kv (== attention_size -// for that layer) instead of the fully-allocated ctx_per_seq. Pre-conditions: +// For an attention K/V input or output, return an ov::Tensor sized to n_kv +// (== attention_size for that layer) instead of the allocated ctx_per_seq. Pre-conditions: // * non-static (CPU/GPU) backend, single sequence, seq_active_start == 0 // * ggml KV layout is a contiguous [1, 1, ctx_per_seq, n_heads_kv*head_size] // so the first n_kv rows are the live prefix and shrinking the ctx axis -// gives a valid tensor over the same host storage +// gives a valid tensor over the same host/device-USM storage // * not an SWA layer (ring cache): once the window has wrapped the first // n_kv rows no longer contain the live prefix // On any unmet pre-condition returns std::nullopt; the caller falls back to // the full-size tensor. std::optional try_make_kv_sliced_tensor(const std::shared_ptr & ggml_decoder, - const std::string & name, - const ggml_tensor * ggml_tensor) { + const std::string & name, + const ggml_tensor * ggml_tensor) { static const bool kv_slice_disabled = ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_SLICE"); if (kv_slice_disabled) { return std::nullopt; @@ -60,7 +60,15 @@ std::optional try_make_kv_sliced_tensor(const std::shared_ptris_static() || ggml_decoder->is_stateful()) { return std::nullopt; } - if (ggml_tensor->op != GGML_OP_NONE || ggml_tensor->view_src != nullptr) { + if (ggml_tensor->op != GGML_OP_NONE || ggml_tensor->view_src != nullptr || !ggml_is_contiguous(ggml_tensor)) { + return std::nullopt; + } + // USAGE_ANY alone is not proof of an attention cache. Only the ordinary + // llama.cpp K/V roots have this prefix layout; recurrent caches (including + // rollback snapshots) must always bind their complete stored row bank. + if (GgmlOvDecoder::is_recurrent_cache(ggml_tensor) || + (strncmp(ggml_tensor->name, "cache_k_l", strlen("cache_k_l")) != 0 && + strncmp(ggml_tensor->name, "cache_v_l", strlen("cache_v_l")) != 0)) { return std::nullopt; } const auto * op = ggml_decoder->get_tensor_used_op(ggml_tensor); @@ -127,7 +135,8 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren #endif extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u); - extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_SLICE") ? 1u : 0u); + // KV slicing changes runtime tensor bindings, not the dynamic compiled graph. + // Both full-capacity and live-prefix bindings must share one cache entry. extra_cfg = extra_cfg * 131 + (manual_gqa_enabled ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_shape_from_mask_enabled() ? 1u : 0u); From 6cb21a72ed0f8de277847db6924b4bc199108b16 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 10:34:23 +0200 Subject: [PATCH 32/65] tools: add natural-text server benchmark and OpenVINO profile summary Assisted-by: Codex --- scripts/analyze-openvino-profile.py | 90 ++++++++++++ scripts/server-bench-text.py | 207 ++++++++++++++++++++++++++++ 2 files changed, 297 insertions(+) create mode 100644 scripts/analyze-openvino-profile.py create mode 100644 scripts/server-bench-text.py diff --git a/scripts/analyze-openvino-profile.py b/scripts/analyze-openvino-profile.py new file mode 100644 index 000000000000..c88c39afbf98 --- /dev/null +++ b/scripts/analyze-openvino-profile.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 + +import argparse +import csv +from collections import defaultdict +from pathlib import Path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Summarize OpenVINO profiling CSV files") + parser.add_argument("profiles", nargs="+", type=Path) + parser.add_argument("--limit", type=int, default=15, help="rows shown per table") + parser.add_argument("--gaps", type=int, default=0, metavar="N", help="show the N largest device timeline gaps") + return parser.parse_args() + + +def print_group(title: str, values: dict[str, list[int]], total_us: int, limit: int) -> None: + print(f"\n{title}") + print(f"{'device ms':>10} {'count':>7} {'share':>7} name") + for name, (time_us, count) in sorted(values.items(), key=lambda item: item[1][0], reverse=True)[:limit]: + share = 100.0 * time_us / total_us if total_us else 0.0 + print(f"{time_us / 1000:10.3f} {count:7d} {share:6.1f}% {name}") + + +def print_gaps(rows: list[dict[str, str]], limit: int) -> None: + timeline = sorted( + (row for row in rows if int(row["start_time_us"]) > 0), key=lambda row: int(row["start_time_us"]) + ) + if not timeline: + return + + gaps: list[tuple[int, dict[str, str]]] = [] + completed_until = int(timeline[0]["start_time_us"]) + int(timeline[0]["real_time_us"]) + for row in timeline[1:]: + start_us = int(row["start_time_us"]) + if start_us > completed_until: + gaps.append((start_us - completed_until, row)) + completed_until = max(completed_until, start_us + int(row["real_time_us"])) + + print("\nLargest device timeline gaps before node") + print("Profiling adds synchronization; a gap marks a boundary and is not time caused by the following node.") + for gap_us, row in sorted(gaps, key=lambda item: item[0], reverse=True)[:limit]: + print(f'{gap_us:8d} us {row["node_type"]:24} {row["node_name"]} | {row["exec_type"]}') + + +def analyze(path: Path, limit: int, gap_limit: int) -> None: + by_type: dict[str, list[int]] = defaultdict(lambda: [0, 0]) + by_impl: dict[str, list[int]] = defaultdict(lambda: [0, 0]) + by_node: dict[str, list[int]] = defaultdict(lambda: [0, 0]) + executed_rows: list[dict[str, str]] = [] + total_real_us = 0 + total_cpu_us = 0 + executed = 0 + + with path.open(newline="") as profile_file: + for row in csv.DictReader(profile_file): + if row["status"] != "EXECUTED": + continue + executed_rows.append(row) + real_us = int(row["real_time_us"]) + total_real_us += real_us + total_cpu_us += int(row["cpu_time_us"]) + executed += 1 + for values, key in ( + (by_type, row["node_type"]), + (by_impl, row["exec_type"]), + (by_node, f'{row["node_type"]}: {row["node_name"]}'), + ): + values[key][0] += real_us + values[key][1] += 1 + + print(f"\n== {path} ==") + print(f"executed nodes: {executed}") + print(f"summed device time: {total_real_us / 1000:.3f} ms") + print(f"summed CPU time: {total_cpu_us / 1000:.3f} ms") + print_group("Node types", by_type, total_real_us, limit) + print_group("Implementations", by_impl, total_real_us, limit) + print_group("Individual nodes", by_node, total_real_us, limit) + if gap_limit > 0: + print_gaps(executed_rows, gap_limit) + + +def main() -> None: + args = parse_args() + for profile in args.profiles: + analyze(profile, args.limit, args.gaps) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/server-bench-text.py b/scripts/server-bench-text.py new file mode 100644 index 000000000000..5288dcd86294 --- /dev/null +++ b/scripts/server-bench-text.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Benchmark saved natural-text prompts on an already running llama-server. + +The corpus is local Markdown, rather than random token IDs. Prompts are sized +approximately at paragraph boundaries, saved once, and reused across server +configurations. Native completion timings provide the actual token counts. +""" + +import argparse +import concurrent.futures +import hashlib +import json +from pathlib import Path +import threading +import time +import urllib.request + + +HTTP = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +def request(url, body=None, timeout=7200): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url, data, {"Content-Type": "application/json"}) + with HTTP.open(req, timeout=timeout) as response: + return json.load(response) + + +def save(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n") + + +def render(url, content): + return request(url + "/apply-template", { + "messages": [{"role": "user", "content": content}], + })["prompt"] + + +def token_count(url, prompt): + return len(request(url + "/tokenize", { + "content": prompt, "add_special": True, "parse_special": True, + })["tokens"]) + + +def prepare_prompts(args): + files = sorted(args.text_dir.rglob("*.md")) + if not files: + raise ValueError(f"No Markdown corpus found in {args.text_dir}") + documents = [(str(p.relative_to(args.text_dir)), p.read_text()) for p in files] + corpus_hash = hashlib.sha256(json.dumps(documents).encode()).hexdigest() + prompts = {} + for target in args.prompt_sizes: + prompts[target] = [] + for variant in range(args.server_slots): + path = args.prompts_dir / f"p{target}-v{variant}.json" + if path.exists(): + item = json.loads(path.read_text()) + prompt = render(args.url, item["content"]) + if prompt != item["prompt"] or token_count(args.url, prompt) != item["prompt_n"]: + raise ValueError(f"Saved prompt/template/tokenizer mismatch: {path}") + if item["corpus_sha256"] != corpus_hash: + raise ValueError(f"Corpus changed since {path} was saved") + else: + # Rotate documents for distinct long requests; never repeat a + # short passage or pad with random IDs to reach a target length. + offset = variant * len(documents) // args.server_slots + ordered = documents[offset:] + documents[:offset] + paragraphs = [] + for name, text in ordered: + paragraphs.extend(p for p in (f"Source: {name}\n\n" + text).split("\n\n") if p.strip()) + prefix = ( + f"Read reference collection {variant + 1} below. Explain its main technical " + "ideas, practical recommendations, and tradeoffs in a detailed summary.\n\n" + "Reference material:\n\n" + ) + # Find the nearest complete paragraph prefix. Exact lengths are + # deliberately relaxed; the measured length is recorded below. + cache = {} + + def candidate(n): + if n not in cache: + content = prefix + "\n\n".join(paragraphs[:n]) + prompt = render(args.url, content) + cache[n] = (content, prompt, token_count(args.url, prompt)) + return cache[n] + + if candidate(len(paragraphs))[2] < target: + raise ValueError(f"Corpus is too short for a {target}-token prompt") + low, high = 1, len(paragraphs) + while low < high: + middle = (low + high) // 2 + if candidate(middle)[2] < target: + low = middle + 1 + else: + high = middle + choices = [candidate(low)] + if low > 1: + choices.append(candidate(low - 1)) + content, prompt, count = min(choices, key=lambda x: abs(x[2] - target)) + if abs(count - target) > max(128, target * 0.05): + raise ValueError(f"Paragraph boundary gives {count} tokens for target {target}") + item = { + "target_tokens": target, "variant": variant, + "corpus_sha256": corpus_hash, "source_dir": str(args.text_dir.resolve()), + "source_files": [name for name, _ in ordered], + "content": content, "prompt": prompt, "prompt_n": count, + } + save(path, item) + if item["prompt_n"] + args.n_predict + 8 >= args.ctx_per_seq: + raise ValueError(f"Insufficient sequence context for {path}") + prompts[target].append(item) + print(f"target={target} variant={variant} actual_prompt_tokens={item['prompt_n']}", flush=True) + return prompts + + +def run_wave(args, items, concurrency, n_predict): + barrier = threading.Barrier(concurrency) + + def one(slot): + item = items[slot] + body = { + "prompt": item["prompt"], "id_slot": slot, + "n_predict": n_predict, "temperature": 0.0, + "ignore_eos": True, "cache_prompt": False, "stream": False, + } + barrier.wait(timeout=60) + start = time.perf_counter() + result = request(args.url + "/completion", body) + duration = time.perf_counter() - start + timing = result["timings"] + if (timing["prompt_n"] != item["prompt_n"] or timing["cache_n"] != 0 + or timing["predicted_n"] != n_predict or result.get("truncated")): + raise ValueError(f"Unexpected token counts or truncation in slot {slot}: {timing}") + if result["id_slot"] != slot: + raise ValueError(f"Requested slot {slot}, received {result['id_slot']}") + if args.expect_mtp == "on" and n_predict > 8 and timing.get("draft_n", 0) == 0: + raise ValueError("MTP was requested, but no draft tokens were reported") + if args.expect_mtp == "off" and timing.get("draft_n", 0) > 0: + raise ValueError("Non-MTP control unexpectedly produced draft tokens") + return {"variant": item["variant"], "request_seconds": duration, "response": result} + + start = time.perf_counter() + with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool: + results = list(pool.map(one, range(concurrency))) + wall = time.perf_counter() - start + return {"wall_seconds": wall, "generated_tokens_per_wall_second_including_prefill": + sum(r["response"]["timings"]["predicted_n"] for r in results) / wall, + "requests": results} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--url", default="http://127.0.0.1:18925") + parser.add_argument("--text-dir", type=Path, default=Path("docs")) + parser.add_argument("--prompts-dir", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, required=True) + parser.add_argument("--server-slots", type=int, choices=[1, 4], required=True) + parser.add_argument("--ctx-per-seq", type=int, default=262144) + parser.add_argument("--concurrency", type=int, nargs="+", default=[1]) + parser.add_argument("--prompt-sizes", type=int, nargs="+", default=[1024, 8192, 32768, 65536]) + parser.add_argument("--n-predict", type=int, default=512) + parser.add_argument("--repetitions", type=int, default=3) + parser.add_argument("--expect-mtp", choices=["on", "off"], required=True) + args = parser.parse_args() + args.url = args.url.rstrip("/") + if any(n < 1 or n > args.server_slots for n in args.concurrency): + parser.error("Concurrency must be between one and the configured server slot count") + if args.repetitions < 1 or args.n_predict < 1 or any(n < 1 for n in args.prompt_sizes): + parser.error("Repetitions and token lengths must be positive") + if request(args.url + "/health").get("status") != "ok": + raise ValueError("Server is not ready") + slots = request(args.url + "/slots") + if len(slots) != args.server_slots or any(s["n_ctx"] != args.ctx_per_seq for s in slots): + raise ValueError(f"Server slot count/context does not match the benchmark: {slots}") + expected = args.expect_mtp == "on" + if any(bool(s["speculative"]) != expected for s in slots): + raise ValueError("Server speculative mode does not match --expect-mtp") + save(args.out_dir / "config.json", {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}) + prompts = prepare_prompts(args) + summary = [] + for size in args.prompt_sizes: + for concurrency in args.concurrency: + directory = args.out_dir / f"p{size}-clients{concurrency}" + save(directory / "warmup.json", run_wave(args, prompts[size], concurrency, 8)) + for repetition in range(args.repetitions): + wave = run_wave(args, prompts[size], concurrency, args.n_predict) + save(directory / f"run{repetition + 1}.json", wave) + timings = [r["response"]["timings"] for r in wave["requests"]] + row = { + "target_prompt_tokens": size, "concurrency": concurrency, + "repetition": repetition + 1, + "actual_prompt_tokens": [t["prompt_n"] for t in timings], + "decode_tokens_per_second_per_request": [t["predicted_per_second"] for t in timings], + "prompt_tokens_per_second_per_request": [t["prompt_per_second"] for t in timings], + "draft_tokens": [t.get("draft_n", 0) for t in timings], + "accepted_draft_tokens": [t.get("draft_n_accepted", 0) for t in timings], + "generated_tokens_per_wall_second_including_prefill": wave[ + "generated_tokens_per_wall_second_including_prefill"], + } + summary.append(row) + save(args.out_dir / "summary.json", summary) + print(json.dumps(row), flush=True) + + +if __name__ == "__main__": + main() From 593af4dfa559a14409252680a173fc6845d0a389 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 10:40:12 +0200 Subject: [PATCH 33/65] docs: record fused-cache branch split and UD validation Assisted-by: Codex --- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md index 1a045fdb5924..2f2a5516c194 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -816,6 +816,33 @@ clear, changing batches and rollback depths 0/2. The rotation IR contains 18 native gather/update operations. Logs are in `tmp/ov-branch-split-20261022/` and `tmp/qwen-finalize-20261022/`. +### Target UD validation after cleanup + +The cleaned frontend passes the target UD GGUF through `llama-server -np 4 +-c 8192 -t 2 -tb 2` with GPU, native softplus, `q4_asym64_all` and disabled +KV slicing. Each process runs an eight-token warmup, one uncached saved +1,024-token passage with 512 greedy generated tokens, then four distinct +concurrent prompts with 96 generated tokens each. Startup, requantization and +warmup are excluded from the reported native request timings. + +| Validated path | Prompt tokens/s | Decode tokens/s | Accepted / generated drafts | +| --- | ---: | ---: | ---: | +| Rotation, non-MTP | 925.47 | 28.455 | — | +| In-place, two-token MTP | 830.53 | 41.429 | 340 / 340 | + +The two primary outputs match exactly. All eight concurrent functional requests +complete without truncation. The four MTP requests accept 53/83, 55/78, 53/82 +and 51/87 drafts, exercising rejection as well as parallel slot use. These are +one-request sanity measurements using different cache/speculation modes, not a +controlled rotation-versus-in-place speedup estimate or representative MTP gain. + +A clean detached checkout at `6cb21a72e` also builds `llama-server`, `llama-bench` +and `test-backend-sampler` in Release without the local Vulkan/debugging edits. +The Qwen pruning fix is checked by retaining one layer of the 0.8B F16 GGUF: +its block count and recurrent-layer metadata match the retained layer, and CPU +prefill/decode complete. Validation artifacts are in +`tmp/qwen-finalize-20261022/`. + ## Large-context attention KV slicing (2026-10-22) Leave `GGML_OPENVINO_DISABLE_KV_SLICE` **unset** for the next benchmarks. On the From 2f43b5f3e33d3b96e2750d5b9bca0819cfe46fdb Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 11:19:21 +0200 Subject: [PATCH 34/65] server-bench: preserve native token counts and save request timings --- scripts/server-bench.py | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/scripts/server-bench.py b/scripts/server-bench.py index 2eabb3bce85c..2d1cd8c15e03 100755 --- a/scripts/server-bench.py +++ b/scripts/server-bench.py @@ -6,6 +6,7 @@ import random import sqlite3 import subprocess +from pathlib import Path from time import sleep, time from typing import Optional, Union @@ -126,27 +127,37 @@ def send_prompt(data: dict) -> tuple[float, list[float]]: response.raise_for_status() prompt: str = json.loads(response.text)["prompt"] - json_data: dict = {"prompt": prompt, "seed": data["seed"], "n_predict": data["n_predict"], "stream": True} + json_data: dict = {"prompt": prompt, "seed": data["seed"], "n_predict": data["n_predict"], "stream": True, + "ignore_eos": True, "cache_prompt": False} response = session.post(f"{server_address}/completion", json=json_data, stream=True) response.raise_for_status() - lines = [] + events = [] token_arrival_times: list[float] = [] for line in response.iter_lines(decode_unicode=False): - if not line.startswith(b"data: "): + if not line.startswith(b"data: ") or line[6:] == b"[DONE]": continue - lines.append(line) - token_arrival_times.append(time()) - token_arrival_times = token_arrival_times[:-1] - if len(lines) > 1 and "timings" in json.loads(lines[-2][6:]): - token_arrival_times = token_arrival_times[:-1] - + event = json.loads(line[6:]) + events.append(event) + if event.get("stop"): + continue + # Count native token IDs, excluding empty begin/progress events. + # If an event groups tokens, they share the same arrival time. + count = len(event["tokens"]) if "tokens" in event else 1 + token_arrival_times.extend([time()] * count) + + if data.get("results_dir"): + timing = next((event["timings"] for event in reversed(events) if "timings" in event), None) + Path(data["results_dir"]).mkdir(parents=True, exist_ok=True) + Path(data["results_dir"], f"request-{data['request_index']:04d}.json").write_text( + json.dumps({"prompt": data["prompt"], "request": json_data, "timings": timing, + "events": events, "token_arrival_times": token_arrival_times}, indent=2)) return (t_submit, token_arrival_times) def benchmark( path_server: str, path_log: Optional[str], path_db: Optional[str], name: Optional[str], prompt_source: str, n_prompts: int, - n_predict: int, n_predict_min: int, seed_offset: int): + n_predict: int, n_predict_min: int, seed_offset: int, results_dir: Optional[str] = None): external_server: bool = path_server.startswith("http://") or path_server.startswith("https://") if os.environ.get("LLAMA_ARG_N_PARALLEL") is None: logger.info("LLAMA_ARG_N_PARALLEL not explicitly set, using 32") @@ -196,6 +207,7 @@ def benchmark( data.append({ "session": session, "server_address": server_address, "external_server": external_server, "prompt": p, "synthetic_prompt": synthetic_prompts, "n_predict": random.randint(n_predict_min, n_predict), + "results_dir": results_dir, "request_index": i, "seed": (3 * (seed_offset + 1000 * i) + 2) if seed_offset >= 0 else -1}) if not synthetic_prompts: @@ -281,6 +293,7 @@ def benchmark( "particularly when the server is fast vs. the network or Python script (e.g. when serving a very small model).") parser.add_argument("--path_server", type=str, default="llama-server", help="Path to the llama.cpp server binary") parser.add_argument("--path_log", type=str, default="server-bench-{port}.log", help="Path to the model to use for the benchmark") + parser.add_argument("--results_dir", type=str, default=None, help="Save each response and native server timings for token-count and MTP analysis") parser.add_argument("--path_db", type=str, default=None, help="Path to an sqlite database to store the benchmark results in") parser.add_argument("--name", type=str, default=None, help="Name to label plots and database entries with") parser.add_argument( From 247407214f921ca5a5c86b036c0a73c640811a7f Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 22 Oct 2026 11:32:28 +0200 Subject: [PATCH 35/65] openvino: document MTP regression and host USM alias recovery --- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md index 2f2a5516c194..f1c3b25d03bd 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -974,3 +974,53 @@ python3 tmp/kv-slice-20261022/bench.py on 65536 python3 tmp/kv-slice-20261022/bench.py off-cached 65536 python3 tmp/kv-slice-20261022/summary.py 65536 ``` + + +## MTP regression investigation after branch cleanup (2026-10-22, in progress) + +Matched control: target Qwen3.6 UD Q4_K_M, GPU, `q4_asym64_all`, native +softplus, `-np 4 -c 8192 -t 2 -tb 2`, two MTP drafts, greedy sampling, +1,024 saved prompt tokens and exactly 512 generated tokens. Three requests +follow an eight-token warmup. Transfer tracing is disabled during timed requests +and enabled only for a separate diagnostic request. KV slicing is disabled only +for this historical control; subsequent large-context measurements enable it. + +| Runtime/path | Mean decode t/s | Verification graph reorders | +|---|---:|---:| +| Previous rotation | 46.345 | 250 | +| Current rotation before precision experiment | 44.002 | 250 | +| Previous in-place | 45.014 | 250 | +| Current in-place before precision experiment | 40.720 | 310 | +| In-place with protected cache Reshape precision | 39.021 | 250 | +| Same precision experiment, cache-only retest | 38.504 | 250 | + +All measured requests accepted 340/340 drafts and produced identical text. +Protecting only the fused operation's input did not protect its upstream FP32 +cache Reshape aliases from FP16 conversion. Protecting those aliases removes +60 reorders and reduces verification submissions from 1,191 to 1,071, but does +**not** establish a performance fix: the diagnostic now records roughly 790 MB +of host-USM-to-device transfers per verification. Matching caller cache input +and output addresses alone does not demonstrate direct internal execution. +The subsequent allocation fix below resolves the large transfers. A llama input-binding fallback +experiment did not remove these transfers or improve decode and was reverted. + +Artifacts and effective commands are in `tmp/mtp-regression-20261022/`. +The default rotation repeat measured 43.820 t/s; the large-context batch/MMLU matrix is pending. +MMLU uses the `cais/mmlu`, `all`, test split's first 100 question texts, with +chat templating and 512 generated tokens per request; question lengths are +measured rather than padded to exact targets. Native server timing JSON is +saved separately from stream-arrival plots. The benchmark counts native token +IDs and excludes empty begin/progress and stop events. + + +The recovered in-place path measured **46.610 t/s** over three matched +requests. The GPU cache Result binding previously accepted only device USM; +accepting host USM under the same exact-layout and exclusive-alias checks +removes the full-cache staging transfers on this iGPU. Combined with preserving +cache Reshape precision, the warmed diagnostic records only 320 bytes of +host-USM-to-device transfers per verification, rather than 790 MB. Verification +kernel submissions are 1,131 (including the gather stage), and the sampled +verification call takes 44.838 ms. This is a measured recovery of the in-place +regression; default rotation remains approximately 5% below its historical +46.345 t/s. Raw responses and traces are in the `copy-stack/inplace-mtp` +subdirectory. Temporary upload-site logging was removed. From dd06588b13727c6bc7b06f53e3cbe8890a9c4495 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 23 Oct 2026 04:22:43 +0200 Subject: [PATCH 36/65] openvino: record large-context allocation diagnosis and default-batch validation --- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md index f1c3b25d03bd..8d4fb485cff8 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -1024,3 +1024,61 @@ verification call takes 44.838 ms. This is a measured recovery of the in-place regression; default rotation remains approximately 5% below its historical 46.345 t/s. Raw responses and traces are in the `copy-stack/inplace-mtp` subdirectory. Temporary upload-site logging was removed. + + +### Initial large-context matrix attempts (2026-10-22/23) + +Cache-only import accepts a 128K context allocation with blobs populated at +2K/8K. KV slicing is left enabled. The first `-npl 1` run used the default +`-ub 512`, 128K allocated context, independent random-token prompts, and 512 +decode tokens: + +| Prompt tokens | Prefill t/s | Decode t/s | +|---:|---:|---:| +| 1,024 | 832.26 | 35.06 | +| 8,192 | 905.83 | 27.40 | +| 32,768 | 324.48 | 13.64 | +| 65,536 | no completed sample | no completed sample | + +The 64K case was terminated when system available memory fell below 1 GB. +Attempts with `-ub 64`, including a fresh-process 32K case, also exhibited +large allocation growth and were terminated under memory pressure. These are +not kernel-reported OOM errors; they are incomplete tests. Reducing microbatch +size did not resolve memory growth. Isolated `-ub 64` runs completed 1K and +8K at 35.21 and 27.92 decode t/s respectively. + +This is not evidence that a 32K persistent KV cache requires 64 GB. The +problematic one-sequence tests allocate 128K context, whose 20 FP16 attention +K/V roots total 2.5 GiB; the recurrent caches are about 63 MiB without MTP. +Compiled weights are approximately 18 GiB. Runtime temporaries, retained +allocations, and shape-dependent execution therefore need investigation. +The np4 MMLU MTP startup confirmed 131,072 context per slot with a total +524,288 allocation; it produced no completed responses before exiting. +No valid four-slot MMLU aggregate or complete batch matrix is available yet. +An allocation audit is being added temporarily to identify growing buffers. + + +The default `-b 2048 -ub 512` allocation audit completed 32K prefill/decode. +It recorded 25.8 GB in the GPU non-padded memory pool, including multiple old +allocations attributed to individual attention `ScatterUpdate` nodes (over +1 GB owned by one node whose current requested output was about 33 MB). +Persistent KV capacity does not explain that retained pool volume. +The caller-output rebinding paths replace pooled producer outputs; experimental +fixes release previous ownership and update capacity before adopting borrowed +Result storage. The first matched 32K experiment completed at 384.03 prefill +and 13.91 decode t/s, but its 64K run still exhausted memory and was terminated. +A second rebinding path is now corrected and under validation. These memory +fixes are not yet committed. All subsequent measurements use default batch and +microbatch sizes, as requested; no additional alternate-UB experiments are planned. + + +The second caller-output bookkeeping fix completed the formerly failing 64K +prompt with default batch/microbatch and 128K context: 503.80 prefill t/s, +6.37 decode t/s (130.083 s prefill, 80.362 s decode). System memory fluctuated +around 30–34 GiB during much of the run instead of monotonically reaching the +62 GiB limit. All eight existing remote-output lifecycle tests passed. The +fix releases a primitive's pooled output ownership before replacing its buffer +in `set_output_memory`, and also handles direct producer borrowing from an +optimized Result while refreshing its capacity. No existing operation contract +or kernel arithmetic changes. Four-stream validation is now running with +524,288 total context and default batch/microbatch sizes. From 197304cfdeff6c396003868d174b63f4dbecf106 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 23 Oct 2026 06:52:24 +0200 Subject: [PATCH 37/65] server-bench: count buffered native tokens and reject stream errors --- scripts/server-bench.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/scripts/server-bench.py b/scripts/server-bench.py index 2d1cd8c15e03..10bba07dd5e4 100755 --- a/scripts/server-bench.py +++ b/scripts/server-bench.py @@ -134,11 +134,23 @@ def send_prompt(data: dict) -> tuple[float, list[float]]: events = [] token_arrival_times: list[float] = [] + native_tokens_predicted = 0 for line in response.iter_lines(decode_unicode=False): if not line.startswith(b"data: ") or line[6:] == b"[DONE]": continue event = json.loads(line[6:]) + if "error" in event: + raise RuntimeError(f"Server stream error: {event['error']}") events.append(event) + # Native streams can withhold token IDs while buffering incomplete UTF-8. + # Their cumulative counter includes that work, including the final event. + if not data["external_server"] and "tokens_predicted" in event: + predicted = event["tokens_predicted"] + if predicted < native_tokens_predicted: + raise RuntimeError("Server token counter decreased during streaming") + token_arrival_times.extend([time()] * (predicted - native_tokens_predicted)) + native_tokens_predicted = predicted + continue if event.get("stop"): continue # Count native token IDs, excluding empty begin/progress events. @@ -151,7 +163,8 @@ def send_prompt(data: dict) -> tuple[float, list[float]]: Path(data["results_dir"]).mkdir(parents=True, exist_ok=True) Path(data["results_dir"], f"request-{data['request_index']:04d}.json").write_text( json.dumps({"prompt": data["prompt"], "request": json_data, "timings": timing, - "events": events, "token_arrival_times": token_arrival_times}, indent=2)) + "events": events, "token_arrival_times": token_arrival_times, + "submitted_at": t_submit, "completed_at": time()}, indent=2)) return (t_submit, token_arrival_times) From a6a1612ee3969b06e7958954b23af30ec3bcb84e Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 23 Oct 2026 07:34:15 +0200 Subject: [PATCH 38/65] openvino: document UD split and unified server benchmarks --- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 24 +- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 234 ++++++++++++++++++ .../dev_doc/benchmarks/qwen36_ud_mmlu.py | 127 ++++++++++ 3 files changed, 375 insertions(+), 10 deletions(-) create mode 100644 ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md create mode 100644 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md index 8d4fb485cff8..a09c47256ce0 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -976,7 +976,7 @@ python3 tmp/kv-slice-20261022/summary.py 65536 ``` -## MTP regression investigation after branch cleanup (2026-10-22, in progress) +## MTP regression investigation after branch cleanup (2026-10-22) Matched control: target Qwen3.6 UD Q4_K_M, GPU, `q4_asym64_all`, native softplus, `-np 4 -c 8192 -t 2 -tb 2`, two MTP drafts, greedy sampling, @@ -1005,8 +1005,9 @@ The subsequent allocation fix below resolves the large transfers. A llama input- experiment did not remove these transfers or improve decode and was reverted. Artifacts and effective commands are in `tmp/mtp-regression-20261022/`. -The default rotation repeat measured 43.820 t/s; the large-context batch/MMLU matrix is pending. -MMLU uses the `cais/mmlu`, `all`, test split's first 100 question texts, with +The default rotation repeat measured 43.820 t/s. The expanded large-context +batch/MMLU matrix is documented in [QWEN36-UD-MULTISLOT-BENCHMARK.md](QWEN36-UD-MULTISLOT-BENCHMARK.md). +MMLU uses the `cais/mmlu`, `all`, test split's first eight question texts, with chat templating and 512 generated tokens per request; question lengths are measured rather than padded to exact targets. Native server timing JSON is saved separately from stream-arrival plots. The benchmark counts native token @@ -1054,8 +1055,9 @@ Compiled weights are approximately 18 GiB. Runtime temporaries, retained allocations, and shape-dependent execution therefore need investigation. The np4 MMLU MTP startup confirmed 131,072 context per slot with a total 524,288 allocation; it produced no completed responses before exiting. -No valid four-slot MMLU aggregate or complete batch matrix is available yet. -An allocation audit is being added temporarily to identify growing buffers. +That initial attempt supplied no valid four-slot MMLU aggregate. The temporary +allocation audit below identified the growing buffers; the completed split +batch matrix is in the expanded benchmark report linked above. The default `-b 2048 -ub 512` allocation audit completed 32K prefill/decode. @@ -1067,12 +1069,12 @@ The caller-output rebinding paths replace pooled producer outputs; experimental fixes release previous ownership and update capacity before adopting borrowed Result storage. The first matched 32K experiment completed at 384.03 prefill and 13.91 decode t/s, but its 64K run still exhausted memory and was terminated. -A second rebinding path is now corrected and under validation. These memory -fixes are not yet committed. All subsequent measurements use default batch and +The second rebinding path was subsequently corrected and committed as +`38aaf24a07`; its validation is described below. All subsequent measurements use default batch and microbatch sizes, as requested; no additional alternate-UB experiments are planned. -The second caller-output bookkeeping fix completed the formerly failing 64K +Committed OpenVINO fix `38aaf24a07` (pushed to `zijun`) completed the formerly failing 64K prompt with default batch/microbatch and 128K context: 503.80 prefill t/s, 6.37 decode t/s (130.083 s prefill, 80.362 s decode). System memory fluctuated around 30–34 GiB during much of the run instead of monotonically reaching the @@ -1080,5 +1082,7 @@ around 30–34 GiB during much of the run instead of monotonically reaching the fix releases a primitive's pooled output ownership before replacing its buffer in `set_output_memory`, and also handles direct producer borrowing from an optimized Result while refreshing its capacity. No existing operation contract -or kernel arithmetic changes. Four-stream validation is now running with -524,288 total context and default batch/microbatch sizes. +or kernel arithmetic changes. Four-stream validation completed all 1K/8K/32K/64K cases with +524,288 total context and default batch/microbatch sizes. Four active 64K +prompts measured 448.62 aggregate prefill t/s and 5.20 aggregate decode t/s. +The full table and comparison methodology are in the expanded benchmark report. diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md new file mode 100644 index 000000000000..dbbe4b796a1c --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -0,0 +1,234 @@ +# Qwen3.6 UD multi-slot benchmark (2026-10-23) + +Status: all 16 OpenVINO/Vulkan split/unified server cases and the split +OpenVINO four-slot batched matrix are complete. Remaining matched long-prompt +batched matrices are running. Results are included only after successful +completion and token-count validation. + +## Model and runtime + +- Model: `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`. +- Hardware: Intel Arc B390 integrated GPU, approximately 62 GiB usable system RAM. +- llama.cpp source: `dd06588b1`; OpenVINO source: `38aaf24a07` on + `qwen-mtp-openvino-checkpoint`. +- Release builds, default batch 2048 and microbatch 512; no batch-size overrides. + Both use the default two inference and batch threads on this machine. +- OpenVINO uses GPU, native softplus and `q4_asym64_all`. Recurrent caches use the + default rotation implementation. Attention KV slicing is enabled; it currently + applies to a single physical attention-cache stream and therefore supports + unified KV but falls back to full-capacity bindings for split four-stream KV. +- Vulkan uses the stored GGUF quantization. These are backend configuration + comparisons, not comparisons of identical compressed weight representations. +- GPU workloads run serially. Cache population is excluded from timed tests; + OpenVINO measurements use compiled-model cache-only loading. + +The Vulkan build uses a clean detached checkout of the same llama.cpp commit, +with `CMAKE_BUILD_TYPE=Release` and `GGML_VULKAN=ON`. This excludes local, +unconditional graph-dump instrumentation and the Debug build at `build/vulkan`. +The OpenVINO binary was rebuilt after reverting an experimental input fallback. + +## Batched benchmark + +`llama-batched-bench` uses random token IDs and does not run MTP. Each sequence +gets the stated prompt length and 512 decode steps. No prompt sharing is enabled. +All throughput values in its output are aggregate across the active sequences. + +```bash +MODEL="$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_NATIVE_SOFTPLUS=1 +export GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all +export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR="$PWD/tmp/mtp-regression-20261022/rotation-cache" +export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 + +build/MtpOVPerf/bin/llama-batched-bench -m "$MODEL" -c 131072 \ + -npp 1024,8192,32768,65536 -ntg 512 -npl 1 +build/MtpOVPerf/bin/llama-batched-bench -m "$MODEL" -c 524288 \ + -npp 1024,8192,32768,65536 -ntg 512 -npl 1,4 +build/MtpOVPerf/bin/llama-batched-bench -m "$MODEL" -c 524288 \ + -npp 1024,8192,32768,65536 -ntg 512 -npl 1,4 --kv-unified +``` + +`GGML_OPENVINO_DISABLE_KV_SLICE` and +`GGML_OPENVINO_RECURRENT_CACHE_INPLACE` are unset. The split one-slot allocation +is 128K; split four-slot allocation is 128K per slot. Unified KV uses one 512K +pool, allowing the same aggregate capacity without reserving equal slot regions. +Vulkan uses the same commands with the clean Release binary path. + +Completed split OpenVINO four-slot allocation, including one-active controls: + +| Prompt/sequence | Active sequences | Aggregate prefill t/s | Aggregate decode t/s | +|---:|---:|---:|---:| +| 1,024 | 1 | 405.21 | 4.55 | +| 1,024 | 4 | 636.96 | 26.70 | +| 8,192 | 1 | 696.17 | 5.08 | +| 8,192 | 4 | 798.97 | 20.93 | +| 32,768 | 1 | 588.60 | 4.04 | +| 32,768 | 4 | 627.16 | 11.10 | +| 65,536 | 1 | 455.76 | 2.73 | +| 65,536 | 4 | 448.62 | 5.20 | + +Raw log: `tmp/mtp-regression-20261022/pool-v2-np4.log`. These low one-active +results are measured with four physical split cache streams allocated and the +current full-cache binding fallback. They are not the one-slot baseline. + +## Server benchmark + +The matrix has two backends, split/unified KV, MTP off/on, and request concurrency +1/4. All server cases allocate four slots and 524288 total attention-cache tokens. +Each case sends the first eight question texts from `cais/mmlu`, `all`, test, +using the native chat template and `/completion` endpoint. Greedy generation +requests exactly 512 tokens with `ignore_eos=true` and `cache_prompt=false`. +The question lengths are measured with `/tokenize`; they are not padded to +1K/8K/32K/64K. The long-context prompt matrix belongs to the batched tests above. +This uses MMLU as natural input text, not as an accuracy evaluation. + +Server arguments, in addition to the common model/configuration above: + +```bash +llama-server -m "$MODEL" -np 4 -c 524288 --temp 0 +llama-server -m "$MODEL" -np 4 -c 524288 --temp 0 --kv-unified +llama-server -m "$MODEL" -np 4 -c 524288 --temp 0 \ + --spec-type draft-mtp --spec-draft-n-max 2 +llama-server -m "$MODEL" -np 4 -c 524288 --temp 0 --kv-unified \ + --spec-type draft-mtp --spec-draft-n-max 2 +``` + +The wrapper imports `scripts/server-bench.py`, loads the saved local MMLU parquet, +and separates server slot count (always four) from client concurrency (one or +four). Native request timing JSON and stream arrival times are saved. Server SSE +errors fail the run immediately. A completed case must have eight responses, +each with native `predicted_n=512` and a final cumulative +`tokens_predicted=512`, and no +draft-computation failure or missing compiled-model signature in the server log. +The first concurrent unified-MTP attempt completed output by falling back after +missing draft signatures; that attempt is invalid and excluded. Cache population exercises explicit active-slot subsets and full-length +requests before repeating the test. Backend draft sampling adds ports for the +active sequence IDs, so a four-request startup alone does not populate every +valid intermediate graph signature. + +- Native decode t/s/request is the mean of the eight server-reported decode rates. +- End-to-end aggregate t/s is 4096 native generated tokens divided by the + benchmark's client-observed duration, including prompt processing and scheduling. +- Native streams may withhold individual token-ID events while accumulating an + incomplete UTF-8 character. `server-bench.py` uses the cumulative + `tokens_predicted` counter, including the final event, to count this work. + Buffered tokens share the observation time when the counter advances; this + cannot recover their individual GPU completion times. One saved Vulkan + unified non-MTP sequential run contains 4086 partial token IDs but all 4096 + generated tokens are confirmed by final counters and native timing JSON. Its + raw arrivals are preserved, and aggregate throughput uses 4096. Earlier runs + whose counts already match are unaffected. +- Draft acceptance is the sum of accepted/generated drafts in per-request logs. + +A reusable wrapper is saved as +[`benchmarks/qwen36_ud_mmlu.py`](benchmarks/qwen36_ud_mmlu.py). It needs the +Python dependencies used by `scripts/server-bench.py` plus `pyarrow`, and a local +MMLU `all` test parquet at `tmp/mmlu-dataset/all/test-00000-of-00001.parquet` +(or the path in `UD_MMLU_PARQUET`). Example full server matrix: + +```bash +export UD_VULKAN_BIN_DIR=/home/zijun/llama-benchmark-clean/build/vulkan/bin +export UD_LLAMA_COMMIT=dd06588b1 +export UD_OPENVINO_COMMIT=38aaf24a07 +for backend in ov vulkan; do + for layout in split unified; do + for mode in off mtp; do + for concurrency in 1 4; do + python ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py \ + "$backend" "$layout" "$mode" "$concurrency" + done + done + done +done +``` + +OV defaults to cache-only loading and the cache path above. Populate missing +signatures separately with `UD_PRIME_SUBSETS=1 UD_CACHE_ONLY=0 UD_TEST_CTX=8192` +and a distinct `UD_RUN_LABEL`, then rerun the full case in cache-only mode. +`UD_OV_BIN_DIR`, `UD_VULKAN_BIN_DIR`, `UD_MODEL`, `UD_COMPILED_CACHE`, and +`UD_BENCH_DIR` can redirect builds, model, cache and output locations. Use a clean +Release Vulkan build; the local `build/vulkan` used for diagnostics is unsuitable +for reproducing this comparison. + +Raw artifacts and the serial matrix runner: `tmp/ud-backend-matrix-20261023/`. +The runner records effective environment and commit provenance for each server +case. `summary.md`, `server-summary.json`, and `batch-summary.json` are generated +from completed responses and raw logs. + +Completed server matrix: + +| Backend | KV | MTP | Requests in flight | Native decode t/s/request | End-to-end aggregate t/s | Draft acceptance | +|---|---|---|---:|---:|---:|---:| +| OpenVINO | Split | On | 1 | 8.62 | 7.62 | 2632/2905 (90.6%) | +| OpenVINO | Split | On | 4 | 3.88 | 9.11 | 2409/3348 (72.0%) | +| OpenVINO | Split | Off | 1 | 4.54 | 4.43 | - | +| OpenVINO | Split | Off | 4 | 6.47 | 22.90 | - | +| OpenVINO | Unified | On | 1 | 51.35 | 48.11 | 2623/2922 (89.8%) | +| OpenVINO | Unified | On | 4 | 25.91 | 90.98 | 2622/2923 (89.7%) | +| OpenVINO | Unified | Off | 1 | 36.47 | 35.07 | - | +| OpenVINO | Unified | Off | 4 | 21.73 | 80.55 | - | +| Vulkan | Split | On | 1 | 24.48 | 23.23 | 2617/2933 (89.2%) | +| Vulkan | Split | On | 4 | 8.27 | 31.08 | 2607/2955 (88.2%) | +| Vulkan | Split | Off | 1 | 16.81 | 16.28 | - | +| Vulkan | Split | Off | 4 | 8.16 | 31.00 | - | +| Vulkan | Unified | On | 1 | 23.88 | 22.62 | 2625/2919 (89.9%) | +| Vulkan | Unified | On | 4 | 12.88 | 46.84 | 2611/2945 (88.7%) | +| Vulkan | Unified | Off | 1 | 16.66 | 16.13 | - | +| Vulkan | Unified | Off | 4 | 8.72 | 31.06 | - | + +## Interpretation and limits + +For these short MMLU prompts in a large unified allocation, OpenVINO MTP increases +sequential aggregate throughput by 37.2% (35.07 to 48.11 t/s) and four-request +aggregate throughput by 12.9% (80.55 to 90.98 t/s). With Vulkan, unified MTP raises +sequential throughput from 16.13 to 22.62 t/s and four-request throughput from +31.06 to 46.84 t/s. Neither comparison controls the model's numerical weights +across backends, since OpenVINO requantizes them. + +OpenVINO's split four-slot MTP result is much lower than its unified result at +this allocation. Its sequential split run accepts 90.6% of drafts, close to +the unified 89.8%, yet reaches only 8.62 native decode t/s versus 51.35. +Thus poor acceptance does not explain the sequential gap. Full-capacity attention-cache binding remains a candidate +cost: slicing currently handles only one physical stream. Recurrent state size +is determined by sequence count and snapshot capacity, not attention-context +length, so the large context does not itself enlarge the recurrent caches. +The split concurrent run also accepts 72.0% of drafts versus 89.7% for unified; +this changes the amount of verification work. System memory during the split +concurrent run varied around 41–54 GiB. These measurements do not isolate copying, +recurrent kernels, attention, memory pressure or numerical/scheduling differences +well enough to assign the entire layout gap to one of them. At four-request +concurrency, split MTP reaches 9.11 aggregate t/s versus non-MTP 22.90; unified +MTP reaches 90.98 versus non-MTP 80.55. MTP therefore helps unified serving but +hurts the split serving configuration in this large-allocation sample. + +Vulkan's two layouts have almost identical non-MTP aggregate throughput with four +concurrent requests (31.00 versus 31.06 t/s). Its concurrent MTP case gains from +unified KV (31.08 to 46.84 t/s), while its sequential MTP results are close +(23.23 split and 22.62 unified). Vulkan's large-allocation rates are below the earlier small-context controls. +Untimed verbose diagnostics expose a major confound: default `--fit on` can +move expert tensors to `Vulkan_Host` even while reporting all 42/42 layers as +GPU-offloaded. The diagnostic unified-MTP startup reported 43,108 MiB free and +kept 21,087.70 MiB in Vulkan device model storage plus 515.31 MiB host storage. +Subsequent diagnostic starts reported only about 26,700–26,850 MiB free and fit +6,402–8,511 MiB of model tensors into host storage. The split-MTP diagnostic +explicitly overrides expert down/gate/up tensors to `Vulkan_Host`. A layer-count +message therefore does not establish that every expert matmul stays on the GPU. +The Vulkan backend's `supports_buft` accepts its device buffer type rather than +`Vulkan_Host`, so expert host placement can change scheduler placement as well +as memory access costs. + +These diagnostics occurred after the timed server matrix, so their individual +placement values cannot be retroactively assigned to timed cases. They do show +that default fitting can change the workload with the driver-reported budget, +which varied substantially across successive process starts. The lower Vulkan +server rates must be interpreted as configured-default end-to-end results, not +a controlled all-GPU kernel comparison. `llama-batched-bench` loads the model +and context directly and does not call `common_fit_params`; its results do not +have this server-specific automatic-fit confound. + +This is an eight-request throughput sample, with one pass per case. MMLU question +texts average 53.25 templated tokens in this sample. It tests MTP on natural short +prompts and separately tests long-context non-MTP with random token IDs; it does +not measure long-context MTP, MMLU accuracy, or statistical variation across +repeated benchmark passes. diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py new file mode 100644 index 000000000000..2cbce11fbe7c --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py @@ -0,0 +1,127 @@ +"""Matched native server-bench MMLU runs; server slots and traffic concurrency are independent.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import logging +import pyarrow.parquet as pq +import requests +from concurrent.futures import ThreadPoolExecutor +import itertools +import threading +import time + +if len(sys.argv) != 5: + raise SystemExit('Usage: qwen36_ud_mmlu.py ov|vulkan split|unified off|mtp 1|4') + +root = Path(__file__).resolve().parents[5] +backend, layout, mode, concurrency_text = sys.argv[1:5] +concurrency = int(concurrency_text) +assert backend in ('ov', 'vulkan') and layout in ('split', 'unified') +assert mode in ('off', 'mtp') and concurrency in (1, 4) +base = Path(os.environ.get('UD_BENCH_DIR', str(root / 'tmp/ud-backend-matrix-20261023'))) +label = f'{backend}-{layout}-{mode}-c{concurrency}' +out = base / os.environ.get('UD_RUN_LABEL', label) +out.mkdir(parents=True, exist_ok=True) +(out / 'complete.json').unlink(missing_ok=True) +for response in (out / 'responses').glob('request-*.json'): + response.unlink() +spec = importlib.util.spec_from_file_location('server_bench', root / 'scripts/server-bench.py') +b = importlib.util.module_from_spec(spec) +spec.loader.exec_module(b) +logging.getLogger('httpx').setLevel(logging.WARNING) +parquet = Path(os.environ.get('UD_MMLU_PARQUET', str(root / 'tmp/mmlu-dataset/all/test-00000-of-00001.parquet'))) +questions = pq.read_table(parquet, columns=['question'])['question'].to_pylist() +b.get_prompts_text = lambda name, n: questions[:n] if n >= 0 else questions +original_server = b.get_server + +def get_server(path, log): + os.environ['LLAMA_ARG_N_PARALLEL'] = '4' + try: + server = original_server(path, log) + if os.environ.get('UD_PRIME_SUBSETS') == '1': + address = server['address'] + prompt = requests.post(address + '/apply-template', json={'messages': [{'role': 'user', 'content': questions[0]}]}).json()['prompt'] + def prime_slot(slot): + response = requests.post(address + '/completion', json={'prompt': prompt, 'id_slot': slot, 'n_predict': 16 + slot, 'temperature': 0, 'ignore_eos': True, 'cache_prompt': False}, timeout=600) + response.raise_for_status() + assert response.json()['timings']['predicted_n'] == 16 + slot + for count in (1, 2, 3, 4): + for subset in itertools.combinations(range(4), count): + print('Priming active slots', subset, flush=True) + with ThreadPoolExecutor(max_workers=count) as pool: + list(pool.map(prime_slot, subset)) + if backend == 'ov' and os.environ.get('UD_CACHE_ONLY', '1') == '1': + def reject_missing_signature(): + process = server['process'] + while process.poll() is None: + if Path(log).exists() and 'missing or incompatible compiled model' in Path(log).read_text(): + process.kill() + return + time.sleep(1) + threading.Thread(target=reject_missing_signature, daemon=True).start() + return server + except BaseException: + if 'server' in locals(): + server['process'].terminate() + server['process'].wait() + raise + finally: + os.environ['LLAMA_ARG_N_PARALLEL'] = str(concurrency) + +b.get_server = get_server +for key in list(os.environ): + if key.startswith(('LLAMA_ARG_', 'GGML_OPENVINO_', 'GGML_VULKAN_')) or key == 'LD_PRELOAD': + os.environ.pop(key) +os.environ.update({ + 'LLAMA_ARG_MODEL': os.environ.get('UD_MODEL', str(Path.home() / 'models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf')), + 'LLAMA_ARG_N_PARALLEL': str(concurrency), + 'LLAMA_ARG_CTX_SIZE': os.environ.get('UD_TEST_CTX', '524288'), + 'LLAMA_ARG_KV_UNIFIED': '1' if layout == 'unified' else '0', + 'LLAMA_ARG_PORT': '18931', + 'LLAMA_ARG_TEMPERATURE': '0', +}) +if os.environ.get('UD_LOG_VERBOSITY'): + os.environ['LLAMA_ARG_LOG_VERBOSITY'] = os.environ['UD_LOG_VERBOSITY'] +if backend == 'ov': + binary = Path(os.environ.get('UD_OV_BIN_DIR', str(root / 'build/MtpOVPerf/bin'))) / 'llama-server' + os.environ.update({ + 'GGML_OPENVINO_DEVICE': 'GPU', + 'GGML_OPENVINO_NATIVE_SOFTPLUS': '1', + 'GGML_OPENVINO_REQUANT_KQUANT': 'q4_asym64_all', + 'GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR': os.environ.get('UD_COMPILED_CACHE', str(root / 'tmp/mtp-regression-20261022/rotation-cache')), + 'GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY': os.environ.get('UD_CACHE_ONLY', '1'), + }) +else: + binary = Path(os.environ.get('UD_VULKAN_BIN_DIR', str(root / 'build/vulkan/bin'))) / 'llama-server' +if mode == 'mtp': + os.environ['LLAMA_ARG_SPEC_TYPE'] = 'draft-mtp' + os.environ['LLAMA_ARG_SPEC_DRAFT_N_MAX'] = '2' +n_prompts = int(os.environ.get('UD_N_PROMPTS', '8')) +n_predict = int(os.environ.get('UD_N_PREDICT', '512')) +(out / 'effective-env.json').write_text(json.dumps({k:v for k,v in os.environ.items() if k.startswith(('LLAMA_ARG_', 'GGML_OPENVINO_'))}, indent=2)) +(out / 'provenance.json').write_text(json.dumps({ + 'dataset': f'cais/mmlu all test, first {n_prompts} question texts', + 'llama_commit': os.environ.get('UD_LLAMA_COMMIT', subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'], text=True).strip()), + 'harness_commit': subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'], text=True).strip(), + 'openvino_commit': os.environ.get('UD_OPENVINO_COMMIT', 'unspecified'), + 'server_slots': 4, 'request_concurrency': concurrency, 'binary': str(binary), + 'backend': backend, 'layout': layout, 'mode': mode, 'n_predict': n_predict, + 'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest(), + 'dataset_parquet': str(parquet), +}, indent=2)) +os.chdir(out) +b.benchmark(str(binary), str(out / 'server.log'), None, label, 'mmlu', n_prompts, + n_predict, n_predict, 0, str(out / 'responses')) +responses = [json.loads(p.read_text()) for p in sorted((out / 'responses').glob('request-*.json'))] +assert len(responses) == n_prompts, len(responses) +assert all(r['timings']['predicted_n'] == n_predict for r in responses) +assert all(r['events'][-1].get('stop') and r['events'][-1]['tokens_predicted'] == n_predict for r in responses) +assert all(len(r['token_arrival_times']) == n_predict for r in responses) +server_log = (out / 'server.log').read_text() +assert 'missing or incompatible compiled model' not in server_log, 'Missing draft signatures invalidate MTP timing' +assert 'returned -3' not in server_log, 'Draft computation failed' +(out / 'complete.json').write_text(json.dumps({'requests': n_prompts, 'generated_tokens': n_prompts*n_predict}, indent=2)) From 7bcf06e28f106d2e5900490739e36105f1b78766 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 23 Oct 2026 08:18:20 +0200 Subject: [PATCH 39/65] openvino: record Vulkan long-context baseline and GPU-fit controls --- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 32 ++++++++++++++----- .../dev_doc/benchmarks/qwen36_ud_mmlu.py | 3 ++ 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index dbbe4b796a1c..41dcbfca26ec 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -72,6 +72,20 @@ Raw log: `tmp/mtp-regression-20261022/pool-v2-np4.log`. These low one-active results are measured with four physical split cache streams allocated and the current full-cache binding fallback. They are not the one-slot baseline. +Completed Vulkan one-slot matrix (`-npl 1 -c 131072`): + +| Prompt/sequence | Active sequences | Aggregate prefill t/s | Aggregate decode t/s | +|---:|---:|---:|---:| +| 1,024 | 1 | 683.62 | 32.49 | +| 8,192 | 1 | 436.10 | 30.59 | +| 32,768 | 1 | 128.25 | 25.99 | +| 65,536 | 1 | 64.64 | 19.80 | + +Raw log: `tmp/ud-backend-matrix-20261023/batch-vulkan-split-npl1.log`. +The 64K prefill takes 1,013.906 seconds, versus 25.865 seconds for decode. +The four-slot Vulkan split/unified matrices and remaining OpenVINO matrices +are still running; partial rows are excluded from final matrix tables. + ## Server benchmark The matrix has two backends, split/unified KV, MTP off/on, and request concurrency @@ -99,11 +113,10 @@ and separates server slot count (always four) from client concurrency (one or four). Native request timing JSON and stream arrival times are saved. Server SSE errors fail the run immediately. A completed case must have eight responses, each with native `predicted_n=512` and a final cumulative -`tokens_predicted=512`, and no -draft-computation failure or missing compiled-model signature in the server log. +`tokens_predicted=512`, and no draft-computation failure or missing compiled-model signature in the server log. The first concurrent unified-MTP attempt completed output by falling back after -missing draft signatures; that attempt is invalid and excluded. Cache population exercises explicit active-slot subsets and full-length -requests before repeating the test. Backend draft sampling adds ports for the +missing draft signatures; that attempt is invalid and excluded. Cache population +exercises explicit active-slot subsets and full-length requests before repeating the test. Backend draft sampling adds ports for the active sequence IDs, so a four-request startup alone does not populate every valid intermediate graph signature. @@ -189,8 +202,8 @@ across backends, since OpenVINO requantizes them. OpenVINO's split four-slot MTP result is much lower than its unified result at this allocation. Its sequential split run accepts 90.6% of drafts, close to the unified 89.8%, yet reaches only 8.62 native decode t/s versus 51.35. -Thus poor acceptance does not explain the sequential gap. Full-capacity attention-cache binding remains a candidate -cost: slicing currently handles only one physical stream. Recurrent state size +Thus poor acceptance does not explain the sequential gap. Full-capacity +attention-cache binding remains a candidate cost: slicing currently handles only one physical stream. Recurrent state size is determined by sequence count and snapshot capacity, not attention-context length, so the large context does not itself enlarge the recurrent caches. The split concurrent run also accepts 72.0% of drafts versus 89.7% for unified; @@ -205,7 +218,8 @@ hurts the split serving configuration in this large-allocation sample. Vulkan's two layouts have almost identical non-MTP aggregate throughput with four concurrent requests (31.00 versus 31.06 t/s). Its concurrent MTP case gains from unified KV (31.08 to 46.84 t/s), while its sequential MTP results are close -(23.23 split and 22.62 unified). Vulkan's large-allocation rates are below the earlier small-context controls. +(23.23 split and 22.62 unified). Vulkan's large-allocation rates are below the +earlier small-context controls. Untimed verbose diagnostics expose a major confound: default `--fit on` can move expert tensors to `Vulkan_Host` even while reporting all 42/42 layers as GPU-offloaded. The diagnostic unified-MTP startup reported 43,108 MiB free and @@ -225,7 +239,9 @@ which varied substantially across successive process starts. The lower Vulkan server rates must be interpreted as configured-default end-to-end results, not a controlled all-GPU kernel comparison. `llama-batched-bench` loads the model and context directly and does not call `common_fit_params`; its results do not -have this server-specific automatic-fit confound. +have this server-specific automatic-fit confound. A separate server control +with `UD_FORCE_GPU=1` (explicit `-ngl 99 -fit off`) is queued after the requested +matrix; it will be reported separately from the default-fit results. This is an eight-request throughput sample, with one pass per case. MMLU question texts average 53.25 templated tokens in this sample. It tests MTP on natural short diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py index 2cbce11fbe7c..ba16ccf136b4 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py @@ -84,6 +84,9 @@ def reject_missing_signature(): 'LLAMA_ARG_PORT': '18931', 'LLAMA_ARG_TEMPERATURE': '0', }) +if os.environ.get('UD_FORCE_GPU') == '1': + os.environ['LLAMA_ARG_N_GPU_LAYERS'] = '99' + os.environ['LLAMA_ARG_FIT'] = '0' if os.environ.get('UD_LOG_VERBOSITY'): os.environ['LLAMA_ARG_LOG_VERBOSITY'] = os.environ['UD_LOG_VERBOSITY'] if backend == 'ov': From 056e0a63b3866be1f2d3acea8b383c5691228a11 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 23 Oct 2026 11:42:23 +0200 Subject: [PATCH 40/65] openvino: finalize UD benchmark report and MTP comparison Assisted-by: Codex --- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 370 ++++++++++++++++-- 1 file changed, 330 insertions(+), 40 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index 41dcbfca26ec..5cc8b18a98f3 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -1,9 +1,8 @@ # Qwen3.6 UD multi-slot benchmark (2026-10-23) -Status: all 16 OpenVINO/Vulkan split/unified server cases and the split -OpenVINO four-slot batched matrix are complete. Remaining matched long-prompt -batched matrices are running. Results are included only after successful -completion and token-count validation. +Status: the campaign is finished. All 16 original server cases and all eight +Vulkan full-GPU server reruns completed. Of 40 batched timing rows, 32 completed +and eight were skipped at user request. No benchmark remains pending. ## Model and runtime @@ -27,12 +26,173 @@ with `CMAKE_BUILD_TYPE=Release` and `GGML_VULKAN=ON`. This excludes local, unconditional graph-dump instrumentation and the Debug build at `build/vulkan`. The OpenVINO binary was rebuilt after reverting an experimental input fallback. + +## Result matrices + +The campaign is finished: 32 batched timing rows, 16 original server cases and +8 Vulkan server reruns completed. Eight remaining batched rows were canceled. +No benchmark is pending. All completed cases decode 512 tokens per sequence. + +### Batched-bench: prefill time and decode throughput + +Each cell is **prefill seconds @ aggregate decode tokens/s**. For `-npl 1,4`, +the two entries are **one active / four active sequences** with four slots +allocated. `Skipped` means canceled, not zero throughput. `1K/8K/32K/64K` +mean 1024/8192/32768/65536 prompt tokens per sequence. + +Batched-bench does not sample or stream output tokens, so it does not measure +TTFT. Its synchronized prefill duration is shown as a prefill-only proxy: it +excludes model loading, sampling, server scheduling and transport. With four +active sequences it is the time to prefill all four, not a per-request TTFT. + +| Backend/configuration | 1K prompt | 8K prompt | 32K prompt | 64K prompt | +|---|---:|---:|---:|---:| +| OV `-npl 1` | 1.244 @ 34.75 | 9.062 @ 27.71 | 44.871 @ 14.19 | Skipped | +| OV `-npl 1,4` split | 2.527 @ 4.55 / 6.431 @ 26.70 | 11.767 @ 5.08 / 41.013 @ 20.93 | 55.671 @ 4.04 / 208.992 @ 11.10 | 143.794 @ 2.73 / 584.334 @ 5.20 | +| OV `-npl 1,4 --kv-unified` | 1.218 @ 35.51 / 3.734 @ 83.10 | 8.469 @ 27.95 / 47.204 @ 43.12 | 50.438 @ 14.32 / 1279.251 @ 7.72 | Skipped / Skipped | +| Vulkan `-npl 1` | 1.498 @ 32.49 | 18.785 @ 30.59 | 255.503 @ 25.99 | 1013.906 @ 19.80 | +| Vulkan `-npl 1,4` split | 1.508 @ 32.45 / 5.931 @ 72.39 | 18.901 @ 30.31 / 75.542 @ 65.11 | 258.362 @ 25.99 / 1021.572 @ 41.53 | Skipped / Skipped | +| Vulkan `-npl 1,4 --kv-unified` | 1.492 @ 32.44 / 5.964 @ 71.82 | 18.785 @ 30.69 / 75.933 @ 55.31 | 254.584 @ 25.42 / Skipped | Skipped / Skipped | + +Memory usage was not recorded for these batched timing rows. The one saved +`/proc/meminfo` snapshot describes system memory before a run, so it is not +reported as benchmark memory usage. No additional tests were run for this table. + +### Server: TTFT and end-to-end output throughput (includes prefill) + +Each cell is **mean TTFT seconds @ end-to-end aggregate output tokens/s** over eight +MMLU questions (35-73 templated tokens, mean 53.25). Every server allocates +four slots and 524288 total context tokens. Columns select one or four requests +in flight; these are short natural prompts, not the long batched prompt matrix. + +End-to-end output throughput is total generated tokens divided by the total +benchmark elapsed time. Its denominator includes prefill, decode, scheduling +and client overhead; its numerator counts generated tokens only. It is **not +decode throughput** and should not be compared directly with the decode t/s in +the batched-bench matrix. The server's decode-only rates are in the next table. + +TTFT is the client-observed interval from request submission to the first +counted token arrival, including template application, scheduling, prompt +processing and transport. It is the harness's saved "Average prompt latency", +checked against per-request timestamps when those were saved. Stream buffering +can delay the first observed token. Aggregate throughput includes prompt time +and scheduling; native decode rates are shown separately below. + +The primary Vulkan rows use the verified `-fit off -ngl 99` reruns. OV uses the +original completed cases with cache-only loading. OV requantization and stored +Vulkan GGUF weights differ, as described under Model and runtime. + +| Backend/configuration | 1 request: TTFT s @ end-to-end t/s | 4 requests: TTFT s @ end-to-end aggregate t/s | +|---|---:|---:| +| OV, split, MTP off | 2.888 @ 4.43 | 10.355 @ 22.90 | +| OV, split, MTP on | 7.757 @ 7.62 | 39.164 @ 9.11 | +| OV, unified, MTP off | 0.582 @ 35.07 | 1.888 @ 80.55 | +| OV, unified, MTP on | 0.674 @ 48.11 | 2.102 @ 90.98 | +| Vulkan full GPU, split, MTP off | 0.812 @ 30.26 | 2.615 @ 61.41 | +| Vulkan full GPU, split, MTP on | 0.891 @ 44.79 | 1.692 @ 52.05 | +| Vulkan full GPU, unified, MTP off | 0.800 @ 30.33 | 5.961 @ 55.71 | +| Vulkan full GPU, unified, MTP on | 0.915 @ 44.00 | 2.903 @ 48.59 | + +### Server: decode throughput per request (excludes prefill) + +These values are the mean server-reported tokens/s per request during decode. +Prompt processing time is excluded. Four-request values here are **per request, +not aggregate**. Multiplying the mean by four gives only an approximate +aggregate decode rate: requests do not necessarily start and finish decoding +together, and this is an arithmetic mean of per-request rates. + +| Backend/configuration | 1 request: decode t/s per request | 4 requests: decode t/s per request | +|---|---:|---:| +| OV, split, MTP off | 4.54 | 6.47 | +| OV, split, MTP on | 8.62 | 3.88 | +| OV, unified, MTP off | 36.47 | 21.73 | +| OV, unified, MTP on | 51.35 | 25.91 | +| Vulkan full GPU, split, MTP off | 31.74 | 16.63 | +| Vulkan full GPU, split, MTP on | 48.54 | 13.87 | +| Vulkan full GPU, unified, MTP off | 31.79 | 16.60 | +| Vulkan full GPU, unified, MTP on | 47.71 | 13.29 | + +MTP comparison using the same **decode-only tokens/s per request**, with +**MTP off → MTP on** in each cell. Vulkan uses the verified full-GPU runs. +All cases allocate four server slots; the columns select one or four requests +in flight. + +| Backend/layout | One request: off → on | Four requests: off → on | +|---|---:|---:| +| OV split | 4.54 → 8.62 | 6.47 → 3.88 | +| OV unified | 36.47 → 51.35 | 21.73 → 25.91 | +| Vulkan split | 31.74 → 48.54 | 16.63 → 13.87 | +| Vulkan unified | 31.79 → 47.71 | 16.60 → 13.29 | + +MTP improves decode throughput in every one-request case. With four requests +in flight, it improves OV unified throughput but lowers OV split and Vulkan +throughput in these measurements. + +For reference, historical Vulkan default-fit results in the same TTFT @ +aggregate-throughput format. Expert placement was not controlled in these runs; +they are excluded from the primary Vulkan comparison above. + +| Backend/configuration | 1 request in flight | 4 requests in flight | +|---|---:|---:| +| Vulkan default fit, split, MTP off | 1.025 @ 16.28 | 3.439 @ 31.00 | +| Vulkan default fit, split, MTP on | 1.126 @ 23.23 | 2.773 @ 31.08 | +| Vulkan default fit, unified, MTP off | 1.052 @ 16.13 | 6.886 @ 31.06 | +| Vulkan default fit, unified, MTP on | 1.148 @ 22.62 | 3.080 @ 46.84 | + +### Available server memory measurements + +Each cell is **main-context device / host allocations in GiB**, from llama.cpp's +shutdown memory breakdown (model + main cache + main compute buffers). This is +an allocation tally, not peak process or whole-system memory usage. Host and +device storage both occupy DRAM on this integrated GPU. `N/R` means not recorded +in the timed run; diagnostic measurements from other runs are not substituted. + +The MTP rows omit the separate draft context, output buffers and allocations +outside that main-context breakdown. In the Vulkan MTP startup logs, the draft +context additionally allocates 1024 MiB of attention KV, 170.02 / 554.02 MiB +of device compute and 136.02 / 520.02 MiB of host compute for split / unified, +plus its output buffer. Repeated reserve messages are not additional allocations. +Thus these cells must not be interpreted as total MTP memory or compared with +unrecorded OV peaks. + +| Backend/configuration | 1 request in flight | 4 requests in flight | +|---|---:|---:| +| OV, split, MTP off | N/R | N/R | +| OV, split, MTP on | N/R | N/R | +| OV, unified, MTP off | N/R | N/R | +| OV, unified, MTP on | N/R | N/R | +| Vulkan full GPU, split, MTP off | 30.54 / 0.64 | 30.54 / 0.64 | +| Vulkan full GPU, split, MTP on | 31.55 / 0.64 | 31.55 / 0.64 | +| Vulkan full GPU, unified, MTP off | 30.92 / 1.02 | 30.92 / 1.02 | +| Vulkan full GPU, unified, MTP on | 31.93 / 1.02 | 31.93 / 1.02 | + + + ## Batched benchmark `llama-batched-bench` uses random token IDs and does not run MTP. Each sequence gets the stated prompt length and 512 decode steps. No prompt sharing is enabled. All throughput values in its output are aggregate across the active sequences. +The executable has no repetition loop or `llama-bench`-style `-r` repetitions. +It runs each `(prompt length, decode length, active sequence count)` combination +once, after one 16-token warmup per process. Thus the `-npl 1` command contains +four measured cases, and `-npl 1,4` contains eight. `-ntg 512` means 512 decode +steps per sequence; with four active sequences, each step processes four +inputs and the measured decode totals 2048 tokens. Default microbatch 512 +makes 64K prefill require 128 microbatches per sequence, or 512 microbatches +for four sequences. These are required model evaluations, not benchmark +repetitions that can be removed while retaining the specified prompt length. + +Prefill dominates the slow Vulkan cases: four independent 32K sequences took +1021.572 seconds to prefill versus 49.309 seconds to decode. Reducing decode +from 512 to 128 would save roughly 37 seconds in that case, leaving the +17-minute prefill. The requested 512 decode steps are retained. On interruption, +the former whole-matrix runner repeated its completed shorter rows; those +restarts are not intentional repetitions. Results are now checkpointed per +prompt length, and remaining long-prompt batched cases are skipped at user request. +The full-GPU Vulkan server reruns then completed within the half-hour time budget. + ```bash MODEL="$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" export GGML_OPENVINO_DEVICE=GPU @@ -53,38 +213,71 @@ build/MtpOVPerf/bin/llama-batched-bench -m "$MODEL" -c 524288 \ `GGML_OPENVINO_RECURRENT_CACHE_INPLACE` are unset. The split one-slot allocation is 128K; split four-slot allocation is 128K per slot. Unified KV uses one 512K pool, allowing the same aggregate capacity without reserving equal slot regions. -Vulkan uses the same commands with the clean Release binary path. - -Completed split OpenVINO four-slot allocation, including one-active controls: - -| Prompt/sequence | Active sequences | Aggregate prefill t/s | Aggregate decode t/s | -|---:|---:|---:|---:| -| 1,024 | 1 | 405.21 | 4.55 | -| 1,024 | 4 | 636.96 | 26.70 | -| 8,192 | 1 | 696.17 | 5.08 | -| 8,192 | 4 | 798.97 | 20.93 | -| 32,768 | 1 | 588.60 | 4.04 | -| 32,768 | 4 | 627.16 | 11.10 | -| 65,536 | 1 | 455.76 | 2.73 | -| 65,536 | 4 | 448.62 | 5.20 | - -Raw log: `tmp/mtp-regression-20261022/pool-v2-np4.log`. These low one-active -results are measured with four physical split cache streams allocated and the -current full-cache binding fallback. They are not the one-slot baseline. - -Completed Vulkan one-slot matrix (`-npl 1 -c 131072`): - -| Prompt/sequence | Active sequences | Aggregate prefill t/s | Aggregate decode t/s | -|---:|---:|---:|---:| -| 1,024 | 1 | 683.62 | 32.49 | -| 8,192 | 1 | 436.10 | 30.59 | -| 32,768 | 1 | 128.25 | 25.99 | -| 65,536 | 1 | 64.64 | 19.80 | - -Raw log: `tmp/ud-backend-matrix-20261023/batch-vulkan-split-npl1.log`. -The 64K prefill takes 1,013.906 seconds, versus 25.865 seconds for decode. -The four-slot Vulkan split/unified matrices and remaining OpenVINO matrices -are still running; partial rows are excluded from final matrix tables. +Vulkan uses the same commands with the clean Release binary path. These commands +describe the original full matrix; rows labeled Skipped were canceled before +completion and are not measured results. + + +Batched matrix status. Values are aggregate tokens/s; `Skipped` marks a +user-canceled long-prompt case. All other rows completed. +Each completed timing row finished its prefill and all 512 +synchronized decode steps. Completed rows from an interrupted matrix are +retained; they do not imply that its other prompt lengths completed. + +| Backend | KV | Allocated sequences | Prompt/sequence | Active sequences | Prefill t/s | Decode t/s | Status | +|---|---|---:|---:|---:|---:|---:|---| +| OpenVINO | Split | 1 | 1,024 | 1 | 823.14 | 34.75 | Complete | +| OpenVINO | Split | 1 | 8,192 | 1 | 904.00 | 27.71 | Complete | +| OpenVINO | Split | 1 | 32,768 | 1 | 730.27 | 14.19 | Complete | +| OpenVINO | Split | 1 | 65,536 | 1 | - | - | Skipped | +| OpenVINO | Split | 4 | 1,024 | 1 | 405.21 | 4.55 | Complete | +| OpenVINO | Split | 4 | 1,024 | 4 | 636.96 | 26.70 | Complete | +| OpenVINO | Split | 4 | 8,192 | 1 | 696.17 | 5.08 | Complete | +| OpenVINO | Split | 4 | 8,192 | 4 | 798.97 | 20.93 | Complete | +| OpenVINO | Split | 4 | 32,768 | 1 | 588.60 | 4.04 | Complete | +| OpenVINO | Split | 4 | 32,768 | 4 | 627.16 | 11.10 | Complete | +| OpenVINO | Split | 4 | 65,536 | 1 | 455.76 | 2.73 | Complete | +| OpenVINO | Split | 4 | 65,536 | 4 | 448.62 | 5.20 | Complete | +| OpenVINO | Unified | 4 | 1,024 | 1 | 840.45 | 35.51 | Complete | +| OpenVINO | Unified | 4 | 1,024 | 4 | 1097.04 | 83.10 | Complete | +| OpenVINO | Unified | 4 | 8,192 | 1 | 967.34 | 27.95 | Complete | +| OpenVINO | Unified | 4 | 8,192 | 4 | 694.17 | 43.12 | Complete | +| OpenVINO | Unified | 4 | 32,768 | 1 | 649.66 | 14.32 | Complete | +| OpenVINO | Unified | 4 | 32,768 | 4 | 102.46 | 7.72 | Complete | +| OpenVINO | Unified | 4 | 65,536 | 1 | - | - | Skipped | +| OpenVINO | Unified | 4 | 65,536 | 4 | - | - | Skipped | +| Vulkan | Split | 1 | 1,024 | 1 | 683.62 | 32.49 | Complete | +| Vulkan | Split | 1 | 8,192 | 1 | 436.10 | 30.59 | Complete | +| Vulkan | Split | 1 | 32,768 | 1 | 128.25 | 25.99 | Complete | +| Vulkan | Split | 1 | 65,536 | 1 | 64.64 | 19.80 | Complete | +| Vulkan | Split | 4 | 1,024 | 1 | 679.07 | 32.45 | Complete | +| Vulkan | Split | 4 | 1,024 | 4 | 690.61 | 72.39 | Complete | +| Vulkan | Split | 4 | 8,192 | 1 | 433.42 | 30.31 | Complete | +| Vulkan | Split | 4 | 8,192 | 4 | 433.77 | 65.11 | Complete | +| Vulkan | Split | 4 | 32,768 | 1 | 126.83 | 25.99 | Complete | +| Vulkan | Split | 4 | 32,768 | 4 | 128.30 | 41.53 | Complete | +| Vulkan | Split | 4 | 65,536 | 1 | - | - | Skipped | +| Vulkan | Split | 4 | 65,536 | 4 | - | - | Skipped | +| Vulkan | Unified | 4 | 1,024 | 1 | 686.38 | 32.44 | Complete | +| Vulkan | Unified | 4 | 1,024 | 4 | 686.81 | 71.82 | Complete | +| Vulkan | Unified | 4 | 8,192 | 1 | 436.08 | 30.69 | Complete | +| Vulkan | Unified | 4 | 8,192 | 4 | 431.54 | 55.31 | Complete | +| Vulkan | Unified | 4 | 32,768 | 1 | 128.71 | 25.42 | Complete | +| Vulkan | Unified | 4 | 32,768 | 4 | - | - | Skipped | +| Vulkan | Unified | 4 | 65,536 | 1 | - | - | Skipped | +| Vulkan | Unified | 4 | 65,536 | 4 | - | - | Skipped | + +Original OpenVINO split four-slot log: +`tmp/mtp-regression-20261022/pool-v2-np4.log`. Vulkan one-slot log: +`tmp/ud-backend-matrix-20261023/batch-vulkan-split-npl1.log`. Its split +four-slot rows through 32K are in `batch-vulkan-split-npl1-4.log` in the same +folder. New runs save one prompt length per process as `batch-*-pp*.log` and +checkpoint it separately. This avoids repeating completed lengths on restart. +It also introduces a fresh 16-token warmup for each remaining prompt length; +these are labeled by per-case provenance rather than silently pooled as repeats. +Vulkan one-slot 64K prefill took 1,013.906 seconds versus 25.865 for decode. + + ## Server benchmark @@ -169,7 +362,8 @@ The runner records effective environment and commit provenance for each server case. `summary.md`, `server-summary.json`, and `batch-summary.json` are generated from completed responses and raw logs. -Completed server matrix: +Original default-fit server matrix (historical Vulkan rows; use the full-GPU +reruns for the primary comparison): | Backend | KV | MTP | Requests in flight | Native decode t/s/request | End-to-end aggregate t/s | Draft acceptance | |---|---|---|---:|---:|---:|---:| @@ -192,6 +386,10 @@ Completed server matrix: ## Interpretation and limits +The following comparisons describe the original default-fit server matrix. +Use the full-GPU Vulkan reruns below for the primary backend comparison, since +the original Vulkan weight placement was not controlled. + For these short MMLU prompts in a large unified allocation, OpenVINO MTP increases sequential aggregate throughput by 37.2% (35.07 to 48.11 t/s) and four-request aggregate throughput by 12.9% (80.55 to 90.98 t/s). With Vulkan, unified MTP raises @@ -232,6 +430,46 @@ The Vulkan backend's `supports_buft` accepts its device buffer type rather than `Vulkan_Host`, so expert host placement can change scheduler placement as well as memory access costs. +The memory fitting decision uses the Vulkan backend's sum of +`heapBudget[i] - heapUsage[i]`, rather than the physical 64 GiB system-memory +capacity. Khronos describes this budget as a changing guideline for process +allocations; it may respond to other system activity and is not a fixed hardware +limit. See the [Vulkan memory-budget specification](https://github.com/KhronosGroup/Vulkan-Docs/blob/main/chapters/memory.adoc#memory-device). + +The installed Mesa package is `26.2.4~kisak1~n`. In the corresponding upstream +Mesa 26.2.4 source, Intel ANV normally caps its system-memory heap at 75% +of the kernel-reported system memory on this class of machine (older Xe kernels +with an already restricted heap have a separate path). The diagnostic reports +47,898 MiB total Vulkan heap, consistent with this restriction. It then updates +available system-heap memory, distributes it over those heaps, reserves 10%, +and reports +`heapBudget = min(heapSize, heapUsage + 0.9 * availableShare)`, rounded down to +MiB. Both the heap-size cap and the available-memory reserve apply. The Intel +device-info path bounds the kernel's available-memory estimate +by Linux `/proc/meminfo`'s `MemAvailable`. This explains why total installed RAM +is not the budget used by the fitter. It does not establish the cause of the +particular 43-to-27 GiB change between diagnostic starts. See +[Mesa's Intel budget calculation](https://gitlab.freedesktop.org/mesa/mesa/-/blob/mesa-26.2.4/src/intel/vulkan/anv_physical_device.c), +[available-memory adjustment](https://gitlab.freedesktop.org/mesa/mesa/-/blob/mesa-26.2.4/src/intel/dev/intel_device_info.c), +and [Linux available-memory query](https://gitlab.freedesktop.org/mesa/mesa/-/blob/mesa-26.2.4/src/util/os_misc.c). + +In the split non-MTP diagnostic, the estimate was 31,278 MiB against 26,739 MiB +free. Including the default 1024 MiB margin, the fitter needed to reduce GPU +allocations by 5563 MiB. Context was explicitly set to 524288, so it left context +unchanged and moved expert tensors to `Vulkan_Host`: the final model allocation +was 14,696.44 MiB device plus 6402.22 MiB host. The all-GPU non-MTP model is +about 21 GiB, attention KV is 10 GiB at this allocation, and recurrent/compute +buffers add more; comparing model size alone with total RAM misses these costs. +MTP adds its attention cache and recurrent snapshots as well. + +This is a conservative software placement decision, not evidence that the UMA +hardware cannot accommodate an all-GPU run. The exact reason the driver budget +fell from roughly 43 GiB to 27 GiB across starts has not been isolated. Host and +GPU allocations both use system DRAM on this integrated GPU, but they remain +different backend allocation types; expert host placement can change where +matmuls execute. The separately labeled `-fit off -ngl 99` controls avoid that +placement decision; their measured results are shown below. + These diagnostics occurred after the timed server matrix, so their individual placement values cannot be retroactively assigned to timed cases. They do show that default fitting can change the workload with the driver-reported budget, @@ -239,12 +477,64 @@ which varied substantially across successive process starts. The lower Vulkan server rates must be interpreted as configured-default end-to-end results, not a controlled all-GPU kernel comparison. `llama-batched-bench` loads the model and context directly and does not call `common_fit_params`; its results do not -have this server-specific automatic-fit confound. A separate server control -with `UD_FORCE_GPU=1` (explicit `-ngl 99 -fit off`) is queued after the requested -matrix; it will be reported separately from the default-fit results. +have this server-specific automatic-fit confound. Separate server reruns +with `UD_FORCE_GPU=1` (explicit `-ngl 99 -fit off`) are reported below, separately +from the original default-fit results. This is an eight-request throughput sample, with one pass per case. MMLU question texts average 53.25 templated tokens in this sample. It tests MTP on natural short prompts and separately tests long-context non-MTP with random token IDs; it does not measure long-context MTP, MMLU accuracy, or statistical variation across repeated benchmark passes. + +## Vulkan server reruns with full GPU weight placement + +These reruns keep the same model, four slots, 524288 context, MMLU inputs, +concurrency and 512 generated tokens. They add `-ngl 99 -fit off` and llama +info logging (`-lv 4`) to record actual model storage. All eight original Vulkan +server configurations are rerun because their timed logs did not retain enough +placement detail to identify individually which had host-offloaded experts. +The small host embedding allocation is expected; each included rerun retains +more than 20,000 MiB of device weights and less than 1024 MiB of host weights. +The original default-fit table is retained as historical configuration data. + +Reproduce a full-GPU server case with the reusable wrapper, for example: + +```bash +UD_FORCE_GPU=1 UD_LOG_VERBOSITY=4 UD_RUN_LABEL=gpu-vulkan-unified-mtp-c4 \ +UD_VULKAN_BIN_DIR=/home/zijun/llama-benchmark-clean/build/vulkan/bin \ +UD_LLAMA_COMMIT=dd06588b1 UD_OPENVINO_COMMIT=38aaf24a07 \ +python ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py \ + vulkan unified mtp 4 +``` + +| KV | MTP | Requests in flight | Native decode t/s/request | End-to-end aggregate t/s | Draft acceptance | Device / host model MiB | Status | +|---|---|---:|---:|---:|---:|---:|---| +| Split | Off | 1 | 31.74 | 30.26 | - | 20583.34 / 515.31 | Complete | +| Split | Off | 4 | 16.63 | 61.41 | - | 20583.34 / 515.31 | Complete | +| Split | On | 1 | 48.54 | 44.79 | 2626/2911 (90.2%) | 21087.70 / 515.31 | Complete | +| Split | On | 4 | 13.87 | 52.05 | 2621/2927 (89.5%) | 21087.70 / 515.31 | Complete | +| Unified | Off | 1 | 31.79 | 30.33 | - | 20583.34 / 515.31 | Complete | +| Unified | Off | 4 | 16.60 | 55.71 | - | 20583.34 / 515.31 | Complete | +| Unified | On | 1 | 47.71 | 44.00 | 2626/2911 (90.2%) | 21087.70 / 515.31 | Complete | +| Unified | On | 4 | 13.29 | 48.59 | 2629/2908 (90.4%) | 21087.70 / 515.31 | Complete | + +With expert weights kept on the GPU, Vulkan sequential rates are close across +KV layouts. The original default-fit rates therefore mixed backend performance +with weight-placement effects. The full-GPU table is the primary Vulkan server +comparison; the historical default-fit table documents the earlier workload. + +Split KV: MTP changes sequential aggregate throughput from 30.26 to +44.79 t/s (+48.0%) and four-request aggregate throughput from +61.41 to 52.05 t/s (-15.2%). + +Unified KV: MTP changes sequential aggregate throughput from 30.33 to +44.00 t/s (+45.1%) and four-request aggregate throughput from +55.71 to 48.59 t/s (-12.8%). + +The user stopped remaining long-prompt batched tests to finish this campaign +within half an hour. The Vulkan unified 32K one-active row finished before +cancellation and is retained; its four-active row did not finish. OpenVINO +unified four-active 32K took 1279.251 seconds prefill and 265.141 seconds decode +(102.46 and 7.72 aggregate t/s). That measured slowdown also made its remaining +64K case unsuitable for the revised time budget; no 64K values are extrapolated. From 508e30be3caa0a67f6264c17f83ee2c3450ac375 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Tue, 27 Oct 2026 01:12:22 +0530 Subject: [PATCH 41/65] ggml-openvino: honour the -1 skip id in MUL_MAT_ID Upstream made an id of -1 in MUL_MAT_ID skip the slot and zero its row of the result. The translator passed -1 straight to GatherMatmul or Gather, so 169 of the 743 MUL_MAT_ID op tests on CPU (all skip=1) failed. A skipped slot now looks up a valid expert, and the result is multiplied by a 0/1 mask of the kept slots. For the packed MXFP4 path (Gather and MatMul), clamping the id to expert 0 is enough. GatherMatmul computes a wrong row when a token names the same expert twice, so the general path gives each skipped slot an expert that no other slot of the token uses. TopK indices are never -1, and model graphs take the ids from the router's TopK. Those graphs skip the handling and stay unchanged, so the GPU MoE fusion still matches them. --- .../ggml-openvino/openvino/op/mul_mat_id.cpp | 109 +++++++++++++++++- 1 file changed, 108 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp b/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp index 52c3f5edad83..5a06035efdc1 100644 --- a/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp +++ b/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp @@ -8,20 +8,36 @@ #include #include #include +#include +#include #include #include #include #include #include #include +#include +#include #include +#include +#include +#include +#include #include +#include #include +#include +#include #include +#include #include #include +#include +#include #include #include +#include +#include #include namespace ov { @@ -71,6 +87,79 @@ ov::Output static_shape_dims_or_shapeof(const ov::Output & i return get_dimensions(shape, dims); } +// TopK indices are never -1. Model graphs take the ids from the router's TopK through views and +// reshapes, so they skip the -1 handling below and keep the GatherMatmul pattern that the GPU MoE +// fusion matches. +bool ids_from_topk(ov::Output ids) { + for (;;) { + const auto node = ids.get_node_shared_ptr(); + if (ov::is_type(node)) { + return ids.get_index() == 1; + } + if (!ov::is_type(node) && !ov::is_type(node) && + !ov::is_type(node) && !ov::is_type(node) && + !ov::is_type(node) && !ov::is_type(node) && + !ov::is_type(node)) { + return false; + } + ids = node->input_value(0); + } +} + +// An id of -1 skips the slot and zeroes the matching row of the result. The skipped slot looks up a +// valid expert, and the result is multiplied by this mask: 1 for a kept slot, 0 for a skipped one, +// shaped [ids..., 1] to broadcast over the row. +ov::Output kept_slots_mask(const ov::Output & ids, const ov::element::Type & type) { + auto zero = ov::op::v0::Constant::create(ids.get_element_type(), ov::Shape{}, {0}); + ov::Output keep = std::make_shared(ids, zero); + keep = std::make_shared(keep, type); + return std::make_shared(keep, const_i64({-1})); +} + +ov::Output clamp_skipped_ids(const ov::Output & ids) { + auto zero = ov::op::v0::Constant::create(ids.get_element_type(), ov::Shape{}, {0}); + return std::make_shared(ids, zero); +} + +// GatherMatmul computes a wrong row when two slots of a token name the same expert (ggml leaves +// that undefined too, see TAG_MUL_MAT_ID_DUPLICATE_ID), so a skipped slot cannot simply look up +// expert 0 while another slot of the row keeps it. A row with S skipped slots keeps at most +// n_used - S experts, so [0, n_used) holds at least S unused ones: the r-th skipped slot of a row +// looks up the r-th of them. ids is [n_tokens, n_used]. +ov::Output distinct_ids_for_skipped_slots(const ov::Output & ids) { + using namespace ov::op; + const auto & ps = ids.get_partial_shape(); + if (ps.rank().is_dynamic() || ps[ps.rank().get_length() - 1].is_dynamic()) { + return clamp_skipped_ids(ids); + } + const auto type = ids.get_element_type(); + const int64_t n_used = ps[ps.rank().get_length() - 1].get_length(); + std::vector range(n_used); + std::iota(range.begin(), range.end(), 0); + auto experts = v0::Constant::create(type, ov::Shape{static_cast(n_used)}, range); + auto zero = v0::Constant::create(type, ov::Shape{}, {0}); + auto one = v0::Constant::create(type, ov::Shape{}, {1}); + auto last_axis = v0::Constant::create(ov::element::i64, ov::Shape{}, {-1}); + + // free[t, e]: no slot of row t uses expert e, for e in [0, n_used) + auto uses = std::make_shared(std::make_shared(ids, const_i64({-1})), experts); + auto free = std::make_shared(std::make_shared(uses, const_i64({-2}), false)); + // 1-based rank of each free expert in its row, and of each skipped slot in its row + auto free_rank = std::make_shared(std::make_shared(free, type), last_axis); + auto skip = std::make_shared(ids, zero); + auto skip_rank = std::make_shared( + std::make_shared(std::make_shared(skip, type), last_axis, true), one); + + // pick[t, j, e]: expert e is the skip_rank[t, j]-th free expert of row t + auto pick = std::make_shared( + std::make_shared(std::make_shared(skip_rank, const_i64({-1})), + std::make_shared(free_rank, const_i64({-2}))), + std::make_shared(free, const_i64({-2}))); + auto picked = std::make_shared( + std::make_shared(std::make_shared(pick, type), experts), const_i64({-1}), false); + return std::make_shared(skip, picked, ids); +} + ov::Output translate_mul_mat_id_mxfp4_packed(const NodeContext & context, ov::Output expert_weights, ov::Output activations, @@ -98,6 +187,13 @@ ov::Output translate_mul_mat_id_mxfp4_packed(const NodeContext & conte if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) { ids = std::make_shared(ids, ov::element::i32); } + const auto output_type = context.get_output_type(); + // Gather and MatMul handle repeated ids, so clamping a skipped slot to expert 0 is enough here. + std::optional> keep; + if (!ids_from_topk(ids)) { + keep = kept_slots_mask(ids, output_type); + ids = clamp_skipped_ids(ids); + } auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}); @@ -156,10 +252,12 @@ ov::Output translate_mul_mat_id_mxfp4_packed(const NodeContext & conte ov::OutputVector{batch_dim, get_dimensions(ids_shape, {0, 1}), row_dim}, 0); result = std::make_shared(result, result_target_dims, false); - const auto output_type = context.get_output_type(); if (result.get_element_type() != output_type) { result = std::make_shared(result, output_type); } + if (keep) { + result = std::make_shared(result, *keep); + } return result; } @@ -219,6 +317,12 @@ OutputVector translate_mul_mat_id(const NodeContext & context) { } const auto output_type = context.get_output_type(); + std::optional> keep; + if (!ids_from_topk(ids)) { + keep = kept_slots_mask(ids, output_type); + ids = distinct_ids_for_skipped_slots(ids); + } + const auto activations_type = ggml_openvino_is_gpu() ? ov::element::f16 : ov::element::f32; if (activations.get_element_type() != activations_type) { activations = std::make_shared(activations, activations_type); @@ -244,6 +348,9 @@ OutputVector translate_mul_mat_id(const NodeContext & context) { if (result.get_element_type() != output_type) { result = std::make_shared(result, output_type); } + if (keep) { + result = std::make_shared(result, *keep); + } return rename_outputs_with_suffix({result}, context.get_name()); } From 3ea0e631719c3c4771d2ec687fdaab1673231136 Mon Sep 17 00:00:00 2001 From: yzhou51 Date: Fri, 23 Oct 2026 09:43:27 +0800 Subject: [PATCH 42/65] ggml-openvino: Gather rows before dequantizing a quantized embedding table 1. Optimize gather to fetch row before dequant 2. add NPU token_embd quantization option --- docs/backend/OPENVINO.md | 2 + ggml/src/ggml-openvino/README.md | 2 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 15 +- ggml/src/ggml-openvino/model-cache.cpp | 1 + .../ggml-openvino/npu/npu_quant_policy.cpp | 17 ++ .../ggml-openvino/openvino/op/get_rows.cpp | 154 +++++++++++++++++- 6 files changed, 182 insertions(+), 9 deletions(-) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 1303a1e3b6c0..1fcd12edae31 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -744,6 +744,8 @@ Boolean flags follow a uniform convention: set to a **positive integer** (e.g. ` | `GGML_OPENVINO_RELEASE_WEIGHTS` | Boolean | inherits from `GGML_OPENVINO_MEMORY_OPTIMIZE` on GPU | GPU-only. Release host weight buffers after the compiled model cache can reuse the device/plugin copy. Requires stable graph shapes; dynamic workloads that need recompilation should leave this disabled. | | `GGML_OPENVINO_SPILL_DIR` | String | `not set` | Directory for a disk-backed weight buffer. When set, the repacked weight buffer is mapped from an unlinked file on this path instead of anonymous memory, so its pages are reclaimable under memory pressure instead of staying pinned, cutting the load-time host memory peak. Must point at real storage; a tmpfs mount (e.g. `/tmp` on many systems) backs it with RAM and makes the peak worse. | | `GGML_OPENVINO_REQUANT_KQUANT` | String | `not set` | Requantize Q6_K/Q5_K weights (and matching MoE expert weights) to a 4-bit target instead of the default Q8_0_C, trading accuracy for less memory traffic. One of `q4_asym64` (Q6_K/Q5_K only, keeps a real zero point at group 64), `q4_asym64_all` (also requantizes Q4_K), `q4_sym128` (Q6_K/Q5_K only), `q4_sym128_all` (Q4_K too, drops its per-group zero point), or `native` (no requantization). | +| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | String | `not set` | NPU-only. How a Q6_K `token_embd.weight` (also used as the output projection when the embeddings are tied) is stored for the NPU. When **unset** it is converted to `F16`. `q4_0_128` stores it as symmetric int4 with group size 128, and `q4_0_c` as symmetric int4 with one scale per row. Both read about 1 GB less weight data per token for a 248320 x 2560 table, at some cost in accuracy (on Qwen3.5-4B Q4_0: mean KLD 0.112 with `F16`, 0.128 with `q4_0_128`, 0.151 with `q4_0_c`). Use together with `GGML_OPENVINO_GATHER_BEFORE_DEQUANT`, which is on by default on NPU. | +| `GGML_OPENVINO_GATHER_BEFORE_DEQUANT` | Boolean | device-based | Tri-state. When a quantized embedding table is looked up (`GET_ROWS`), gather the rows of the quantized weights and scales first and dequantize only those rows, instead of dequantizing the whole table for every token. Without it, a quantized table that is tied to the output projection is dequantized in full on every token, which makes NPU decode slower than with an `F16` table. When **unset** it is enabled on `NPU` and disabled on other devices. Set to a positive integer to force-enable, or `0` to force-disable. It does not change the results, and has no effect on tables that are not quantized. | | `GGML_OPENVINO_PROFILING` | Integer | `0` | `1` logs execution timing; `2` or higher also enables OpenVINO and OpenCL profiling. | | `GGML_OPENVINO_DEBUG_NODE` | String | `not set` | Add the named graph nodes as compiled outputs for debugging. Separate multiple names with commas. | | `GGML_OPENVINO_MOE_OP` | Boolean | `1` | On GPU, set to `0` to keep the unfused GatherMatmul path. | diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index a12233d2aa17..a0ce3c8949be 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -29,7 +29,7 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally. -Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. +Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_GATHER_BEFORE_DEQUANT`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode. diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 190c9b88ea24..b429106c9739 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -9,10 +9,10 @@ #include #include #include +#include #include #include #include -#include #include ov::Core & ov_singleton_core() { @@ -56,7 +56,8 @@ std::string ggml_openvino_get_device_description(const std::string & device_name if (has_prefix(device_name, "NPU")) { try { - const std::string arch = ov_singleton_core().get_property(device_name, "DEVICE_ARCHITECTURE").as(); + const std::string arch = + ov_singleton_core().get_property(device_name, "DEVICE_ARCHITECTURE").as(); if (!arch.empty()) { description += " (NPU " + arch + ")"; } @@ -83,9 +84,10 @@ static std::string resolve_openvino_device_name(const std::vector & for (const std::string & name : available_devices) { list += "\n " + name + ": " + ggml_openvino_get_device_description(name); } - GGML_ABORT("GGML OpenVINO Backend: GGML_OPENVINO_DEVICE=%s is not available. " - "Set it to one of the available OpenVINO devices:%s", - requested, list.c_str()); + GGML_ABORT( + "GGML OpenVINO Backend: GGML_OPENVINO_DEVICE=%s is not available. " + "Set it to one of the available OpenVINO devices:%s", + requested, list.c_str()); } return requested; } @@ -155,6 +157,8 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_LOG_UNSUPPORTED_OPS", "GGML_OPENVINO_LOG_SWA_LAYERS", "GGML_OPENVINO_NATIVE_SOFTPLUS", + "GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", + "GGML_OPENVINO_GATHER_BEFORE_DEQUANT", "GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", "GGML_OPENVINO_REQUANT_KQUANT", "GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT", @@ -441,6 +445,7 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * } return ExtraQuantType::Q8_0_C; } + if (strncmp(tensor->name, "output.weight", 13) == 0) { return ExtraQuantType::Q8_0_C; } diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 81cf2b6ff77b..fdbc1c68023a 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -173,6 +173,7 @@ bool ggml_openvino_model_cache_only() { static const char * cache_settings[] = { "GGML_OPENVINO_REQUANT_KQUANT", "GGML_OPENVINO_NATIVE_SOFTPLUS", + "GGML_OPENVINO_GATHER_BEFORE_DEQUANT", "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_KV_SLICE", "GGML_OPENVINO_MANUAL_GQA_ATTN", diff --git a/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp b/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp index 12aac130ec61..e1399fc111fa 100644 --- a/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp +++ b/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp @@ -3,6 +3,8 @@ #include "ggml-impl.h" #include "ggml.h" +#include +#include #include ExtraQuantType ggml_openvino_get_npu_requant_type() { @@ -22,6 +24,21 @@ std::optional ggml_openvino_npu_token_embd_requant_type(const gg // GGML_OPENVINO_TOKEN_EMBD_I4 into group-128 int4 (only worth it for a tied embedding, // where the table is also the lm_head weight - see gather_compressed_rows). if (tensor->type == GGML_TYPE_Q6_K) { + // q4_0_c: per-channel u4, q4_0_128: group 128, default: F16 + if (const char * q = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT")) { + ExtraQuantType type = ExtraQuantType::F16; + if (strcmp(q, "q4_0_c") == 0) { + type = ExtraQuantType::Q4_0_C; + } else if (strcmp(q, "q4_0_128") == 0) { + type = ExtraQuantType::Q4_0_128; + } + static std::once_flag logged; + std::call_once(logged, [&] { + GGML_LOG_INFO("ggml-openvino: NPU token_embd.weight requant type: %s", + (type == ExtraQuantType::F16 ? "F16" : q)); + }); + return type; + } if (ggml_openvino_getenv_int("GGML_OPENVINO_TOKEN_EMBD_I4")) { return ExtraQuantType::Q4_0_128; } diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index 252a450f8237..9e7b6cbde7e0 100644 --- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp @@ -1,7 +1,9 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" +#include "ggml-openvino/ggml-openvino-extra.h" +#include #include #include #include @@ -11,9 +13,12 @@ #include #include #include +#include +#include #include #include #include +#include #include namespace ov { @@ -21,6 +26,143 @@ namespace frontend { namespace ggml { namespace op { +namespace { + +// Gathering the rows of a quantized embedding table before dequantizing them is on by default on NPU and can be +// forced either way with GGML_OPENVINO_GATHER_BEFORE_DEQUANT (a positive value enables it, 0 disables it). +bool gather_before_dequant_enabled() { + if (ggml_openvino_getenv_str("GGML_OPENVINO_GATHER_BEFORE_DEQUANT") != nullptr) { + return ggml_openvino_getenv_int("GGML_OPENVINO_GATHER_BEFORE_DEQUANT") > 0; + } + return ggml_openvino_is_npu(); +} + +// Gathers the constant `c` along its first axis when it holds one entry per table row. A constant whose dimensions +// are all 1 broadcasts against every row and is returned unchanged. Returns an empty Output for any other shape. +Output gather_table_rows(const Output & c, const Output & indices, int64_t rows) { + const auto & ps = c.get_partial_shape(); + if (ps.is_dynamic()) { + return {}; + } + if (ps.rank().get_length() > 0 && ps[0].get_length() == rows) { + auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}); + return std::make_shared(c, indices, axis); + } + const auto & shape = ps.to_shape(); + if (std::all_of(shape.begin(), shape.end(), [](size_t dim) { return dim == 1; })) { + return c; + } + return {}; +} + +// A quantized embedding table reaches GET_ROWS as the dequantization chain +// +// [Convert(f32)] <- [Reshape] <- Multiply(scale, [Subtract(zero point)] <- Convert(quantized Constant)) +// +// built by make_int4_weights()/make_int8_weights(). Gathering after this chain dequantizes the whole table (about +// 1.3 GB in f16 for a 248320 x 2560 token_embd) for every token. When the table is tied to the output projection, +// the NPUW partitioner also hands the dequantized table from one submodel to the next. Gathering the rows of the +// quantized constants and of their scales first dequantizes only the selected rows, and leaves the table to be +// consumed once, in its quantized form, by the output projection. +// +// `data` is the 2D table [rows, cols]; the quantized constant is [rows, groups, group_size] (followed by a Reshape) +// or [rows, cols] (channel-wise, no Reshape). Returns an empty Output when `data` is not such a chain, so that the +// caller falls back to a plain Gather. +Output gather_before_dequant(const Output & data, const Output & indices) { + using namespace ov::op; + + const auto indices_rank = indices.get_partial_shape().rank(); + if (indices_rank.is_dynamic()) { + return {}; + } + + Output chain = data; + const auto top_convert = ov::as_type_ptr(chain.get_node_shared_ptr()); + if (top_convert) { + chain = top_convert->input_value(0); + } + const bool has_reshape = ov::is_type(chain.get_node()); + if (has_reshape) { + chain = chain.get_node()->input_value(0); + } + + // Multiply(x, scale): exactly one operand is the scale constant. + const auto multiply = ov::as_type_ptr(chain.get_node_shared_ptr()); + if (!multiply) { + return {}; + } + Output scale; + Output dequant_input; + for (size_t i = 0; i < 2; ++i) { + if (ov::is_type(multiply->input_value(i).get_node())) { + scale = multiply->input_value(i); + dequant_input = multiply->input_value(1 - i); + } + } + if (!scale.get_node()) { + return {}; + } + + // Optional zero point: Subtract(Convert(q), Constant or Convert(Constant)). + Output zero_point; + if (const auto subtract = ov::as_type_ptr(dequant_input.get_node_shared_ptr())) { + zero_point = subtract->input_value(1); + dequant_input = subtract->input_value(0); + } + + const auto convert_q = ov::as_type_ptr(dequant_input.get_node_shared_ptr()); + if (!convert_q || !ov::is_type(convert_q->input_value(0).get_node())) { + return {}; + } + const Output quantized = convert_q->input_value(0); + + const auto & quantized_ps = quantized.get_partial_shape(); + if (quantized_ps.is_dynamic() || quantized_ps.rank().get_length() != (has_reshape ? 3 : 2)) { + return {}; + } + const int64_t rows = quantized_ps[0].get_length(); + + Output rows_q = gather_table_rows(quantized, indices, rows); + Output rows_scale = gather_table_rows(scale, indices, rows); + if (!rows_q.get_node() || !rows_scale.get_node()) { + return {}; + } + Output result = std::make_shared(rows_q, convert_q->get_destination_type()); + + if (zero_point.get_node()) { + std::shared_ptr zero_point_convert = + ov::as_type_ptr(zero_point.get_node_shared_ptr()); + const Output zero_point_const = zero_point_convert ? zero_point_convert->input_value(0) : zero_point; + if (!ov::is_type(zero_point_const.get_node())) { + return {}; + } + Output rows_zero_point = gather_table_rows(zero_point_const, indices, rows); + if (!rows_zero_point.get_node()) { + return {}; + } + if (zero_point_convert) { + rows_zero_point = + std::make_shared(rows_zero_point, zero_point_convert->get_destination_type()); + } + result = std::make_shared(result, rows_zero_point); + } + result = std::make_shared(result, rows_scale); + + if (has_reshape) { + // [indices..., groups, group_size] -> [indices..., cols]: keep the index dimensions (0) and infer the rest. + std::vector pattern(indices_rank.get_length(), 0); + pattern.push_back(-1); + result = std::make_shared( + result, v0::Constant::create(ov::element::i64, ov::Shape{pattern.size()}, pattern), true); + } + if (top_convert) { + result = std::make_shared(result, top_convert->get_destination_type()); + } + return result; +} + +} // namespace + OutputVector translate_get_rows(const NodeContext & context) { num_inputs_check(context, 2, 2); @@ -159,12 +301,18 @@ OutputVector translate_get_rows(const NodeContext & context) { auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1}); res = std::make_shared(data, indices, axis, 1); } else { + if (gather_before_dequant_enabled() && data.get_partial_shape().rank() == 2) { + res = gather_before_dequant(data, indices); + } // For a tied embedding the same weight also feeds the lm_head matmul. Gathering the // dequantized table would give that dequantization chain a second consumer, forcing the // full table to be materialized; gather the packed rows instead and dequantize those. - if (auto compressed = gather_compressed_rows(data, indices)) { - res = compressed; - } else { + if (!res.get_node()) { + if (auto compressed = gather_compressed_rows(data, indices)) { + res = compressed; + } + } + if (!res.get_node()) { auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}); res = std::make_shared(data, indices, axis); } From 0974aef916ddb3c17557b3361ef5a18afe465197 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Mon, 26 Oct 2026 11:30:35 -0700 Subject: [PATCH 43/65] ggml-openvino: select the NPU token_embd type with GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT GET_ROWS had two rewrites that gather the rows of a quantized table before dequantizing them: gather_compressed_rows, which runs on every device, and gather_before_dequant, enabled on NPU by GGML_OPENVINO_GATHER_BEFORE_DEQUANT. Both match the int4 and int8 chains built by make_int4_weights() and make_int8_weights(). Keep gather_compressed_rows and drop the second rewrite and its switch. The NPU type of a Q6_K token_embd.weight was set by two booleans, GGML_OPENVINO_TOKEN_EMBD_I8 and GGML_OPENVINO_TOKEN_EMBD_I4, and by GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT. Keep only the string variable, with the values f16 (default), q8_0_c, q4_0_128 and q4_0_c, so the int8 and group-128 int4 settings stay available. An unknown value aborts, as for GGML_OPENVINO_NPU_REQUANT_POLICY, instead of silently using f16. The variable replaces the two booleans in the NPU compiled-model cache key. --- docs/backend/OPENVINO.md | 5 +- ggml/src/ggml-openvino/README.md | 2 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 3 - ggml/src/ggml-openvino/model-cache.cpp | 1 - .../ggml-openvino/npu/npu_quant_policy.cpp | 51 +++--- .../ggml-openvino/openvino/op/get_rows.cpp | 154 +----------------- ggml/src/ggml-openvino/utils.cpp | 4 +- 7 files changed, 30 insertions(+), 190 deletions(-) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 1fcd12edae31..d720ca04adff 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -735,8 +735,6 @@ Boolean flags follow a uniform convention: set to a **positive integer** (e.g. ` | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for non-stateful single-row KV writes. Intended for NPU decode paths where `ScatterUpdate` copies the full destination tensor to update one row. | | `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | Boolean | `0` | Disable the stateful KV-state sequence-axis relayout (relayout is on by default). It moves the KV state sequence axis from dim 1 to dim 2, so the GPU plugin can append new tokens in place instead of copying the whole state every token, and the reader side no longer transposes the whole accumulated state. Set to `1` to disable. | | `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` | Boolean | `0` | Dynamic CPU/GPU graphs read the active sequence count and the attended KV length from the shape of the KQ mask inside the model, so the GPU plugin can infer the attention shapes without waiting for input values and selects its fused SDPA kernel. Set to `1` to pass them as separate inputs instead. | -| `GGML_OPENVINO_TOKEN_EMBD_I8` | Boolean | `0` | NPU-only. Keep `token_embd.weight` from widening Q6_K to FP16 by using the normal int8 compressed-weight layout instead. Reduces embedding-table memory at possible accuracy/performance cost. | -| `GGML_OPENVINO_TOKEN_EMBD_I4` | Boolean | `0` | NPU-only. Requantize `token_embd.weight` to group-128 int4. Intended mainly for tied embeddings, where compressed-row gather can read only the selected packed rows before dequantization. | | `GGML_OPENVINO_NPU_KEEP_Q4_0` | Boolean | `0` | NPU-only experimental toggle. Keep native `Q4_0` weights instead of regrouping them through the NPU requant policy. Can avoid requantization work and extra scale storage changes, but the resulting group-32 graph may be unstable on current NPU drivers. | | `GGML_OPENVINO_MANUAL_GQA_ATTN` | Boolean | device-based | Tri-state. When **unset**, manual GQA attention is enabled by default on `GPU` and disabled on other devices. Set to a positive integer to force-enable, or `0` to force-disable. | | `GGML_OPENVINO_MEMORY_OPTIMIZE` | Boolean | `0` | Umbrella switch for compile-time memory reductions. Enables `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS` unless those fine-grained variables are explicitly set. | @@ -744,8 +742,7 @@ Boolean flags follow a uniform convention: set to a **positive integer** (e.g. ` | `GGML_OPENVINO_RELEASE_WEIGHTS` | Boolean | inherits from `GGML_OPENVINO_MEMORY_OPTIMIZE` on GPU | GPU-only. Release host weight buffers after the compiled model cache can reuse the device/plugin copy. Requires stable graph shapes; dynamic workloads that need recompilation should leave this disabled. | | `GGML_OPENVINO_SPILL_DIR` | String | `not set` | Directory for a disk-backed weight buffer. When set, the repacked weight buffer is mapped from an unlinked file on this path instead of anonymous memory, so its pages are reclaimable under memory pressure instead of staying pinned, cutting the load-time host memory peak. Must point at real storage; a tmpfs mount (e.g. `/tmp` on many systems) backs it with RAM and makes the peak worse. | | `GGML_OPENVINO_REQUANT_KQUANT` | String | `not set` | Requantize Q6_K/Q5_K weights (and matching MoE expert weights) to a 4-bit target instead of the default Q8_0_C, trading accuracy for less memory traffic. One of `q4_asym64` (Q6_K/Q5_K only, keeps a real zero point at group 64), `q4_asym64_all` (also requantizes Q4_K), `q4_sym128` (Q6_K/Q5_K only), `q4_sym128_all` (Q4_K too, drops its per-group zero point), or `native` (no requantization). | -| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | String | `not set` | NPU-only. How a Q6_K `token_embd.weight` (also used as the output projection when the embeddings are tied) is stored for the NPU. When **unset** it is converted to `F16`. `q4_0_128` stores it as symmetric int4 with group size 128, and `q4_0_c` as symmetric int4 with one scale per row. Both read about 1 GB less weight data per token for a 248320 x 2560 table, at some cost in accuracy (on Qwen3.5-4B Q4_0: mean KLD 0.112 with `F16`, 0.128 with `q4_0_128`, 0.151 with `q4_0_c`). Use together with `GGML_OPENVINO_GATHER_BEFORE_DEQUANT`, which is on by default on NPU. | -| `GGML_OPENVINO_GATHER_BEFORE_DEQUANT` | Boolean | device-based | Tri-state. When a quantized embedding table is looked up (`GET_ROWS`), gather the rows of the quantized weights and scales first and dequantize only those rows, instead of dequantizing the whole table for every token. Without it, a quantized table that is tied to the output projection is dequantized in full on every token, which makes NPU decode slower than with an `F16` table. When **unset** it is enabled on `NPU` and disabled on other devices. Set to a positive integer to force-enable, or `0` to force-disable. It does not change the results, and has no effect on tables that are not quantized. | +| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | String | `f16` | NPU-only. How a Q6_K `token_embd.weight` (also used as the output projection when the embeddings are tied) is stored for the NPU. `f16` converts it to FP16, `q8_0_c` stores it as int8 with one scale per row, `q4_0_128` as symmetric int4 with group size 128, and `q4_0_c` as symmetric int4 with one scale per row. A quantized table is looked up by gathering the selected rows before dequantizing them. The int4 layouts read about 1 GB less weight data per token for a 248320 x 2560 table, at some cost in accuracy (on Qwen3.5-4B Q4_0: mean KLD 0.112 with `f16`, 0.128 with `q4_0_128`, 0.151 with `q4_0_c`). Any other value fails during model loading. | | `GGML_OPENVINO_PROFILING` | Integer | `0` | `1` logs execution timing; `2` or higher also enables OpenVINO and OpenCL profiling. | | `GGML_OPENVINO_DEBUG_NODE` | String | `not set` | Add the named graph nodes as compiled outputs for debugging. Separate multiple names with commas. | | `GGML_OPENVINO_MOE_OP` | Boolean | `1` | On GPU, set to `0` to keep the unfused GatherMatmul path. | diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index a0ce3c8949be..a12233d2aa17 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -29,7 +29,7 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally. -Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_GATHER_BEFORE_DEQUANT`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. +Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode. diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index b429106c9739..ccc6fcc8ddb4 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -158,12 +158,9 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_LOG_SWA_LAYERS", "GGML_OPENVINO_NATIVE_SOFTPLUS", "GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", - "GGML_OPENVINO_GATHER_BEFORE_DEQUANT", "GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", "GGML_OPENVINO_REQUANT_KQUANT", "GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT", - "GGML_OPENVINO_TOKEN_EMBD_I8", - "GGML_OPENVINO_TOKEN_EMBD_I4", "GGML_OPENVINO_NPU_KEEP_Q4_0", "GGML_OPENVINO_NPU_FAST_MASK", "GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK", diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index fdbc1c68023a..81cf2b6ff77b 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -173,7 +173,6 @@ bool ggml_openvino_model_cache_only() { static const char * cache_settings[] = { "GGML_OPENVINO_REQUANT_KQUANT", "GGML_OPENVINO_NATIVE_SOFTPLUS", - "GGML_OPENVINO_GATHER_BEFORE_DEQUANT", "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_KV_SLICE", "GGML_OPENVINO_MANUAL_GQA_ATTN", diff --git a/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp b/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp index e1399fc111fa..f20c57cc2784 100644 --- a/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp +++ b/ggml/src/ggml-openvino/npu/npu_quant_policy.cpp @@ -3,7 +3,6 @@ #include "ggml-impl.h" #include "ggml.h" -#include #include #include @@ -19,34 +18,30 @@ ExtraQuantType ggml_openvino_get_npu_requant_type() { } std::optional ggml_openvino_npu_token_embd_requant_type(const ggml_tensor * tensor) { - // NPU widens a Q6_K embedding table to f16, which doubles its footprint versus the - // int8 form used everywhere else. GGML_OPENVINO_TOKEN_EMBD_I8 opts back into int8, and - // GGML_OPENVINO_TOKEN_EMBD_I4 into group-128 int4 (only worth it for a tied embedding, - // where the table is also the lm_head weight - see gather_compressed_rows). - if (tensor->type == GGML_TYPE_Q6_K) { - // q4_0_c: per-channel u4, q4_0_128: group 128, default: F16 - if (const char * q = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT")) { - ExtraQuantType type = ExtraQuantType::F16; - if (strcmp(q, "q4_0_c") == 0) { - type = ExtraQuantType::Q4_0_C; - } else if (strcmp(q, "q4_0_128") == 0) { - type = ExtraQuantType::Q4_0_128; - } - static std::once_flag logged; - std::call_once(logged, [&] { - GGML_LOG_INFO("ggml-openvino: NPU token_embd.weight requant type: %s", - (type == ExtraQuantType::F16 ? "F16" : q)); - }); - return type; - } - if (ggml_openvino_getenv_int("GGML_OPENVINO_TOKEN_EMBD_I4")) { - return ExtraQuantType::Q4_0_128; - } - if (ggml_openvino_getenv_int("GGML_OPENVINO_TOKEN_EMBD_I8") == 0) { - return ExtraQuantType::F16; - } + // NPU widens a Q6_K embedding table to f16 by default. The int4 layouts only pay off for a tied + // embedding, where the table is also the lm_head weight and GET_ROWS gathers the packed rows + // before dequantizing them (see gather_compressed_rows). + if (tensor->type != GGML_TYPE_Q6_K) { + return std::nullopt; + } + const std::string quant = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", "f16"); + ExtraQuantType type; + if (quant == "f16") { + type = ExtraQuantType::F16; + } else if (quant == "q8_0_c") { + type = ExtraQuantType::Q8_0_C; + } else if (quant == "q4_0_128") { + type = ExtraQuantType::Q4_0_128; + } else if (quant == "q4_0_c") { + type = ExtraQuantType::Q4_0_C; + } else { + GGML_ABORT("Unknown GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT: %s", quant.c_str()); } - return std::nullopt; + static std::once_flag logged; + std::call_once(logged, [&] { + GGML_LOG_INFO("ggml-openvino: NPU token_embd.weight requant type: %s\n", quant.c_str()); + }); + return type; } std::optional ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor) { diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index 9e7b6cbde7e0..252a450f8237 100644 --- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp @@ -1,9 +1,7 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" -#include "ggml-openvino/ggml-openvino-extra.h" -#include #include #include #include @@ -13,12 +11,9 @@ #include #include #include -#include -#include #include #include #include -#include #include namespace ov { @@ -26,143 +21,6 @@ namespace frontend { namespace ggml { namespace op { -namespace { - -// Gathering the rows of a quantized embedding table before dequantizing them is on by default on NPU and can be -// forced either way with GGML_OPENVINO_GATHER_BEFORE_DEQUANT (a positive value enables it, 0 disables it). -bool gather_before_dequant_enabled() { - if (ggml_openvino_getenv_str("GGML_OPENVINO_GATHER_BEFORE_DEQUANT") != nullptr) { - return ggml_openvino_getenv_int("GGML_OPENVINO_GATHER_BEFORE_DEQUANT") > 0; - } - return ggml_openvino_is_npu(); -} - -// Gathers the constant `c` along its first axis when it holds one entry per table row. A constant whose dimensions -// are all 1 broadcasts against every row and is returned unchanged. Returns an empty Output for any other shape. -Output gather_table_rows(const Output & c, const Output & indices, int64_t rows) { - const auto & ps = c.get_partial_shape(); - if (ps.is_dynamic()) { - return {}; - } - if (ps.rank().get_length() > 0 && ps[0].get_length() == rows) { - auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}); - return std::make_shared(c, indices, axis); - } - const auto & shape = ps.to_shape(); - if (std::all_of(shape.begin(), shape.end(), [](size_t dim) { return dim == 1; })) { - return c; - } - return {}; -} - -// A quantized embedding table reaches GET_ROWS as the dequantization chain -// -// [Convert(f32)] <- [Reshape] <- Multiply(scale, [Subtract(zero point)] <- Convert(quantized Constant)) -// -// built by make_int4_weights()/make_int8_weights(). Gathering after this chain dequantizes the whole table (about -// 1.3 GB in f16 for a 248320 x 2560 token_embd) for every token. When the table is tied to the output projection, -// the NPUW partitioner also hands the dequantized table from one submodel to the next. Gathering the rows of the -// quantized constants and of their scales first dequantizes only the selected rows, and leaves the table to be -// consumed once, in its quantized form, by the output projection. -// -// `data` is the 2D table [rows, cols]; the quantized constant is [rows, groups, group_size] (followed by a Reshape) -// or [rows, cols] (channel-wise, no Reshape). Returns an empty Output when `data` is not such a chain, so that the -// caller falls back to a plain Gather. -Output gather_before_dequant(const Output & data, const Output & indices) { - using namespace ov::op; - - const auto indices_rank = indices.get_partial_shape().rank(); - if (indices_rank.is_dynamic()) { - return {}; - } - - Output chain = data; - const auto top_convert = ov::as_type_ptr(chain.get_node_shared_ptr()); - if (top_convert) { - chain = top_convert->input_value(0); - } - const bool has_reshape = ov::is_type(chain.get_node()); - if (has_reshape) { - chain = chain.get_node()->input_value(0); - } - - // Multiply(x, scale): exactly one operand is the scale constant. - const auto multiply = ov::as_type_ptr(chain.get_node_shared_ptr()); - if (!multiply) { - return {}; - } - Output scale; - Output dequant_input; - for (size_t i = 0; i < 2; ++i) { - if (ov::is_type(multiply->input_value(i).get_node())) { - scale = multiply->input_value(i); - dequant_input = multiply->input_value(1 - i); - } - } - if (!scale.get_node()) { - return {}; - } - - // Optional zero point: Subtract(Convert(q), Constant or Convert(Constant)). - Output zero_point; - if (const auto subtract = ov::as_type_ptr(dequant_input.get_node_shared_ptr())) { - zero_point = subtract->input_value(1); - dequant_input = subtract->input_value(0); - } - - const auto convert_q = ov::as_type_ptr(dequant_input.get_node_shared_ptr()); - if (!convert_q || !ov::is_type(convert_q->input_value(0).get_node())) { - return {}; - } - const Output quantized = convert_q->input_value(0); - - const auto & quantized_ps = quantized.get_partial_shape(); - if (quantized_ps.is_dynamic() || quantized_ps.rank().get_length() != (has_reshape ? 3 : 2)) { - return {}; - } - const int64_t rows = quantized_ps[0].get_length(); - - Output rows_q = gather_table_rows(quantized, indices, rows); - Output rows_scale = gather_table_rows(scale, indices, rows); - if (!rows_q.get_node() || !rows_scale.get_node()) { - return {}; - } - Output result = std::make_shared(rows_q, convert_q->get_destination_type()); - - if (zero_point.get_node()) { - std::shared_ptr zero_point_convert = - ov::as_type_ptr(zero_point.get_node_shared_ptr()); - const Output zero_point_const = zero_point_convert ? zero_point_convert->input_value(0) : zero_point; - if (!ov::is_type(zero_point_const.get_node())) { - return {}; - } - Output rows_zero_point = gather_table_rows(zero_point_const, indices, rows); - if (!rows_zero_point.get_node()) { - return {}; - } - if (zero_point_convert) { - rows_zero_point = - std::make_shared(rows_zero_point, zero_point_convert->get_destination_type()); - } - result = std::make_shared(result, rows_zero_point); - } - result = std::make_shared(result, rows_scale); - - if (has_reshape) { - // [indices..., groups, group_size] -> [indices..., cols]: keep the index dimensions (0) and infer the rest. - std::vector pattern(indices_rank.get_length(), 0); - pattern.push_back(-1); - result = std::make_shared( - result, v0::Constant::create(ov::element::i64, ov::Shape{pattern.size()}, pattern), true); - } - if (top_convert) { - result = std::make_shared(result, top_convert->get_destination_type()); - } - return result; -} - -} // namespace - OutputVector translate_get_rows(const NodeContext & context) { num_inputs_check(context, 2, 2); @@ -301,18 +159,12 @@ OutputVector translate_get_rows(const NodeContext & context) { auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1}); res = std::make_shared(data, indices, axis, 1); } else { - if (gather_before_dequant_enabled() && data.get_partial_shape().rank() == 2) { - res = gather_before_dequant(data, indices); - } // For a tied embedding the same weight also feeds the lm_head matmul. Gathering the // dequantized table would give that dequantization chain a second consumer, forcing the // full table to be materialized; gather the packed rows instead and dequantize those. - if (!res.get_node()) { - if (auto compressed = gather_compressed_rows(data, indices)) { - res = compressed; - } - } - if (!res.get_node()) { + if (auto compressed = gather_compressed_rows(data, indices)) { + res = compressed; + } else { auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}); res = std::make_shared(data, indices, axis); } diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 222f41b417e5..5ce24070e0ea 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -1838,8 +1838,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared if (!model_cache_dir.empty()) { uint64_t base_extra = ggml_openvino_model_cache_extra_cfg(stateful, /*recurrent=*/false); base_extra = base_extra * 131 + (self_contained ? 1u : 0u); - base_extra = base_extra * 131 + static_cast(ggml_openvino_getenv_int("GGML_OPENVINO_TOKEN_EMBD_I8")); - base_extra = base_extra * 131 + static_cast(ggml_openvino_getenv_int("GGML_OPENVINO_TOKEN_EMBD_I4")); + base_extra = ggml_openvino_model_cache_mix_string( + base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT")); base_extra = base_extra * 131 + static_cast(ggml_openvino_getenv_int("GGML_OPENVINO_NPU_KEEP_Q4_0")); base_extra = base_extra * 131 + (ggml_openvino_static_kv_slice_enabled() ? 1u : 0u); base_extra = ggml_openvino_model_cache_mix_string( From bdaf4818f72ce38b5bc000a25d754df932895f1d Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 27 Oct 2026 04:19:32 +0100 Subject: [PATCH 44/65] openvino: use stable in-place recurrent caches and optional separate convolution Remove rotated cache banks, select the independent Update ops, and flatten the post-GDN projection back into the token stream. Bump the compiled-model cache revision. Assisted-by: Codex --- ggml/src/ggml-openvino/CMakeLists.txt | 16 --- ggml/src/ggml-openvino/README.md | 28 +++-- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 14 +++ ggml/src/ggml-openvino/ggml-decoder.cpp | 5 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 4 +- ggml/src/ggml-openvino/ggml-openvino-extra.h | 7 -- ggml/src/ggml-openvino/ggml-openvino.cpp | 102 ++---------------- .../openvino/op/gated_delta_net.cpp | 22 +--- .../openvino/op/recurrent_cache.hpp | 44 -------- .../openvino/op/recurrent_cache_update.hpp | 12 ++- ggml/src/ggml-openvino/openvino/op_table.h | 2 +- .../openvino/recurrent_cache_fusion.cpp | 25 ++--- .../openvino/translate_session.cpp | 6 +- ggml/src/ggml-openvino/utils.cpp | 29 +---- tests/test-backend-sampler.cpp | 4 +- 15 files changed, 76 insertions(+), 244 deletions(-) delete mode 100644 ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index 21997fc5b251..3ed43b9fab27 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -34,22 +34,6 @@ endif() # Released runtimes retain the ordinary cache translators. include(CheckCXXSourceCompiles) -unset(GGML_OPENVINO_HAS_FUSED_RECURRENCE CACHE) -set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) -set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op") -check_cxx_source_compiles("#include -int main() { - auto conv = std::make_shared(ov::OutputVector{}, 3); - auto gdn = std::make_shared(ov::OutputVector{}); -}" - GGML_OPENVINO_HAS_FUSED_RECURRENCE) -unset(CMAKE_REQUIRED_LIBRARIES) -unset(CMAKE_REQUIRED_INCLUDES) -if(GGML_OPENVINO_HAS_FUSED_RECURRENCE) - target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_FUSED_RECURRENCE=1) -endif() - -# Separate Update ops permit staged in-place cache mutation on compatible runtimes. unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE) set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op") diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 5c80a9e61e91..7edd0be96751 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -6,15 +6,23 @@ Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP w Stateless recurrent execution uses the same reset, reorder, and partial cache-writeback paths at every slot capacity, including one slot without MTP. `test-backend-sampler --test recurrent_slots` compares four-slot reset, copy, inactive-slot preservation, and rollback against independently replayed sequences. -The matched stateless GPU path emits two fused operations per recurrent layer: -`RecurrentConvCache` and `RecurrentGatedDeltaNet`. Each computes its result and -returns the full updated cache. Device-USM cache banks rotate by default; -`GGML_OPENVINO_RECURRENT_CACHE_INPLACE=1` selects the separate staged Update ops -on a compatible runtime. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` selects the -ordinary GGML decomposition. The older three-op native path is removed. -The [integration report](dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md#direct-frontend-integration-and-branch-split-2026-10-22) -records the required OpenVINO branches and tests. Rebuild both repos and regenerate -compiled-model blobs after this translation change (revision 10). +The matched stateless GPU path uses `RecurrentConvCacheUpdate` and +`RecurrentGatedDeltaNetUpdate`. In-place cache mutation is the primary path: +Parameter and Result share a stable caller-owned USM allocation. Required source +rows are staged on device before writes, so resets, cyclic reorders and rollback +remain generic. Incompatible bindings use private output plus Result copy-back. +Rotation banks and the older three-op native path are removed. +`GGML_OPENVINO_SEPARATE_RECURRENT_CONV=1` makes the convolution Update op produce +history plus QKV for the ordinary GroupConvolution instead of fusing convolution. +`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary GGML decomposition. +Rebuild both repos and regenerate compiled-model blobs for translation revision 11. + +Set `GGML_OPENVINO_ENABLE_KV_4D=1` to enable the upstream stateless in-place +attention KV update pattern where eligible. It binds full-capacity cache tensors +and lets the GPU fusion expose the live prefix to attention. The current upstream +eligibility check supports one physical stream (including unified KV); explicit +split multi-slot KV retains the ordinary full-cache path. This option does not +change recurrent cache handling. The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_DISABLE_KV_SLICE` unset to use live-prefix attention cache bindings where supported. The [large-context comparison](dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md#large-context-attention-kv-slicing-2026-10-22) measures the benefit and documents the single-stream restriction. Earlier [performance measurements](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) used disabled slicing; yamini-model results remain historical references. @@ -51,7 +59,7 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally. -Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. +Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`, `GGML_OPENVINO_ENABLE_KV_4D`, `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`, and `GGML_OPENVINO_SEPARATE_RECURRENT_CONV`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. `GGML_OPENVINO_DISABLE_KV_SLICE` is a runtime binding option and can differ between cache population and cache-only runs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Slicing is enabled by default for contiguous ordinary K/V roots with one allocated stream, one active sequence at offset zero, and no sliding-window attention. Recurrent convolution/GDN caches and their rollback snapshots always retain their full stored row bank. Other layouts use full bindings. Repopulate caches made before this option was removed from the fingerprint once without cache-only mode. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 222082f4cd4f..17b92203891e 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -1,3 +1,17 @@ +# Current recurrent-cache implementation (2026-10-27) + +Dynamic stateless GPU graphs use the independent `RecurrentConvCacheUpdate` and +`RecurrentGatedDeltaNetUpdate` ops for Qwen3.5/Qwen3.6 in llama.cpp. In-place USM +bindings are primary; private output and copy-back handle incompatible bindings. +There are no rotation banks. `GGML_OPENVINO_SEPARATE_RECURRENT_CONV=1` selects +history/QKV output plus ordinary GroupConvolution. See the backend README for +current settings and the multislot report for the new benchmark campaign. + +The remaining sections are historical measurements and design notes. Their +rotation ops, opt-in in-place flag and branch layout describe earlier versions. + +--- + # Generic recurrent-cache baseline for Qwen MTP Date: 2026-10-15. Branch: `qwen-openvino-generic-cache`. Model: Qwen3.6-35B-A3B-Q4_K_M_yamini.gguf. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 29bcc624ae0e..e84ffba0570e 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -356,7 +356,8 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW && norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { - return 6; + // The post-GDN projection rejoins the flat token stream. + return node->ne[2] == 1 ? 5 : 6; } } } @@ -1521,7 +1522,7 @@ void GgmlOvDecoder::add_extra_inputs() { create_1d_input("rs_snapshot_stride_" + node_name, writeback.snapshot_stride); } } -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE m_compute_params.recurrent_controls.clear(); if (!m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 38ef4cdf7c0e..63124d0be18b 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -147,7 +147,7 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_DISABLE_FUSED_RECURRENCE", "GGML_OPENVINO_DISABLE_CACHE_ROTATION", - "GGML_OPENVINO_RECURRENT_CACHE_INPLACE", + "GGML_OPENVINO_SEPARATE_RECURRENT_CONV", "GGML_OPENVINO_ENABLE_KV_4D", "GGML_OPENVINO_ENABLE_FALLBACK", "GGML_OPENVINO_KV_SCATTER_ELEMENTS", @@ -763,7 +763,7 @@ ggml_openvino_tensor_extra * ggml_openvino_create_tensor_extra(const ggml_tensor GGML_ASSERT(ggml_openvino_is_gpu()); auto gpu_context = remote_context->as(); auto usm_tensor = gpu_context.create_tensor(element_type, shape, - ggml_openvino_buffer_resolve_data(tensor, 0, ggml_nbytes(tensor))); + tensor->data); ov_tensor = std::make_shared(std::move(usm_tensor)); } else { ov_tensor = std::make_shared(element_type, shape, tensor->data); diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 5fe8af518254..342980efbb3a 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -248,13 +248,6 @@ ggml_openvino_tensor_extra * ggml_openvino_create_tensor_extra(const ggml_tensor // Check if a tensor's buffer uses remote (device) memory (e.g. GPU USM) bool ggml_openvino_buffer_is_remote(const ggml_tensor * tensor); -// Logical GGML addresses remain stable when recurrent GPU cache allocations rotate. -// Resolve root/view ranges through the owning buffer, including checkpoint I/O. -void * ggml_openvino_buffer_resolve_data(const ggml_tensor * tensor, size_t offset = 0, size_t size = 0); -void * ggml_openvino_buffer_resolve_address(const ggml_tensor * tensor, const void * logical, size_t size); -std::optional ggml_openvino_buffer_prepare_cache_output(ggml_tensor * tensor); -void ggml_openvino_buffer_commit_cache_output(ggml_tensor * tensor); - // Register an extra with the tensor's OpenVINO buffer context for proper lifetime management. // This sets tensor->extra and tracks the extra in the buffer context for cleanup. void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_extra_base * extra); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 7c4a0dd42b92..524c393d1b80 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -87,31 +87,6 @@ struct ggml_backend_openvino_buffer_context { // Wrapping of the buffer std::shared_ptr ov_buffer; - // Stable logical GGML address -> current/spare immutable device cache storage. - // Kept by the buffer, not an InferRequest, so checkpoints, views and a newly - // compiled graph all see the latest state. Publish only after successful infer. - struct cache_storage { - size_t size; - ov::intel_gpu::ocl::USMTensor current; - ov::intel_gpu::ocl::USMTensor spare; - bool pending = false; - }; - - std::map cache_allocations; - - void * resolve(const void * logical, size_t bytes) { - const auto address = reinterpret_cast(logical); - auto it = cache_allocations.upper_bound(address); - if (it != cache_allocations.begin()) { - --it; - const auto delta = address - it->first; - if (delta <= it->second.size && bytes <= it->second.size - delta) { - return static_cast(it->second.current.get()) + delta; - } - } - return const_cast(logical); - } - // Track all extras for cleanup std::map tensor_extras; std::map weight_fingerprints; @@ -482,7 +457,7 @@ static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buf auto mem_fill_fn = ggml_openvino_get_clEnqueueMemFillINTEL(); if (mem_fill_fn != nullptr) { uint8_t pattern = value; - cl_int err = mem_fill_fn(queue, ctx->resolve((char *) tensor->data + offset, size), &pattern, + cl_int err = mem_fill_fn(queue, (char *) tensor->data + offset, &pattern, sizeof(pattern), size, 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemFillINTEL failed with error %d\n", __func__, err); @@ -619,7 +594,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer cl_command_queue queue = ggml_openvino_get_cl_queue(); auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL(); if (mem_cpy_fn != nullptr) { - cl_int err = mem_cpy_fn(queue, CL_TRUE, ctx->resolve((char *) tensor->data + offset, size), data, size, + cl_int err = mem_cpy_fn(queue, CL_TRUE, (char *) tensor->data + offset, data, size, 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL failed with error %d\n", __func__, err); @@ -667,7 +642,7 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer cl_command_queue queue = ggml_openvino_get_cl_queue(); auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL(); if (mem_cpy_fn != nullptr) { - cl_int err = mem_cpy_fn(queue, CL_TRUE, data, ctx->resolve((const char *) tensor->data + offset, size), + cl_int err = mem_cpy_fn(queue, CL_TRUE, data, (const char *) tensor->data + offset, size, 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL failed with error %d\n", __func__, err); @@ -697,7 +672,7 @@ static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer } // Can copy from host to device if (ggml_backend_buffer_is_host(src->buffer)) { - cl_int err = mem_cpy_fn(queue, CL_TRUE, ggml_openvino_buffer_resolve_data(dst, 0, ggml_nbytes(src)), + cl_int err = mem_cpy_fn(queue, CL_TRUE, dst->data, src->data, ggml_nbytes(src), 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL (host-to-device) failed with error %d\n", __func__, err); @@ -710,8 +685,8 @@ static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer ggml_backend_openvino_buffer_context * src_ctx = (ggml_backend_openvino_buffer_context *) src->buffer->context; if (src_ctx->is_remote) { - cl_int err = mem_cpy_fn(queue, CL_TRUE, ggml_openvino_buffer_resolve_data(dst, 0, ggml_nbytes(src)), - ggml_openvino_buffer_resolve_data(src, 0, ggml_nbytes(src)), ggml_nbytes(src), + cl_int err = mem_cpy_fn(queue, CL_TRUE, dst->data, + src->data, ggml_nbytes(src), 0, nullptr, nullptr); if (err != CL_SUCCESS) { GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL (device-to-device) failed with error %d\n", __func__, err); @@ -744,17 +719,6 @@ static void ggml_backend_openvino_buffer_clear(ggml_backend_buffer_t buffer, uin GGML_LOG_WARN("%s: clEnqueueMemFillINTEL failed with error %d\n", __func__, err); } clFinish(queue); - // The original allocation remains the logical address space, while - // current rotated roots may live elsewhere. Clear both banks too. - for (auto & [address, storage] : ctx->cache_allocations) { - for (auto bank : {storage.current, storage.spare}) { - mem_fill_fn(queue, bank.get(), &pattern, sizeof(pattern), storage.size, 0, nullptr, nullptr); - } - storage.pending = false; - } - if (!ctx->cache_allocations.empty()) { - clFinish(queue); - } } else { GGML_LOG_WARN("%s: clEnqueueMemFillINTEL not available for GPU buffer clear\n", __func__); } @@ -950,60 +914,6 @@ bool ggml_openvino_buffer_is_remote(const ggml_tensor * tensor) { return ctx->is_remote; } -void * ggml_openvino_buffer_resolve_data(const ggml_tensor * tensor, size_t offset, size_t size) { - const auto * logical = static_cast(tensor->data) + offset; - return ggml_openvino_buffer_resolve_address(tensor, logical, size); -} - -void * ggml_openvino_buffer_resolve_address(const ggml_tensor * tensor, const void * logical, size_t size) { - if (!ggml_openvino_buffer_is_remote(tensor)) { - return const_cast(logical); - } - auto * ctx = static_cast(tensor->buffer->context); - return ctx->resolve(logical, size); -} - -std::optional ggml_openvino_buffer_prepare_cache_output(ggml_tensor * tensor) { - if (!ggml_openvino_buffer_is_remote(tensor) || tensor->view_src || !ggml_is_contiguous(tensor) || - !GgmlOvDecoder::is_recurrent_cache(tensor) || ggml_nbytes(tensor) == 0) { - return std::nullopt; - } - auto * ctx = static_cast(tensor->buffer->context); - const auto address = reinterpret_cast(tensor->data); - const auto bytes = ggml_nbytes(tensor); - auto found = ctx->cache_allocations.find(address); - if (found == ctx->cache_allocations.end()) { - // Reject overlapping logical roots; views are resolved within one root. - for (const auto & [begin, storage] : ctx->cache_allocations) { - if (address <= begin ? begin - address < bytes : address - begin < storage.size) { - return std::nullopt; - } - } - auto context = ggml_openvino_get_remote_context()->as(); - const auto type = GgmlOvDecoder::get_ov_type(tensor); - const auto shape = GgmlOvDecoder::get_shape(tensor); - auto current = context.create_tensor(type, shape, tensor->data); - auto spare = context.create_usm_device_tensor(type, shape); - found = ctx->cache_allocations - .emplace(address, ggml_backend_openvino_buffer_context::cache_storage{bytes, current, spare}) - .first; - } - auto & storage = found->second; - if (storage.size != bytes) { - return std::nullopt; - } - storage.pending = true; - return storage.spare; -} - -void ggml_openvino_buffer_commit_cache_output(ggml_tensor * tensor) { - auto * ctx = static_cast(tensor->buffer->context); - auto & storage = ctx->cache_allocations.at(reinterpret_cast(tensor->data)); - GGML_ASSERT(storage.pending); - std::swap(storage.current, storage.spare); - storage.pending = false; -} - void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_extra_base * extra) { GGML_ASSERT(tensor != nullptr); GGML_ASSERT(tensor->buffer != nullptr); diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index c8434614a13f..0e4ff99288f7 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -3,9 +3,6 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE -#include "recurrent_cache.hpp" -#endif #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE #include "recurrent_cache_update.hpp" #endif @@ -196,22 +193,13 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto // << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape() // << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl; -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE if (cache_inputs) { OutputVector args{q, k, v, (*cache_inputs)[0], g, beta}; args.insert(args.end(), cache_inputs->begin() + 1, cache_inputs->end()); - std::shared_ptr fused; -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - if (ggml_openvino_getenv_int("GGML_OPENVINO_RECURRENT_CACHE_INPLACE")) { - fused = std::make_shared( - args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); - } else -#endif - { - fused = std::make_shared( - args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); - } - fused->set_friendly_name(context.get_name() + "/RecurrentGatedDeltaNet"); + auto fused = std::make_shared( + args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); + fused->set_friendly_name(context.get_name() + "/RecurrentGatedDeltaNetUpdate"); // The matched state VIEW is consumed only by the overridden full-cache // writeback. Route that cache directly instead of materializing snapshots. if (context.get_output_names().size() == 3) { @@ -276,7 +264,7 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { return translate_gdn(context, nullptr); } -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs) { return translate_gdn(context, &cache_inputs); } diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp deleted file mode 100644 index ef2f217d2a93..000000000000 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_cache.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) 2026 Intel Corporation -// SPDX-License-Identifier: Apache-2.0 - -#pragma once -#include "gated_delta_net.hpp" -#include "openvino/op/op.hpp" - -// Internal OpenVINO developer API mirror for Qwen3.5/Qwen3.6 in llama.cpp. -// Keep declarations and class layouts in sync with the patched OpenVINO runtime. -// Port/precedence contracts: dev_doc/OPENVINO-RECURRENT-CACHE.md and OV developer header. -namespace ov::op::internal { -// Inputs: original cache, active/extra rows, reset begin/length, extra offsets, -// QKV [1,B,C,T], ordered (window start,destination row) pairs and depthwise -// weights [1,1,C,H+1]. Outputs: convolution [1,B,T,C] and full updated cache_r. -// Original cache reads remain immutable for cyclic row maps. -class OPENVINO_API RecurrentConvCache : public ov::op::Op { -public: - OPENVINO_OP("RecurrentConvCache"); - RecurrentConvCache() = default; - RecurrentConvCache(const OutputVector & args, int64_t history); - void validate_and_infer_types() override; - bool visit_attributes(AttributeVisitor & visitor) override; - std::shared_ptr clone_with_new_inputs(const OutputVector & args) const override; - - int64_t get_history() const { return m_history; } - -private: - int64_t m_history = 0; -}; - -// Attention and full updated cache_s; generic reset/reorder and MTP snapshot writes. -class OPENVINO_API RecurrentGatedDeltaNet : public GatedDeltaNet { -public: - OPENVINO_OP("RecurrentGatedDeltaNet", "internal", GatedDeltaNet); - RecurrentGatedDeltaNet() = default; - RecurrentGatedDeltaNet(const OutputVector & args, - bool fuse_qk_l2norm = false, - float q_eps = 1e-6f, - float k_eps = 1e-6f, - int64_t snapshot_count = 1); - void validate_and_infer_types() override; - std::shared_ptr clone_with_new_inputs(const OutputVector & args) const override; -}; -} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp index 4eb79c16d467..6666a2bab989 100644 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp @@ -5,10 +5,12 @@ namespace ov::op::internal { /// Qwen3.5/Qwen3.6 llama.cpp convolution and generic cache_r maintenance. -/// Inputs match the nine-input RecurrentConvCache: original cache, active rows, -/// extra rows, reset begin/length, extra offsets, QKV, windows, depthwise weights. -/// Outputs are convolution [1,B,T,C] and the complete updated [1,1,S,C*history] cache. -/// GPU execution may reuse a caller's identical input/output device allocation only +/// Inputs: original cache, active rows, extra rows, reset begin/length, +/// extra offsets, QKV [1,B,C,T], windows and optional depthwise weights. +/// With nine inputs output 0 is convolution [1,B,T,C]; with eight it is +/// history plus QKV [1,B,C,history+T] for a separate GroupConvolution. +/// Output 1 is the complete updated [1,1,S,C*history] cache. +/// GPU execution may reuse a caller's identical input/output USM allocation only /// when it is the exclusive cache reader. Required original rows are gathered into /// device scratch before any reset, reorder or window write, preserving cycles, /// duplicate sources and later-window precedence. Other bindings retain immutable @@ -31,7 +33,7 @@ class OPENVINO_API RecurrentConvCacheUpdate : public Op { }; /// Qwen3.5/Qwen3.6 llama.cpp GDN and generic cache_s maintenance. -/// Inputs match the twelve-input RecurrentGatedDeltaNet: Q/K/V, cache, gate/beta, +/// Twelve inputs: Q/K/V, cache, gate/beta, /// active/extra rows, reset begin/length, extra offsets, ordered write control. /// Outputs are attention [B,T,H,V] and the complete [1,1,S,H*V*K] updated cache. /// snapshot_count saves only the newest min(T,count) states, newest first. diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index ead87a567a4e..f2759dc44b4e 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -49,7 +49,7 @@ GGML_OP_CONVERTER(translate_clamp); GGML_OP_CONVERTER(translate_pad); GGML_OP_CONVERTER(translate_ssm_conv); GGML_OP_CONVERTER(translate_gated_delta_net); -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); #endif GGML_OP_CONVERTER(translate_repeat); diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp index d75a590d787a..4d7bd29af185 100644 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp @@ -1,9 +1,8 @@ -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE # include "recurrent_cache_fusion.h" # include "../ggml-openvino-extra.h" # include "ggml-impl.h" -# include "op/recurrent_cache.hpp" # include "op_table.h" # ifdef GGML_OPENVINO_HAS_CACHE_UPDATE # include "op/recurrent_cache_update.hpp" @@ -285,25 +284,21 @@ OutputVector RecurrentCacheFusion::translate(int index, const NodeContext & cont const auto history = context.get_input_shape(0)[3].get_length(); NodeContext compute_context(m_decoder, m_tensors, group.compute); const auto channels = context.get_input_shape(0)[2].get_length(); - inputs.push_back(std::make_shared(compute_context.get_input(1), - constant({4}, {1, 1, channels, history + 1}), false)); - std::shared_ptr fused; -# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - if (ggml_openvino_getenv_int("GGML_OPENVINO_RECURRENT_CACHE_INPLACE")) { - fused = std::make_shared(inputs, history); - } else -# endif - { - fused = std::make_shared(inputs, history); + const bool separate = ggml_openvino_getenv_int("GGML_OPENVINO_SEPARATE_RECURRENT_CONV") > 0; + if (!separate) { + inputs.push_back(std::make_shared(compute_context.get_input(1), + constant({4}, {1, 1, channels, history + 1}), false)); } - fused->set_friendly_name(compute_context.get_name() + "/RecurrentConvCache"); + auto fused = std::make_shared(inputs, history); + fused->set_friendly_name(compute_context.get_name() + "/RecurrentConvCacheUpdate"); group.conv = fused->output(0); group.updated = fused->output(1); - return op::translate_concat(context); + return separate ? OutputVector{group.conv} : op::translate_concat(context); } if (index == group.compute) { if (group.concat >= 0) { - return {group.conv}; + return ggml_openvino_getenv_int("GGML_OPENVINO_SEPARATE_RECURRENT_CONV") > 0 ? + op::translate_ssm_conv(context) : OutputVector{group.conv}; } inputs.push_back(context.get_input("rs_update_" + m_decoder->get_op_name(group.writeback))); auto outputs = op::translate_recurrent_gated_delta_net(context, inputs); diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index 176b513bac5b..d87aeb21523c 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -5,7 +5,7 @@ #include "ggml-openvino/openvino/node_context.h" #include "ggml-openvino/openvino/utils.h" #include "input_model.h" -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE #include "recurrent_cache_fusion.h" #endif #include "pass/align_eltwise_ranks.h" @@ -315,7 +315,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo (*tensor_map)[it.first] = it.second; } -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map); #endif auto translate_node = [&](const std::shared_ptr & decoder, int node_idx) { @@ -339,7 +339,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo " is not implemented."); NodeContext node_context(decoder, tensor_map, node_idx, this); ov::OutputVector converted_outputs; -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE converted_outputs = recurrent_fusion.translate(node_idx, node_context); #endif if (converted_outputs.empty()) { diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 5b9f1ebf68ff..e04afa3d3e2c 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -170,14 +170,14 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : ggml_openvino_is_gpu(); - uint64_t extra_cfg = 10; // Direct fused recurrent computation and full-cache writeback. -#ifdef GGML_OPENVINO_HAS_FUSED_RECURRENCE + uint64_t extra_cfg = 11; // Stable in-place caches and optional separate convolution. +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ? 0u : 1u); #else extra_cfg = extra_cfg * 131; #endif #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_RECURRENT_CACHE_INPLACE") ? 1u : 0u); + extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_SEPARATE_RECURRENT_CONV") ? 1u : 0u); #else extra_cfg = extra_cfg * 131; #endif @@ -479,11 +479,10 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr & ggml_d } } - // Resolve rotated roots/views before consulting an extra built for another bank. + // Reuse the caller-owned full-cache binding when its shape and storage match. if (!ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS") && !ggml_decoder->is_static() && !ggml_decoder->is_splited_model() && ggml_openvino_buffer_is_remote(ggml_tensor)) { - auto resolved = ggml_openvino_buffer_resolve_address(ggml_tensor, output_data, - ov::shape_size(output_shape) * output_type.size()); + auto resolved = output_data; if (ggml_tensor->extra != nullptr) { auto * base = static_cast(ggml_tensor->extra); if (base->type == ggml_openvino_extra_base::Type::TENSOR) { @@ -601,24 +600,6 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_ if (extra_base->type == ggml_openvino_extra_base::Type::TENSOR) { // GGML_LOG_DEBUG("Using ggml_tensor->extra as ov::Tensor for input: %s\n", name.c_str()); auto * tensor_extra = static_cast(extra_base); - if (ggml_openvino_buffer_is_remote(ggml_tensor)) { - auto tensor = tensor_extra->tensor->as(); - // Extras may retain a prior bank after a checkpoint write. - const auto shape = tensor.get_shape(); - const auto type = tensor.get_element_type(); - // Noncontiguous views can share a base extra. Preserve that - // binding's original base/window while selecting its current bank. - const auto * bound_tensor = ggml_tensor; - while (bound_tensor->view_src && bound_tensor->extra == bound_tensor->view_src->extra) { - bound_tensor = bound_tensor->view_src; - } - auto resolved = ggml_openvino_buffer_resolve_data(bound_tensor, 0, tensor.get_byte_size()); - if (tensor.get() == resolved) { - return *tensor_extra->tensor; - } - auto context = ggml_openvino_get_remote_context()->as(); - return context.create_tensor(type, shape, resolved); - } return *tensor_extra->tensor; } } diff --git a/tests/test-backend-sampler.cpp b/tests/test-backend-sampler.cpp index 698796050063..637d7fe9a670 100644 --- a/tests/test-backend-sampler.cpp +++ b/tests/test-backend-sampler.cpp @@ -1316,8 +1316,8 @@ static void test_backend_recurrent_slots(const test_params & params) { auto memory = llama_get_memory(ctx.ctx.get()); run({3, 3, 3, 3}); run({0, 0, 1, 0}); - // Export/import after both cache banks have been used. Checkpoint reads - // and writes must resolve the current storage rather than logical data. + // Export/import after recurrent state changes. Restoring one sequence + // must preserve the other sequences and their stable cache allocations. const size_t checkpoint_size = llama_state_seq_get_size(ctx.ctx.get(), 2); GGML_ASSERT(checkpoint_size > 0); std::vector checkpoint(checkpoint_size); From 9ca7965d654c75edd807a14b335a46a8e2cdd73c Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 27 Oct 2026 04:28:54 +0100 Subject: [PATCH 45/65] openvino: accept matching empty axes in DIV repeat translation A no-logits MoE warmup can have a zero token axis on both operands. Keep its repeat factor at one instead of rejecting the graph. Assisted-by: Codex --- ggml/src/ggml-openvino/openvino/op/div.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ggml/src/ggml-openvino/openvino/op/div.cpp b/ggml/src/ggml-openvino/openvino/op/div.cpp index 2089ffd4c819..8bd060c62a2f 100644 --- a/ggml/src/ggml-openvino/openvino/op/div.cpp +++ b/ggml/src/ggml-openvino/openvino/op/div.cpp @@ -66,6 +66,10 @@ ov::Output repeat_input_to_match(const NodeContext & context, const int64_t input_dim = input_shape[axis].get_length(); const int64_t target_dim = target_shape[axis].get_length(); + // Empty token axes can occur in a MoE warmup with no logits. + if (input_dim == target_dim) { + continue; + } FRONT_END_OP_CONVERSION_CHECK(input_dim > 0 && target_dim > 0 && target_dim % input_dim == 0, "DIV input shape ", input_shape, " cannot repeat to match ", target_shape); From 2188bc23f5c3f0913e3ca58ebef1262b22451789 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 27 Oct 2026 05:51:08 +0100 Subject: [PATCH 46/65] openvino: remove the obsolete cache rotation environment setting Assisted-by: Codex --- ggml/src/ggml-openvino/ggml-openvino-extra.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 63124d0be18b..e98e2691fe4f 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -146,7 +146,6 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_DISABLE_CACHE", "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_DISABLE_FUSED_RECURRENCE", - "GGML_OPENVINO_DISABLE_CACHE_ROTATION", "GGML_OPENVINO_SEPARATE_RECURRENT_CONV", "GGML_OPENVINO_ENABLE_KV_4D", "GGML_OPENVINO_ENABLE_FALLBACK", From 03682953534798cf78d42717f5f10b62744f9d2c Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 27 Oct 2026 05:51:09 +0100 Subject: [PATCH 47/65] openvino: validate imported KV results in their four-dimensional layout Use the same head-split shape for cached KV Parameters and Results, so compatible stateless KV models load in cache-only mode. Assisted-by: Codex --- ggml/src/ggml-openvino/utils.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index e04afa3d3e2c..b42e98031d71 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -375,8 +375,16 @@ static bool compiled_model_matches_graph(const ov::CompiledModel & model, continue; } const auto & port = model.output(i); + const auto * tensor = graph_it->second; + auto expected_shape = GgmlOvDecoder::get_shape(tensor); + if (decoder.is_kvcache_4d_input(tensor)) { + // Cache Results use the same head-split layout as their Parameters. + const auto heads = static_cast(decoder.get_n_heads_kv_for_tensor(tensor)); + expected_shape = {1, static_cast(tensor->ne[1]), heads, + static_cast(tensor->ne[0]) / heads}; + } if (port.get_element_type() != GgmlOvDecoder::get_ov_type(graph_it->second) || - !port.get_partial_shape().compatible(ov::PartialShape(GgmlOvDecoder::get_shape(graph_it->second)))) { + !port.get_partial_shape().compatible(ov::PartialShape(expected_shape))) { return false; } } From 3d9b2fb78d1877cac358eef134bd16d21e5be2d5 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 27 Oct 2026 05:53:12 +0100 Subject: [PATCH 48/65] docs: record the bounded in-place KV and convolution benchmark rerun Include reusable cache-population and summary commands, 23 completed timing rows, seven deadline skips, native validation, memory limits, and follow-up opportunities. Separate decode throughput from prefill latency. Assisted-by: Codex --- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 5 + .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 239 +++++++++++++++++- .../benchmarks/qwen36_ud_inplace_batched.py | 115 +++++++++ .../benchmarks/qwen36_ud_inplace_summary.py | 69 +++++ 4 files changed, 427 insertions(+), 1 deletion(-) create mode 100644 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py create mode 100644 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md index a09c47256ce0..53ad6970c523 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -1,5 +1,10 @@ # Qwen3.5/Qwen3.6 generic recurrent fusion performance +The measurements below are historical. The current in-place implementation and +the fused/separate convolution rerun are documented in +[the 2026-10-27 benchmark campaign](QWEN36-UD-MULTISLOT-BENCHMARK.md#in-place-kv-and-recurrent-convolution-rerun-2026-10-27). +The current code removes the recurrent rotation ops and buffer banks. + 2026-10-21. This work supports Qwen3.5 and Qwen3.6 (`qwen35`/`qwen35moe`) in llama.cpp's OpenVINO backend, including multi-slot llama-server and draft-MTP verification/rollback. It implements the two computation/cache boundaries proposed diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index 5cc8b18a98f3..13e4147e0107 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -1,6 +1,243 @@ # Qwen3.6 UD multi-slot benchmark (2026-10-23) -Status: the campaign is finished. All 16 original server cases and all eight +## In-place KV and recurrent convolution rerun (2026-10-27) + +This is a separate campaign; earlier tables use the previous translation and +`-b 2048 -ub 512`. The current code merges `origin/dev_backend_openvino` +`0974aef91`, removes recurrent rotation, and compares fused convolution against +history/QKV output plus ordinary GroupConvolution. No new server or Vulkan +measurements are part of this rerun. + +- llama.cpp implementation: `9ca7965d6` (`qwen-openvino-inplace-perf`, isolated + worktree `/home/zijun/llama.cpp-inplace-perf`). Merge commit: `26870e70d`; + recurrent implementation: `bdaf4818f`. +- OpenVINO: `397f7a2c71` (`qwen-mtp-inplace-primary`). Release GPU build at + `/home/zijun/openvino-build-mtp`. +- Timed binaries include the cache-only fixes subsequently committed as llama.cpp + `036829535` and OpenVINO `40d69210bf`. The llama.cpp build identifier stayed + `9ca7965d6` during the measurements. Obsolete rotation-setting cleanup is + `2188bc23f`; it does not change the graph or cache fingerprint used here. +- Same target UD GGUF, GPU, native softplus, `q4_asym64_all`. + `GGML_OPENVINO_ENABLE_KV_4D=1`; KV slicing is not disabled. +- `-b 8192 -ub 8192`, 1024/8192/32768 prompt tokens per sequence, 512 decode + tokens per sequence. One-slot context is 131072; four-slot contexts are 524288 + total. Split allocates 131072 per slot; unified shares the total capacity. +- In-place recurrent caches are primary in both variants. Fused convolution is + the default; `GGML_OPENVINO_SEPARATE_RECURRENT_CONV=1` selects the separate + variant. Both use the same reset, reorder and ordered writeback semantics. +- Full-capacity 4D attention KV is bound where the upstream eligibility check + permits one physical stream (one-slot and unified). The GPU StatelessKV fusion + can expose the live prefix to attention. Explicit split four-slot KV is still + outside that upstream eligibility check and retains ordinary full bindings. +- All GPU workloads are serial. Cache population and functional checks precede + the 30-minute timed matrix. Timed runs use compiled-model cache-only mode. + Each batched timing row is one pass; batched-bench does not test MTP acceptance. + The upstream merge, cache implementation and batch sizes all changed from the + earlier campaign. These results do not isolate the effect of any one change. + +Reproducible runner: [qwen36_ud_inplace_batched.py](benchmarks/qwen36_ud_inplace_batched.py). +Raw commands, outputs, memory samples and status: +`tmp/inplace-kv-retest-20261027/target/` in the original llama.cpp workspace. +The six compiled blobs total approximately 108 GiB on disk. They are shared +across prompt lengths; convolution mode and KV layout use distinct signatures. + +```sh +BINARY=/home/zijun/llama.cpp-inplace-perf/build/MtpOVPerf/bin/llama-batched-bench +MODEL="$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" +OUT=/home/zijun/llama.cpp/tmp/inplace-kv-retest-20261027/target +RUNNER=ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py +python3 "$RUNNER" --binary "$BINARY" --model "$MODEL" --output "$OUT" --phase prime +python3 "$RUNNER" --binary "$BINARY" --model "$MODEL" --output "$OUT" --phase timed --minutes 30 +python3 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py \ + --output "$OUT" --report ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md --finished +``` + +The equivalent raw commands for either variant are below. Set the separate-conv +flag only for the separate variant; unset it for the fused default. Set cache-only +only after population using the same compilation settings. + +```sh +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_NATIVE_SOFTPLUS=1 +export GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all +export GGML_OPENVINO_ENABLE_KV_4D=1 +export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR="$OUT/model-cache" +export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 +"$BINARY" -m "$MODEL" -c 131072 -npp 1024,8192,32768 -ntg 512 -npl 1 -b 8192 -ub 8192 +"$BINARY" -m "$MODEL" -c 524288 -npp 1024,8192,32768 -ntg 512 -npl 1,4 -b 8192 -ub 8192 +"$BINARY" -m "$MODEL" -c 524288 -npp 1024,8192,32768 -ntg 512 -npl 1,4 --kv-unified -b 8192 -ub 8192 +``` + +### Validation + +All 13 native shape, attribute and GPU test cases pass, including history-only +convolution, cyclic/duplicate reorders, overlapping windows/snapshots, mixed +precision, dynamic shapes, host/device USM, alias/distinct output bindings, +exclusive Reshapes, shared readers, unrelated overlaps and export/import. +Convolution uses an independent host reference; GDN uses ordinary GDN with +independent host cache mapping. Both llama.cpp convolution variants pass the +0.8B four-slot reset/copy/checkpoint/rollback test (`rollback=0,2`). + +These checks also caught a post-GDN reshape that kept sequence and token axes +separate at the projection/residual boundary; it now flattens back into the +shared token stream. Full UD preparation exposed matching empty token axes in +DIV during no-logits MoE warmup; their repeat factor now remains one. The 0.8B +split four-slot 8K prompt smoke test with `b=ub=8192` completed (peak process RSS +12.77 GiB); its short 8-token decode is a functional check, not a target result. + +### Cache-only and runtime binding checks + +Cache preparation itself passed, but the first cache-only validation exposed two +compatibility bugs. The llama.cpp imported-output check compared 4D KV Results +against their old flat GGML shape; it now validates the same head-split layout +used for input/output binding. In the GPU plugin, SetOutput tried to bind a dynamic +Result's arguments while its producer still had the empty allocation from the +previous no-logits batch. Dynamic argument binding is deferred to inference, +after shape inference and allocation. These fixes preserve the compiled graph +format; the six prepared blobs are reused. + +Both new GPU output-binding regression tests pass with directly compiled and +exported/imported models. They cover empty-to-nonempty producer allocations and +a new output destination with unchanged input storage and shape. The 13 native +shape, attribute and GPU test cases also pass after the runtime fix. + +The one-slot and unified runtime dumps each contain 20 `stateless_kv` primitives, +60 `recurrent_cache_update` primitives and 10 attention primitives. All 80 cache +Parameter/Result pairs bind the same USM pointers. Short cache-only runs pass +no-logits warmup, prefill and decode, including four active unified sequences. +The pointer check establishes caller bindings; the OpenCL trace also checks +explicit copy calls, and does not measure traffic inside a kernel. + +### Convolution kernel control + +This isolated control uses 8192 channels, history 3, four cache rows, one active +sequence, FP16 data/weights and an FP32 cache. Cache input and output share device +USM. Eight warmups precede 20 measured calls per variant; profiling is enabled, +so these are operator controls, not predicted full-model token rates. + +| Input tokens | Fused request time (ms) | Separate request time (ms) | +|---:|---:|---:| +| 1 | 0.068 | 0.158 | +| 1024 | 2.179 | 3.243 | +| 8192 | 18.862 | 26.746 | + +At 8192 tokens, the ordinary convolution itself takes 2.133 ms in the last +profiled call, against 16.269 ms for the fused cache/convolution primitive. +However, the separate path also needs 3.104 ms to materialize history/QKV, +2.461 ms input layout conversion, 2.419 ms output reorder and 16.364 ms for the +final transpose. The full separate chain is slower in this control. Full-model +consumers may allow different layout optimizations, so the model matrix remains +the primary comparison. Improving the fused convolution's output access and +eliminating separate-convolution transposes are concrete kernel/layout targets. + +### Native GenAI prefill scheduling + +Native GenAI supports chunked prefill. In local source `25899f70`, +[SchedulerConfig](https://github.com/openvinotoolkit/openvino.genai/blob/25899f70/src/cpp/include/openvino/genai/scheduler_config.hpp) +defaults to `max_num_batched_tokens=256` and `dynamic_split_fuse=true`. Its +[latency-oriented client configuration](https://github.com/openvinotoolkit/openvino.genai/blob/25899f70/src/cpp/src/utils.cpp) +sets the token budget to `size_t::max`, so that client path does not impose this +small batch limit. With chunking disabled, the scheduler requires a full prompt +to fit the budget. These modes use different scheduling choices; native GenAI +performance alone does not prove the best llama.cpp microbatch size. This rerun +uses an 8192-token budget and equal batch/microbatch sizes, so 32K prompts still +span several graph executions. + + +Finished: 23/30 timing rows retained. A row is retained only after its prefill and all 512 decode steps finish. + +Decode throughput below excludes prefill. Values are aggregate tokens/s, using `speed_tg = pl * tg / t_tg`. In four-slot configurations, `A / B` means one active sequence / four active sequences; divide B by four for the simultaneous per-sequence rate. + +| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt | +|---|---:|---:|---:| +| Fused conv, `-npl 1` | 38.82 | 34.31 | 24.66 | +| Fused conv, `-npl 1,4` split | 4.56 / 27.36 | 5.17 / 22.47 | 4.47 / Skipped | +| Fused conv, `-npl 1,4 --kv-unified` | 38.40 / 93.43 | 33.98 / 71.90 | Skipped / Skipped | +| Separate conv, `-npl 1` | 38.22 | 33.90 | 24.44 | +| Separate conv, `-npl 1,4` split | 4.52 / 27.53 | 5.13 / 23.07 | Skipped / Skipped | +| Separate conv, `-npl 1,4 --kv-unified` | 37.92 / 90.75 | 33.40 / 71.07 | Skipped / Skipped | + +Prefill duration in seconds (not streaming TTFT). `t_pp` ends after all active prompts finish and synchronization completes. It is a prefill-latency proxy, and includes first-use runtime shape/kernel preparation; it does not include process startup or loading compiled blobs. + +| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt | +|---|---:|---:|---:| +| Fused conv, `-npl 1` | 1.052 | 5.596 | 24.133 | +| Fused conv, `-npl 1,4` split | 2.768 / 4.113 | 12.157 / 88.200 | 37.953 / Skipped | +| Fused conv, `-npl 1,4 --kv-unified` | 1.069 / 2.421 | 6.290 / 29.394 | Skipped / Skipped | +| Separate conv, `-npl 1` | 1.096 | 5.457 | 30.124 | +| Separate conv, `-npl 1,4` split | 3.344 / 4.388 | 8.760 / 27.930 | Skipped / Skipped | +| Separate conv, `-npl 1,4 --kv-unified` | 1.336 / 2.839 | 7.074 / 24.270 | Skipped / Skipped | + +Aggregate prefill throughput in tokens/s. Prompt tokens are independently evaluated for each sequence; no shared-prompt optimization is enabled. + +| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt | +|---|---:|---:|---:| +| Fused conv, `-npl 1` | 973.71 | 1464.03 | 1357.78 | +| Fused conv, `-npl 1,4` split | 370.00 / 995.92 | 673.87 / 371.52 | 863.39 / Skipped | +| Fused conv, `-npl 1,4 --kv-unified` | 957.77 / 1691.56 | 1302.47 / 1114.77 | Skipped / Skipped | +| Separate conv, `-npl 1` | 934.72 | 1501.26 | 1087.77 | +| Separate conv, `-npl 1,4` split | 306.26 / 933.49 | 935.13 / 1173.20 | Skipped / Skipped | +| Separate conv, `-npl 1,4 --kv-unified` | 766.60 / 1442.88 | 1158.11 / 1350.12 | Skipped / Skipped | + +Peak process RSS in GiB for each process (both active-sequence rows together). This is a host process measurement, not dedicated GPU memory or total system consumption. + +| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt | +|---|---:|---:|---:| +| Fused conv, `-npl 1` | 21.23 | 21.31 | 21.31 | +| Fused conv, `-npl 1,4` split | 21.31 | 21.31 | 20.00 | +| Fused conv, `-npl 1,4 --kv-unified` | 21.31 | 21.31 | Skipped | +| Separate conv, `-npl 1` | 21.31 | 21.31 | 21.21 | +| Separate conv, `-npl 1,4` split | 21.31 | 21.31 | Skipped | +| Separate conv, `-npl 1,4 --kv-unified` | 21.31 | 21.31 | Skipped | + +The 30-minute limit interrupted `timed-fused-split-32768` after 267.8 seconds; 1 completed row(s) from that process are retained. Remaining cells are marked Skipped. + + + + +### Findings and next opportunities + +All 1K and 8K cases completed. Both one-slot 32K variants and the fused split-KV +one-active-sequence row completed. The 30-minute limit interrupted the fused +split-KV four-active-sequence case; seven remaining rows were skipped. No further +GPU benchmark is running. RSS shown for the interrupted process covers only its +observed lifetime. System memory and process RSS measure different allocations; +the minimum system `MemAvailable` in completed processes ranged from 8.07 to +34.52 GiB, so the approximately 21 GiB process RSS is not total GPU/system usage. + +Decode rates are close between convolution variants. Fused versus separate +one-slot decode is 38.82 versus 38.22 t/s at 1K, 34.31 versus 33.90 at 8K, and +24.66 versus 24.44 at 32K. Four-active unified decode is 93.43 versus 90.75 at 1K +and 71.90 versus 71.07 at 8K. These single-pass differences do not establish a +repeatable small speedup. + +Separate convolution improves some prefill cases, but not all. Four-active split +8K prefill takes 27.930 seconds versus fused 88.200; unified 8K takes 24.270 +versus 29.394. Conversely, one-slot 32K takes 30.124 seconds versus fused 24.133. +First-use shape/kernel preparation and different memory-pressure samples remain +in these timings. Keep fused convolution as the default and retain the explicit +separate mode for controlled follow-up; a universal long-prefill selection rule +is not justified by this matrix. + +The largest decode gap remains split attention KV. With one active sequence in +four slots, fused 1K decode is 4.56 t/s split versus 38.40 unified, although both +use the same in-place recurrent-cache implementation. At 8K it is 5.17 versus +33.98. The upstream attention fusion excludes split roots because their stream +dimension exceeds one. This comparison points to the attention-cache path and +its layout as the next priority; it does not isolate individual copies or +kernels. Extend the 4D KV translation and StatelessKV fusion to split streams, +then measure actual binding/copy traffic before assigning the residual gap. + +For recurrent computation, optimize fused convolution output stores and layouts, +or remove the separate path's materialization/reorder costs. The kernel control +shows why ordinary convolution arithmetic alone cannot predict full-chain +latency. Both variants retain staged in-place handling for cycles and duplicate +sources, with private output/copy-back for incompatible caller bindings. + +--- + + +Status of the earlier 2026-10-23 campaign: finished. All 16 original server cases and all eight Vulkan full-GPU server reruns completed. Of 40 batched timing rows, 32 completed and eight were skipped at user request. No benchmark remains pending. diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py new file mode 100644 index 000000000000..d0a96a73bc95 --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Populate caches, then run the bounded in-place convolution comparison serially.""" +import argparse +import json +import os +from pathlib import Path +import signal +import subprocess +import time + + +def memory_available_kib(): + for line in Path('/proc/meminfo').read_text().splitlines(): + if line.startswith('MemAvailable:'): + return int(line.split()[1]) + return None + + +def run_case(binary, model, output, mode, layout, prompt, decode, cache_only, deadline=None, probe=None): + name = f'{"timed" if cache_only else "prime"}-{mode}-{layout}-{prompt}' + cache = output / 'model-cache' + spill = output / 'spill' + cache.mkdir(exist_ok=True) + spill.mkdir(exist_ok=True) + env = os.environ.copy() + for key in ('GGML_OPENVINO_DISABLE_KV_SLICE', 'GGML_OPENVINO_RECURRENT_CACHE_INPLACE', + 'GGML_OPENVINO_SEPARATE_RECURRENT_CONV', 'GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY'): + env.pop(key, None) + env.update(GGML_OPENVINO_DEVICE='GPU', GGML_OPENVINO_NATIVE_SOFTPLUS='1', + GGML_OPENVINO_REQUANT_KQUANT='q4_asym64_all', GGML_OPENVINO_ENABLE_KV_4D='1', + GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=str(cache), GGML_OPENVINO_SPILL_DIR=str(spill)) + if mode == 'separate': + env['GGML_OPENVINO_SEPARATE_RECURRENT_CONV'] = '1' + if cache_only: + env['GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY'] = '1' + if probe: + env['LD_PRELOAD'] = str(probe) + cmd = [str(binary), '-m', str(model), '-c', '131072' if layout == 'one' else '524288', + '-npp', str(prompt), '-ntg', str(decode), '-npl', '1' if layout == 'one' else '1,4', + '-b', '8192', '-ub', '8192', '--output-format', 'jsonl'] + if layout == 'unified': + cmd.append('--kv-unified') + meta = dict(name=name, mode=mode, layout=layout, prompt=prompt, decode=decode, command=cmd, + environment={k: v for k, v in env.items() if k.startswith('GGML_OPENVINO_')}, + initial_available_kib=memory_available_kib()) + (output / f'{name}.command.json').write_text(json.dumps(meta, indent=2) + '\n') + started = time.monotonic() + peak_rss = 0 + minimum_available = meta['initial_available_kib'] + timed_out = False + with (output / f'{name}.log').open('w') as log: + proc = subprocess.Popen(cmd, env=env, cwd=output, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + while proc.poll() is None: + try: + for line in Path(f'/proc/{proc.pid}/status').read_text().splitlines(): + if line.startswith(('VmRSS:', 'VmHWM:')): + peak_rss = max(peak_rss, int(line.split()[1])) + except FileNotFoundError: + pass + available = memory_available_kib() + minimum_available = min(minimum_available, available) + if deadline is not None and time.monotonic() >= deadline: + timed_out = True + os.killpg(proc.pid, signal.SIGTERM) + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + break + time.sleep(0.5) + rows = [] + text = (output / f'{name}.log').read_text(errors='replace') + for line in text.splitlines(): + if line.startswith('{"n_kv_max"'): + rows.append(json.loads(line)) + meta.update(exit_code=proc.returncode, elapsed_seconds=time.monotonic() - started, + peak_process_rss_kib=peak_rss, minimum_available_kib=minimum_available, + timed_out=timed_out, rows=rows) + (output / f'{name}.result.json').write_text(json.dumps(meta, indent=2) + '\n') + with (output / 'results.jsonl').open('a') as file: + file.write(json.dumps(meta) + '\n') + print(f'{name}: rc={proc.returncode}, {len(rows)} rows, {meta["elapsed_seconds"]:.1f}s, RSS {peak_rss / 1048576:.2f} GiB', flush=True) + return meta + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--binary', required=True, type=Path) + parser.add_argument('--model', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--phase', choices=('prime', 'timed'), required=True) + parser.add_argument('--minutes', type=float, default=30) + parser.add_argument('--mode', choices=('fused', 'separate')) + parser.add_argument('--layout', choices=('one', 'split', 'unified')) + args = parser.parse_args() + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + modes = [args.mode] if args.mode else ['fused', 'separate'] + layouts = [args.layout] if args.layout else ['one', 'split', 'unified'] + deadline = time.monotonic() + args.minutes * 60 if args.phase == 'timed' else None + for prompt in ([16] if args.phase == 'prime' else [1024, 8192, 32768]): + for layout in layouts: + for mode in modes: + if deadline is not None and time.monotonic() >= deadline: + print('Benchmark deadline reached; remaining cases are skipped.', flush=True) + return + result = run_case(args.binary.resolve(), args.model.resolve(), output, mode, layout, prompt, + 1 if args.phase == 'prime' else 512, args.phase == 'timed', deadline) + if result['exit_code'] != 0 and not result['timed_out']: + raise SystemExit(f'{result["name"]} failed; inspect its raw log before continuing.') + + +if __name__ == '__main__': + main() diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py new file mode 100644 index 000000000000..205bd2192fc5 --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Summarize completed rows from qwen36_ud_inplace_batched.py.""" +import argparse +import json +from pathlib import Path +import re + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--report', type=Path) + parser.add_argument('--finished', action='store_true') + args = parser.parse_args() + results = [json.loads(path.read_text()) for path in args.output.glob('timed-*.result.json')] + results = [result for result in results if result['prompt'] in (1024, 8192, 32768)] + lookup = {(r['mode'], r['layout'], r['prompt']): r for r in results} + complete = sum(len(result['rows']) for result in results) + status = 'Finished' if args.finished else 'In progress' + lines = [f'{status}: {complete}/30 timing rows retained. A row is retained only after its prefill and all 512 decode steps finish.', '', + 'Decode throughput below excludes prefill. Values are aggregate tokens/s, using `speed_tg = pl * tg / t_tg`. In four-slot configurations, `A / B` means one active sequence / four active sequences; divide B by four for the simultaneous per-sequence rate.', ''] + labels = {'one': '`-npl 1`', 'split': '`-npl 1,4` split', 'unified': '`-npl 1,4 --kv-unified`'} + + def table(metric, fmt): + lines.extend(['| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt |', '|---|---:|---:|---:|']) + for mode in ('fused', 'separate'): + for layout in labels: + cells = [] + for prompt in (1024, 8192, 32768): + result = lookup.get((mode, layout, prompt)) + rows = {row['pl']: row for row in result['rows']} if result else {} + missing = 'Skipped' if args.finished or result else 'Pending' + cells.append(' / '.join(format(rows[pl][metric], fmt) if pl in rows else missing + for pl in ((1,) if layout == 'one' else (1, 4)))) + lines.append(f'| {mode.capitalize()} conv, {labels[layout]} | ' + ' | '.join(cells) + ' |') + lines.append('') + + table('speed_tg', '.2f') + lines.extend(['Prefill duration in seconds (not streaming TTFT). `t_pp` ends after all active prompts finish and synchronization completes. It is a prefill-latency proxy, and includes first-use runtime shape/kernel preparation; it does not include process startup or loading compiled blobs.', '']) + table('t_pp', '.3f') + lines.extend(['Aggregate prefill throughput in tokens/s. Prompt tokens are independently evaluated for each sequence; no shared-prompt optimization is enabled.', '']) + table('speed_pp', '.2f') + lines.extend(['Peak process RSS in GiB for each process (both active-sequence rows together). This is a host process measurement, not dedicated GPU memory or total system consumption.', '', + '| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt |', '|---|---:|---:|---:|']) + for mode in ('fused', 'separate'): + for layout in labels: + cells = [] + for prompt in (1024, 8192, 32768): + result = lookup.get((mode, layout, prompt)) + cells.append(f'{result["peak_process_rss_kib"] / 1048576:.2f}' if result else ('Skipped' if args.finished else 'Pending')) + lines.append(f'| {mode.capitalize()} conv, {labels[layout]} | ' + ' | '.join(cells) + ' |') + lines.append('') + for result in results: + if result['timed_out']: + lines.extend([f'The 30-minute limit interrupted `{result["name"]}` after {result["elapsed_seconds"]:.1f} seconds; {len(result["rows"])} completed row(s) from that process are retained. Remaining cells are marked Skipped.', '']) + section = '\n'.join(lines) + '\n' + (args.output / 'matrix.md').write_text(section) + if args.report: + text = args.report.read_text() + pattern = r'(?s)(\n).*?()' + text, count = re.subn(pattern, lambda match: match[1] + section + '\n' + match[2], text) + if count != 1: + raise SystemExit('Report must contain exactly one inplace-results marker pair.') + args.report.write_text(text) + print(f'Updated matrix: {complete}/30 rows, {status.lower()}.') + + +if __name__ == '__main__': + main() From 626aae3906152b71731719e34bdeefb5fd7c9d89 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 27 Oct 2026 08:25:17 +0100 Subject: [PATCH 49/65] docs: complete default-batch OV unified-KV 32K benchmarks Assisted-by: Codex --- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 88 +++++++++++++++++++ .../benchmarks/qwen36_ud_inplace_batched.py | 24 +++-- .../benchmarks/qwen36_ud_inplace_summary.py | 47 ++++++++++ 3 files changed, 153 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index 13e4147e0107..5518edac87e5 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -236,6 +236,94 @@ sources, with private output/copy-back for incompatible caller bindings. --- +## Default-batch completion of the OV 32K cases (2026-10-27) + +This continuation measures the four unified-KV rows left unfinished by the +30-minute large-batch campaign. The initial plan also included three split-KV +rows, but the user skipped those comparisons until the split KV cache bottleneck +is addressed. Vulkan and 64K cases are outside this continuation. Model, +context allocation, in-place caches and requantization are unchanged. The +llama.cpp source is `3d9b2fb78` and OpenVINO is `40d69210bf`; only the benchmark +runner and reporting options change. Default logical batch size is 2048 and +microbatch size is 512. No `-b` or `-ub` flag is passed, and their environment +overrides are cleared. The compiled-model blobs from the earlier campaign are +reused in cache-only mode. GPU workloads run serially. + +Raw commands, logs, timing rows and sampled memory: +`tmp/inplace-kv-default-batch-20261027/target/` in the original llama.cpp workspace. + +```sh +BINARY=/home/zijun/llama.cpp-inplace-perf/build/MtpOVPerf/bin/llama-batched-bench +MODEL="$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" +OUT=/home/zijun/llama.cpp/tmp/inplace-kv-default-batch-20261027/target +CACHE=/home/zijun/llama.cpp/tmp/inplace-kv-retest-20261027/target/model-cache +RUNNER=ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py +python3 "$RUNNER" --binary "$BINARY" --model "$MODEL" --output "$OUT" \ + --cache-dir "$CACHE" --phase timed --default-batch --prompts 32768 \ + --mode fused --layout unified +python3 "$RUNNER" --binary "$BINARY" --model "$MODEL" --output "$OUT" \ + --cache-dir "$CACHE" --phase timed --default-batch --prompts 32768 \ + --mode separate --layout unified +python3 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py \ + --output "$OUT" --report ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md \ + --default-continuation --finished +``` + +The equivalent raw benchmark commands use the same environment as the earlier +in-place rerun: GPU, native softplus, `q4_asym64_all`, `ENABLE_KV_4D=1` and +compiled-model cache-only loading. Only the separate variant sets +`GGML_OPENVINO_SEPARATE_RECURRENT_CONV=1`. + +```sh +"$BINARY" -m "$MODEL" -c 524288 -npp 32768 -ntg 512 -npl 1,4 --kv-unified +``` + +Each of the two processes measures one then four active sequences. Batched-bench +uses random token IDs and does not test MTP acceptance. Split-KV batch/convolution +comparisons are deferred because full-cache handling dominates their decode; +this does not establish that convolution or batch size has no prefill cost. + + +Finished: 4/4 previously unfinished OV unified-KV 32K rows measured with default batch sizes. The three split-KV continuation rows were skipped at user request. + +These are separate continuation measurements with `-b 2048 -ub 512` defaults; neither flag is passed. They do not replace the historical `-b 8192 -ub 8192` rows. Each sequence has 32,768 prompt tokens and 512 decode tokens; four slots and 524,288 total context tokens are allocated in every case. MTP is off. All rates below are aggregate; prefill seconds exclude startup and are not streaming TTFT. + +| Convolution | KV | Active sequences | Prefill seconds | Prefill t/s | Decode t/s | Peak process RSS GiB | Status | +|---|---|---:|---:|---:|---:|---:|---| +| Fused | Unified | 1 | 31.029 | 1056.05 | 24.57 | 21.29 | Complete | +| Fused | Unified | 4 | 175.468 | 746.98 | 40.79 | 21.29 | Complete | +| Separate | Unified | 1 | 31.405 | 1043.40 | 24.40 | 21.31 | Complete | +| Separate | Unified | 4 | 184.804 | 709.25 | 40.72 | 21.31 | Complete | + +Peak process RSS is shared by both rows from a process. It does not include all GPU/system allocations. + + + +All four retained rows finished successfully in approximately 10.2 minutes, +including both process starts. The three split-KV continuation rows are deferred +at user request; none were measured. No Vulkan tests were run and no benchmark +is running. Completed rows confirm the effective defaults `n_batch=2048` and +`n_ubatch=512`, with exactly 512 decode tokens per sequence. Both processes reused +the existing compiled cache without recompilation. Minimum system `MemAvailable` +was 27.19 GiB for fused convolution and 25.45 GiB for separate convolution; peak +process RSS was 21.29 and 21.31 GiB respectively. + +At 32K, separate convolution does not improve this default-batch sample. One-active +decode is 24.57 versus 24.40 t/s, and four-active aggregate decode is 40.79 versus +40.72 t/s for fused versus separate. Fused prefill takes 31.03 versus 31.40 seconds +with one active sequence and 175.47 versus 184.80 with four. These are single +passes, so the small decode differences are not a repeatability claim. + +Against the earlier default-batch unified-KV campaign, the current fused path's +32K four-active decode improves from 7.72 to 40.79 aggregate t/s, approximately +5.28 times, and prefill falls from 1279.25 to 175.47 seconds. This measures the +combined upstream/backend changes, not the in-place KV update in isolation. +The existing Vulkan split-KV four-active reference is 41.53 t/s, about 1.8% above +the current OV unified result. Vulkan's unified four-active 32K row remains +unmeasured, so this is a comparison with its split layout and older source. + +--- + Status of the earlier 2026-10-23 campaign: finished. All 16 original server cases and all eight Vulkan full-GPU server reruns completed. Of 40 batched timing rows, 32 completed diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py index d0a96a73bc95..c4f164f3c029 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py @@ -16,13 +16,17 @@ def memory_available_kib(): return None -def run_case(binary, model, output, mode, layout, prompt, decode, cache_only, deadline=None, probe=None): +def run_case(binary, model, output, mode, layout, prompt, decode, cache_only, deadline=None, probe=None, + default_batch=False, cache_dir=None): name = f'{"timed" if cache_only else "prime"}-{mode}-{layout}-{prompt}' - cache = output / 'model-cache' + cache = cache_dir if cache_dir is not None else output / 'model-cache' spill = output / 'spill' cache.mkdir(exist_ok=True) spill.mkdir(exist_ok=True) env = os.environ.copy() + if default_batch: + env.pop('LLAMA_ARG_BATCH', None) + env.pop('LLAMA_ARG_UBATCH', None) for key in ('GGML_OPENVINO_DISABLE_KV_SLICE', 'GGML_OPENVINO_RECURRENT_CACHE_INPLACE', 'GGML_OPENVINO_SEPARATE_RECURRENT_CONV', 'GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY'): env.pop(key, None) @@ -36,11 +40,14 @@ def run_case(binary, model, output, mode, layout, prompt, decode, cache_only, de if probe: env['LD_PRELOAD'] = str(probe) cmd = [str(binary), '-m', str(model), '-c', '131072' if layout == 'one' else '524288', - '-npp', str(prompt), '-ntg', str(decode), '-npl', '1' if layout == 'one' else '1,4', - '-b', '8192', '-ub', '8192', '--output-format', 'jsonl'] + '-npp', str(prompt), '-ntg', str(decode), '-npl', '1' if layout == 'one' else '1,4'] + if not default_batch: + cmd.extend(['-b', '8192', '-ub', '8192']) + cmd.extend(['--output-format', 'jsonl']) if layout == 'unified': cmd.append('--kv-unified') meta = dict(name=name, mode=mode, layout=layout, prompt=prompt, decode=decode, command=cmd, + default_batch=default_batch, requested_parallel=cmd[cmd.index('-npl') + 1], environment={k: v for k, v in env.items() if k.startswith('GGML_OPENVINO_')}, initial_available_kib=memory_available_kib()) (output / f'{name}.command.json').write_text(json.dumps(meta, indent=2) + '\n') @@ -93,20 +100,25 @@ def main(): parser.add_argument('--minutes', type=float, default=30) parser.add_argument('--mode', choices=('fused', 'separate')) parser.add_argument('--layout', choices=('one', 'split', 'unified')) + parser.add_argument('--default-batch', action='store_true', help='Omit batch flags and use the binary defaults.') + parser.add_argument('--prompts', type=int, nargs='+', help='Prompt lengths to run instead of the phase defaults.') + parser.add_argument('--cache-dir', type=Path, help='Reuse an existing compiled-model cache directory.') args = parser.parse_args() output = args.output.resolve() output.mkdir(parents=True, exist_ok=True) modes = [args.mode] if args.mode else ['fused', 'separate'] layouts = [args.layout] if args.layout else ['one', 'split', 'unified'] deadline = time.monotonic() + args.minutes * 60 if args.phase == 'timed' else None - for prompt in ([16] if args.phase == 'prime' else [1024, 8192, 32768]): + cache_dir = args.cache_dir.resolve() if args.cache_dir else None + for prompt in (args.prompts or ([16] if args.phase == 'prime' else [1024, 8192, 32768])): for layout in layouts: for mode in modes: if deadline is not None and time.monotonic() >= deadline: print('Benchmark deadline reached; remaining cases are skipped.', flush=True) return result = run_case(args.binary.resolve(), args.model.resolve(), output, mode, layout, prompt, - 1 if args.phase == 'prime' else 512, args.phase == 'timed', deadline) + 1 if args.phase == 'prime' else 512, args.phase == 'timed', deadline, + default_batch=args.default_batch, cache_dir=cache_dir) if result['exit_code'] != 0 and not result['timed_out']: raise SystemExit(f'{result["name"]} failed; inspect its raw log before continuing.') diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py index 205bd2192fc5..28af9c981af1 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py @@ -6,12 +6,59 @@ import re +def summarize_continuation(args): + cases = [('fused', 'unified', (1, 4)), ('separate', 'unified', (1, 4))] + observations = [] + complete = 0 + for mode, layout, parallel in cases: + name = f'timed-{mode}-{layout}-32768' + path = args.output / f'{name}.result.json' + result = json.loads(path.read_text()) if path.exists() else None + rows = result['rows'] if result else [] + log = args.output / f'{name}.log' + if result is None and log.exists(): + rows = [json.loads(line) for line in log.read_text(errors='replace').splitlines() + if line.startswith('{"n_kv_max"')] + by_parallel = {row['pl']: row for row in rows} + for pl in parallel: + row = by_parallel.get(pl) + complete += row is not None + status = 'Complete' if row else ('Incomplete' if args.finished else ('Running' if log.exists() else 'Pending')) + if result and result['exit_code'] != 0 and row is None: + status = f'Failed ({result["exit_code"]})' + observations.append((mode, layout, pl, row, result, status)) + status = 'Finished' if args.finished else 'In progress' + lines = [f'{status}: {complete}/4 previously unfinished OV unified-KV 32K rows measured with default batch sizes. The three split-KV continuation rows were skipped at user request.', '', + 'These are separate continuation measurements with `-b 2048 -ub 512` defaults; neither flag is passed. They do not replace the historical `-b 8192 -ub 8192` rows. Each sequence has 32,768 prompt tokens and 512 decode tokens; four slots and 524,288 total context tokens are allocated in every case. MTP is off. All rates below are aggregate; prefill seconds exclude startup and are not streaming TTFT.', '', + '| Convolution | KV | Active sequences | Prefill seconds | Prefill t/s | Decode t/s | Peak process RSS GiB | Status |', + '|---|---|---:|---:|---:|---:|---:|---|'] + for mode, layout, pl, row, result, state in observations: + values = [f'{row[key]:.{digits}f}' if row else '-' for key, digits in [('t_pp', 3), ('speed_pp', 2), ('speed_tg', 2)]] + rss = f'{result["peak_process_rss_kib"] / 1048576:.2f}' if result else '-' + lines.append(f'| {mode.capitalize()} | {layout.capitalize()} | {pl} | ' + ' | '.join(values) + f' | {rss} | {state} |') + lines.extend(['', 'Peak process RSS is shared by both rows from a process. It does not include all GPU/system allocations.', '']) + section = '\n'.join(lines) + (args.output / 'matrix.md').write_text(section + '\n') + if args.report: + text = args.report.read_text() + pattern = r'(?s)(\n).*?()' + text, count = re.subn(pattern, lambda match: match[1] + section + '\n' + match[2], text) + if count != 1: + raise SystemExit('Report must contain exactly one default-continuation marker pair.') + args.report.write_text(text) + print(f'Updated default-batch continuation: {complete}/4 rows, {status.lower()}.') + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output', required=True, type=Path) parser.add_argument('--report', type=Path) parser.add_argument('--finished', action='store_true') + parser.add_argument('--default-continuation', action='store_true', help='Summarize the four default-batch OV unified-KV 32K continuation rows.') args = parser.parse_args() + if args.default_continuation: + summarize_continuation(args) + return results = [json.loads(path.read_text()) for path in args.output.glob('timed-*.result.json')] results = [result for result in results if result['prompt'] in (1024, 8192, 32768)] lookup = {(r['mode'], r['layout'], r['prompt']): r for r in results} From da95d1b1c0b22c637ed008cd9e7e96d85427c7c8 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 06:25:19 +0100 Subject: [PATCH 50/65] openvino: remove the separate recurrent convolution path Assisted-by: Codex --- ggml/src/ggml-openvino/README.md | 11 ++++++----- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 8 ++++---- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 2 +- ggml/src/ggml-openvino/ggml-openvino-extra.cpp | 1 - .../openvino/op/recurrent_cache_update.hpp | 5 ++--- .../openvino/recurrent_cache_fusion.cpp | 12 ++++-------- ggml/src/ggml-openvino/utils.cpp | 7 +------ 7 files changed, 18 insertions(+), 28 deletions(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 7edd0be96751..0cf161c20a37 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -12,17 +12,18 @@ Parameter and Result share a stable caller-owned USM allocation. Required source rows are staged on device before writes, so resets, cyclic reorders and rollback remain generic. Incompatible bindings use private output plus Result copy-back. Rotation banks and the older three-op native path are removed. -`GGML_OPENVINO_SEPARATE_RECURRENT_CONV=1` makes the convolution Update op produce -history plus QKV for the ordinary GroupConvolution instead of fusing convolution. +The convolution Update op always takes depthwise weights and produces convolution +and the updated cache; the separate history/QKV mode is removed. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary GGML decomposition. -Rebuild both repos and regenerate compiled-model blobs for translation revision 11. +Rebuild both repos and regenerate compiled-model blobs for translation revision 12. Set `GGML_OPENVINO_ENABLE_KV_4D=1` to enable the upstream stateless in-place attention KV update pattern where eligible. It binds full-capacity cache tensors and lets the GPU fusion expose the live prefix to attention. The current upstream eligibility check supports one physical stream (including unified KV); explicit split multi-slot KV retains the ordinary full-cache path. This option does not -change recurrent cache handling. +change recurrent cache handling. Unified KV is recommended for multi-slot GPU +execution because it enables this in-place attention update. The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_DISABLE_KV_SLICE` unset to use live-prefix attention cache bindings where supported. The [large-context comparison](dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md#large-context-attention-kv-slicing-2026-10-22) measures the benefit and documents the single-stream restriction. Earlier [performance measurements](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) used disabled slicing; yamini-model results remain historical references. @@ -59,7 +60,7 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally. -Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`, `GGML_OPENVINO_ENABLE_KV_4D`, `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`, and `GGML_OPENVINO_SEPARATE_RECURRENT_CONV`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. +Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`, `GGML_OPENVINO_ENABLE_KV_4D`, and `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode. `GGML_OPENVINO_DISABLE_KV_SLICE` is a runtime binding option and can differ between cache population and cache-only runs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Slicing is enabled by default for contiguous ordinary K/V roots with one allocated stream, one active sequence at offset zero, and no sliding-window attention. Recurrent convolution/GDN caches and their rollback snapshots always retain their full stored row bank. Other layouts use full bindings. Repopulate caches made before this option was removed from the fingerprint once without cache-only mode. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 17b92203891e..dbbc277dfdaa 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -3,12 +3,12 @@ Dynamic stateless GPU graphs use the independent `RecurrentConvCacheUpdate` and `RecurrentGatedDeltaNetUpdate` ops for Qwen3.5/Qwen3.6 in llama.cpp. In-place USM bindings are primary; private output and copy-back handle incompatible bindings. -There are no rotation banks. `GGML_OPENVINO_SEPARATE_RECURRENT_CONV=1` selects -history/QKV output plus ordinary GroupConvolution. See the backend README for -current settings and the multislot report for the new benchmark campaign. +The convolution op always includes depthwise computation; separate history/QKV +output and rotation banks are removed. See the backend README for current +settings and the multislot report for the benchmark comparisons. The remaining sections are historical measurements and design notes. Their -rotation ops, opt-in in-place flag and branch layout describe earlier versions. +rotation ops, separate-convolution mode, opt-in in-place flag and branch layout describe earlier versions. --- diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md index 53ad6970c523..2d856b847787 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md @@ -3,7 +3,7 @@ The measurements below are historical. The current in-place implementation and the fused/separate convolution rerun are documented in [the 2026-10-27 benchmark campaign](QWEN36-UD-MULTISLOT-BENCHMARK.md#in-place-kv-and-recurrent-convolution-rerun-2026-10-27). -The current code removes the recurrent rotation ops and buffer banks. +The current code removes the recurrent rotation ops, buffer banks and separate-convolution mode. `RecurrentConvCacheUpdate` always takes nine inputs, including depthwise weights; see the linked report for cleanup validation and translation revision 12. 2026-10-21. This work supports Qwen3.5 and Qwen3.6 (`qwen35`/`qwen35moe`) in llama.cpp's OpenVINO backend, including multi-slot llama-server and draft-MTP diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index e98e2691fe4f..e1581a13fc22 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -146,7 +146,6 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_DISABLE_CACHE", "GGML_OPENVINO_DISABLE_KV_SLICE", "GGML_OPENVINO_DISABLE_FUSED_RECURRENCE", - "GGML_OPENVINO_SEPARATE_RECURRENT_CONV", "GGML_OPENVINO_ENABLE_KV_4D", "GGML_OPENVINO_ENABLE_FALLBACK", "GGML_OPENVINO_KV_SCATTER_ELEMENTS", diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp index 6666a2bab989..b107e878d2ce 100644 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp @@ -6,9 +6,8 @@ namespace ov::op::internal { /// Qwen3.5/Qwen3.6 llama.cpp convolution and generic cache_r maintenance. /// Inputs: original cache, active rows, extra rows, reset begin/length, -/// extra offsets, QKV [1,B,C,T], windows and optional depthwise weights. -/// With nine inputs output 0 is convolution [1,B,T,C]; with eight it is -/// history plus QKV [1,B,C,history+T] for a separate GroupConvolution. +/// extra offsets, QKV [1,B,C,T], windows and depthwise weights. +/// Nine inputs; output 0 is convolution [1,B,T,C]. /// Output 1 is the complete updated [1,1,S,C*history] cache. /// GPU execution may reuse a caller's identical input/output USM allocation only /// when it is the exclusive cache reader. Required original rows are gathered into diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp index 4d7bd29af185..8a67d2c72cc3 100644 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp @@ -284,21 +284,17 @@ OutputVector RecurrentCacheFusion::translate(int index, const NodeContext & cont const auto history = context.get_input_shape(0)[3].get_length(); NodeContext compute_context(m_decoder, m_tensors, group.compute); const auto channels = context.get_input_shape(0)[2].get_length(); - const bool separate = ggml_openvino_getenv_int("GGML_OPENVINO_SEPARATE_RECURRENT_CONV") > 0; - if (!separate) { - inputs.push_back(std::make_shared(compute_context.get_input(1), - constant({4}, {1, 1, channels, history + 1}), false)); - } + inputs.push_back(std::make_shared(compute_context.get_input(1), + constant({4}, {1, 1, channels, history + 1}), false)); auto fused = std::make_shared(inputs, history); fused->set_friendly_name(compute_context.get_name() + "/RecurrentConvCacheUpdate"); group.conv = fused->output(0); group.updated = fused->output(1); - return separate ? OutputVector{group.conv} : op::translate_concat(context); + return op::translate_concat(context); } if (index == group.compute) { if (group.concat >= 0) { - return ggml_openvino_getenv_int("GGML_OPENVINO_SEPARATE_RECURRENT_CONV") > 0 ? - op::translate_ssm_conv(context) : OutputVector{group.conv}; + return {group.conv}; } inputs.push_back(context.get_input("rs_update_" + m_decoder->get_op_name(group.writeback))); auto outputs = op::translate_recurrent_gated_delta_net(context, inputs); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index b42e98031d71..6a95b1d00631 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -170,16 +170,11 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : ggml_openvino_is_gpu(); - uint64_t extra_cfg = 11; // Stable in-place caches and optional separate convolution. + uint64_t extra_cfg = 12; // Fused convolution with stable in-place caches. #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ? 0u : 1u); #else extra_cfg = extra_cfg * 131; -#endif -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_SEPARATE_RECURRENT_CONV") ? 1u : 0u); -#else - extra_cfg = extra_cfg * 131; #endif extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u); From c1ae620025555034ca6824d2b3200b5837ee9f0e Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 06:25:20 +0100 Subject: [PATCH 51/65] openvino: handle zero-logits batches and changing sampler sequences Assisted-by: Codex --- .../ggml-openvino/openvino/op/get_rows.cpp | 25 +++++++-------- ggml/src/ggml-openvino/openvino/utils.cpp | 6 ++-- ggml/src/ggml-openvino/utils.h | 14 +++++++-- tests/test-backend-sampler.cpp | 31 ++++++++++++++++++- 4 files changed, 56 insertions(+), 20 deletions(-) diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index 297148235c62..d439c9670250 100644 --- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp @@ -11,9 +11,9 @@ #include #include #include +#include #include #include -#include #include namespace ov { @@ -66,18 +66,15 @@ OutputVector translate_get_rows(const NodeContext & context) { // data[1,b,x,y] ind[1,1,b,x'] test-backend-ops case // data[x,y] ind[1,1,1,x'] normal case - // Squeeze the leading dims down to [b,x']. Stateful models drop one rank, so a hardcoded + // Drop the leading dims down to [b,x']. Stateful models drop one rank, so a hardcoded // {0,1} would also strip the batch dim whenever b == 1 (every decode step). const auto indices_rank = indices.get_partial_shape().rank(); FRONT_END_OP_CONVERSION_CHECK(indices_rank.is_static(), "Expected static rank for GET_ROWS indices"); - std::vector indices_squeeze_axes; - for (int64_t i = 0; i + 2 < indices_rank.get_length(); ++i) { - indices_squeeze_axes.push_back(i); - } - if (!indices_squeeze_axes.empty()) { - indices = std::make_shared( - indices, ov::op::v0::Constant::create(ov::element::i64, {indices_squeeze_axes.size()}, - indices_squeeze_axes)); + if (indices_rank.get_length() > 2) { + // Keep zero-token batches: GPU Squeeze-to-Reshape can treat a zero dimension as a copy marker. + indices = std::make_shared( + indices, get_dimensions(indices.get_node_shared_ptr(), + {int(indices_rank.get_length() - 2), int(indices_rank.get_length() - 1)}), false); } if (row_offset != 0) { indices = std::make_shared( @@ -86,14 +83,14 @@ OutputVector translate_get_rows(const NodeContext & context) { if (data.get_partial_shape().rank() == 4) { if (!(data.get_partial_shape()[1].is_dynamic()) && data.get_partial_shape()[1].get_length() == 1) { // Work-around for a bug in ov cpu plugin for test-backend-ops - data = std::make_shared(data, - ov::op::v0::Constant::create(ov::element::i64, {2}, {0, 1})); + data = std::make_shared( + data, get_dimensions(data.get_node_shared_ptr(), {2, 3}), false); auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}); res = std::make_shared(data, indices, axis); } else { auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1}); - data = - std::make_shared(data, ov::op::v0::Constant::create(ov::element::i64, {1}, {0})); + data = std::make_shared( + data, get_dimensions(data.get_node_shared_ptr(), {1, 2, 3}), false); // data: [batch, rows, ...], indices: [batch, n] - this is a batched gather // (batch_dims=1) along the rows axis. The data and indices batch dims are // logically equal (both == n_tokens) but reach this node through independent diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index 227d9f851438..8ff6be01bda7 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -463,8 +463,9 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return input; } + // 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) { + 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); @@ -495,7 +496,8 @@ ov::Output process_view_input_new(const NodeContext & context, int inp } } - if (!context.is_static() && view_input_size == 1 && context.has_input("s_copy_active_slot_len")) { + if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real() && + context.has_input("s_copy_active_slot_len")) { 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); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index aa9ebcf6ef95..17c591825a53 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -18,14 +18,15 @@ // Cache key for a translated/compiled graph. Node count plus the two end node names identify a // graph during inference, where the same few graphs repeat for the whole session. The list of // external input names below tells those apart more precisely, but it walks every node and every -// src slot, so it is built only when GGML_OPENVINO_FULL_GRAPH_KEY is set. Op tests run many small -// graphs that can share a node count and end names, and need the full key. +// src slot, so it is built only when GGML_OPENVINO_FULL_GRAPH_KEY is set. Sampler row names are +// always included because changing the active sequence changes those Parameters. Op tests run +// many small graphs that can share a node count and end names, and need the full key. struct graph_key { int n_nodes; int n_leaves; std::string first_node_name; std::string last_node_name; - // Each entry: "::" + // External source descriptors "::" and sampler row Parameter names. std::vector input_srcs; graph_key(const ggml_cgraph * cgraph, bool include_inputs = false) : n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) { @@ -34,6 +35,13 @@ struct graph_key { last_node_name = cgraph->nodes[n_nodes - 1]->name; } + for (int i = 0; i < n_nodes; ++i) { + const auto * node = cgraph->nodes[i]; + if (GgmlOvDecoder::is_sampling_view(node)) { + input_srcs.push_back("sampling_row_" + std::string(node->name) + "#n" + std::to_string(i)); + } + } + static const bool full_key = ggml_openvino_getenv_int("GGML_OPENVINO_FULL_GRAPH_KEY") != 0; if (!full_key && !include_inputs) { return; diff --git a/tests/test-backend-sampler.cpp b/tests/test-backend-sampler.cpp index 637d7fe9a670..5622ae6b3ae3 100644 --- a/tests/test-backend-sampler.cpp +++ b/tests/test-backend-sampler.cpp @@ -1158,7 +1158,8 @@ static void test_backend_top_k_rows_impl(const test_params & params, uint32_t n_ bool output; }; const batch_case cases[] = {{{2, 2}, true}, {{1, 1}, true}, {{2, 0}, false}, - {{0, 3}, true}, {{2, 1}, true}, {{1, 1}, true}, {{1, 0}, true}}; + {{0, 3}, true}, {{2, 1}, true}, {{1, 1}, true}, {{1, 0}, true}, + {{0, 1}, true}, {{1, 0}, true}}; int32_t positions[2] = {0, 0}; int case_index = 0; for (const auto & c : cases) { @@ -1350,6 +1351,33 @@ static void test_backend_recurrent_slots(const test_params & params) { printf("backend recurrent slot reset/copy/rollback test PASSED\n"); } +static void test_backend_recurrent_no_logits_prefill(const test_params & params) { + std::vector configs; + for (uint32_t rollback : {0u, 2u}) { + test_context ctx(params, configs, 4, 12, 16, 3, rollback); + // Alternate prefill without logits and logits batches on the same context. + for (int step = 0; step < 4; ++step) { + common_batch batch(ctx.ctx.get()); + const int sequences = step == 3 ? 1 : 4; + const bool logits = step % 2 != 0; + for (int seq = 0; seq < sequences; ++seq) { + batch.add((100 + step * 4 + seq) % ctx.n_vocab, step, seq, logits); + } + GGML_ASSERT(llama_process(ctx.ctx.get(), LLAMA_PROCESS_TYPE_DECODE, batch.get()) == 0); + if (logits) { + for (int seq = 0; seq < sequences; ++seq) { + const float * values = llama_get_logits_ith(ctx.ctx.get(), seq); + GGML_ASSERT(values); + for (int i = 0; i < ctx.n_vocab; ++i) { + GGML_ASSERT(std::isfinite(values[i])); + } + } + } + } + } + printf("backend recurrent prefill without logits test PASSED\n"); +} + static float find_backend_logit(const backend_sampler_output & output, llama_token token) { for (size_t i = 0; i < output.candidates.size(); ++i) { if (output.candidates[i] == token) { @@ -2317,6 +2345,7 @@ static const backend_test_case BACKEND_TESTS[] = { { "top_k_rollback", test_backend_top_k_rows_rollback, false }, { "top_k_hidden_rollback", test_backend_top_k_hidden_rollback, false }, { "recurrent_slots", test_backend_recurrent_slots, false }, + { "recurrent_no_logits_prefill", test_backend_recurrent_no_logits_prefill, false }, }; // TODO: add usage, examples From c2d9797774b5bf10da0c9431dc8b4f398ef09288 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 06:29:32 +0100 Subject: [PATCH 52/65] docs: compare default and large Qwen3.6 benchmark batches Assisted-by: Codex --- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 174 ++++++++++++++++-- .../benchmarks/qwen36_ud_batch_size_bench.py | 125 +++++++++++++ .../benchmarks/qwen36_ud_inplace_batched.py | 69 ++++--- .../benchmarks/qwen36_ud_inplace_summary.py | 100 +++++++++- 4 files changed, 415 insertions(+), 53 deletions(-) create mode 100644 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_batch_size_bench.py diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index 5518edac87e5..4011875a6468 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -1,9 +1,162 @@ -# Qwen3.6 UD multi-slot benchmark (2026-10-23) +# Qwen3.6 UD multi-slot benchmark + +## Matched default and large batch measurements (2026-10-28) + +OV prefill benefits from larger batches in every completed one-slot and unified-KV comparison. The unresolved exception is unified 32K with four active sequences, which became extremely slow and was canceled. The completed Vulkan comparisons show no useful large-batch prefill advantage. Decode throughput is generally unchanged. + + +Completed 47/60 originally planned timing rows. Selected campaign finished. Missing rows: 1 canceled, 12 skipped. + +This campaign compares default `-b 2048 -ub 512` with large `-b 8192 -ub 8192` on the same llama.cpp source. Default batch flags are omitted. OV uses fused in-place recurrent caches, GPU, native softplus, `q4_asym64_all`, `ENABLE_KV_4D=1`, enabled KV slicing and compiled-model cache-only loading. Vulkan uses the stored GGUF weights. GPU workloads run serially, with no elapsed-time cap. + +Each cell is **prefill seconds @ aggregate decode tokens/s**; four-slot rows show **one active / four active sequences**. Prompt lengths are 1024/8192/32768 tokens per sequence, with 512 generated tokens each. One-slot context is 131072 and four-slot context is 524288 total. MTP and shared-prompt processing are off; batched-bench uses random token IDs. Each timing row is one pass. Prefill includes first-use runtime shape/kernel preparation, excludes model loading and is not streaming TTFT. Decode excludes prefill. + +### Default batch: `-b / -ub = 2048 / 512` + +| Backend/configuration | 1K prompt | 8K prompt | 32K prompt | +|---|---:|---:|---:| +| OV fused `-npl 1` | 1.197 @ 34.61 | 7.703 @ 33.77 | 32.539 @ 24.51 | +| OV fused `-npl 1,4` split | 8.959 @ 4.54 / 7.095 @ 27.22 | 10.842 @ 5.19 / 38.769 @ 23.06 | 43.922 @ 4.47 / 170.131 @ 14.54 | +| OV fused `-npl 1,4 --kv-unified` | 1.158 @ 37.46 / 3.479 @ 91.95 | 7.224 @ 33.51 / 30.785 @ 71.41 | 30.326 @ 24.42 / 179.282 @ 40.84 | +| Vulkan `-npl 1` | 1.591 @ 32.37 | 18.586 @ 30.69 | 253.293 @ 26.04 | +| Vulkan `-npl 1,4` split | 1.454 @ 32.59 / 5.808 @ 73.90 | 18.586 @ 30.49 / 74.234 @ 66.32 | Skipped / Skipped | +| Vulkan `-npl 1,4 --kv-unified` | 1.459 @ 32.56 / 5.844 @ 73.63 | 18.573 @ 30.76 / 74.996 @ 56.38 | Skipped / Skipped | + +OpenVINO recorded-process peak RSS: 21.30-21.31 GiB. Lowest sampled system MemAvailable: 11.45 GiB. + +Vulkan recorded-process peak RSS: 0.24-0.66 GiB. Lowest sampled system MemAvailable: 22.14 GiB. + +### Large batch: `-b / -ub = 8192 / 8192` + +| Backend/configuration | 1K prompt | 8K prompt | 32K prompt | +|---|---:|---:|---:| +| OV fused `-npl 1` | 1.072 @ 37.85 | 5.147 @ 33.68 | 22.989 @ 24.31 | +| OV fused `-npl 1,4` split | 2.640 @ 4.53 / 4.896 @ 27.05 | 9.554 @ 5.10 / 41.408 @ 22.61 | 28.137 @ 4.44 / 181.780 @ 14.51 | +| OV fused `-npl 1,4 --kv-unified` | 1.089 @ 37.33 / 2.402 @ 92.00 | 6.498 @ 33.46 / 25.233 @ 71.52 | 25.083 @ 24.38 / Canceled | +| Vulkan `-npl 1` | 1.548 @ 32.42 | 24.700 @ 30.68 | Skipped | +| Vulkan `-npl 1,4` split | 1.533 @ 32.41 / 9.641 @ 74.00 | 24.446 @ 30.81 / Skipped | Skipped / Skipped | +| Vulkan `-npl 1,4 --kv-unified` | 1.562 @ 32.44 / 9.658 @ 72.78 | Skipped / Skipped | Skipped / Skipped | + +OpenVINO recorded-process peak RSS: 21.27-21.31 GiB. Lowest sampled system MemAvailable: 6.89 GiB. + +Vulkan recorded-process peak RSS: 0.55-0.66 GiB. Lowest sampled system MemAvailable: 19.64 GiB. + +Canceled `openvino/large/timed-fused-unified-32768`: Stopped with user approval after 2147.7 seconds of process wall time; the four-active timing row was incomplete and the last stack snapshot was inside prefill. Preserve the completed one-active row. Completed timing rows and sampled memory are retained; missing timings are not extrapolated. + +Canceled `vulkan/large/timed-vulkan-split-8192`: Stopped after the user approved a preliminary conclusion and skipping remaining unnecessary large-batch Vulkan tests. Completed timing rows and sampled memory are retained; missing timings are not extrapolated. + +Process RSS does not include every GPU/system allocation. Per-process command, timing and memory records are stored with the raw results. + +Raw artifacts: `/home/zijun/llama.cpp/tmp/batch-size-matrix-20261028`. Source patches, base commits and binary identities are recorded in the campaign metadata. + + + +### Interpretation + +Every completed OV one-slot and unified-KV prefill comparison improved with the larger batch, including unified KV with one active sequence at 32K. The unresolved exception is 32K with four active sequences, which became extremely slow and was canceled. Single-slot prefill improves as follows: 8K drops from 7.703 to 5.147 seconds (33% less), and 32K from 32.539 to 22.989 seconds (29% less). Unified four-active prefill also improves at 1K/8K, from 3.479/30.785 to 2.402/25.233 seconds (31%/18% less). Decode rates are generally unchanged. These are single-pass observations. + +Larger batches are not a universal improvement. Split four-active 8K/32K prefill is about 7% slower at 8192. Unified four-active 32K with 8192 was stopped with user approval after 2147.7 seconds of process wall time; its completed one-active row is retained. A stack snapshot mapped to the prefill call inside GPU inference, before decode timing, but did not identify the responsible kernel. Defaults are the safer choice for long multi-sequence prefill until this case is profiled. No missing prefill or decode rate is inferred from the process wall time. + +The Vulkan rows do not show a useful large-batch prefill advantage. One-slot 8K prefill increases from 18.586 to 24.700 seconds (33% more), and four-active 1K split/unified prefill increases from 5.808/5.844 to 9.641/9.658 seconds (about 65-66% more). Decode is nearly unchanged. This supports keeping Vulkan defaults for this workload; kernel optimization, dispatch/layout choices and first-use preparation need profiling before assigning a cause. + +With default batches, OV unified four-active decode is 91.95 t/s at 1K and 71.41 t/s at 8K, versus Vulkan split's 73.90/66.32 t/s and Vulkan unified's 73.63/56.38 t/s. OV is about 24%/8% ahead of the faster Vulkan layout in these two cases. At one-slot 32K, OV decode is about 5.9% below Vulkan (24.51 versus 26.04 t/s), while OV prefill is about 7.8 times faster (32.539 versus 253.293 seconds). Fresh Vulkan 32K multi-slot comparisons were deliberately skipped; the older references below remain historical. + +### Profiling limits and next work + +The canceled process had about 42.9 GiB of resident graphics GTT allocations in a Xe driver snapshot, which is not captured completely by process RSS. Dense attention masks scale as live KV span times microbatch tokens; at a fixed span, an 8192-token mask is 16 times larger than a 512-token mask. Mask construction/upload, attention kernel selection and first-use shape/kernel preparation are profiling candidates, not established causes. Two brief stack checks took less than a second combined; the process was otherwise allowed to run until cancellation. Diagnostics are saved as `ov-large-32k-stack.txt`, `ov-large-32k-prefill-call-site.txt` and `ov-large-32k-drm-fdinfo.txt` in the campaign artifact directory. + +The next priorities are to diagnose the large-batch unified 32K/four-active prefill slowdown, profile the remaining one-slot long-context attention/decode gap, and extend the upstream in-place attention KV update to split streams. The recurrent cache banks already have in-place fused convolution/GDN updates; their size depends on slots and snapshots rather than the attention context window. These comparisons do not isolate individual kernel times. New MTP performance measurements remain separate from this non-MTP campaign. + +### Reproduce the campaign + +This campaign measures both batch configurations on the current fused in-place implementation and a Vulkan build from the same llama.cpp source. The original matrix covers 1K/8K/32K prompts for one slot and four slots with split/unified KV, including one and four active sequences in each four-slot allocation. After enough preliminary data was available, the user approved skipping unnecessary remaining Vulkan large-batch tests and lengthy 32K multi-slot comparisons. Missing entries remain explicit. The 30-minute limit is removed. An 8192-token microbatch is a useful comparison point because one 8K prompt fits in it; it is not assumed to be optimal. + +```sh +python3 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_batch_size_bench.py \ + --openvino-binary /home/zijun/llama.cpp-inplace-perf/build/MtpOVPerf/bin/llama-batched-bench \ + --vulkan-binary /home/zijun/llama.cpp-inplace-perf/build/VulkanBatchPerf/bin/llama-batched-bench \ + --model "$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" \ + --output /home/zijun/llama.cpp/tmp/batch-size-matrix-20261028 \ + --openvino-source /home/zijun/openvino \ + --report ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +``` + +The runner populates the OV caches once per layout, shares them across batch settings, and resumes completed timing processes. The continuation used `--skip-canceled` to retain the explicitly canceled OV result and finish the remaining backend cases. Settings inherited through `LLAMA_ARG_*`, `GGML_OPENVINO_*`, `GGML_VULKAN_*` and `LD_PRELOAD` are cleared before each process; the recorded OV configuration is then applied. Batched-bench loads directly and does not use the server's automatic expert fitting. The narrowed `--skip-case` selection is saved in `metadata/skipped-cases.json` and reused when resuming this output directory; use a fresh output directory for a full rerun. + +## Historical conclusions and mixed-batch snapshot (2026-10-28) + +Unified KV with in-place attention and recurrent cache updates is the recommended OV GPU multi-slot configuration for this model. The current native path uses fused convolution and GDN; rotation and the experimental separate-convolution path are removed. + +- Split attention KV remains the largest performance problem. With one active sequence in four allocated slots, the latest 1K sample reaches 4.56 t/s split versus 38.40 t/s unified. Both use in-place recurrent caches; the upstream in-place attention KV fusion currently excludes split streams. +- At default batch sizes, the combined upstream/backend changes raise unified four-active 32K decode from 7.72 to 40.79 aggregate t/s and reduce prefill from 1279.25 to 175.47 seconds. These improvements do not isolate in-place KV, recurrent cache handling or batch size as the sole cause. +- The latest OV unified four-active 32K result is about 1.8% below the older Vulkan split reference, 41.53 t/s. The one-slot 32K OV result is about 5% below the older Vulkan one-slot reference. Vulkan unified four-active 32K remains unmeasured; source revisions and compressed weight representations differ between backends. +- Separate convolution provides no consistent full-model advantage. At default-batch 32K, fused/separate four-active decode is 40.79/40.72 t/s, and fused prefill is faster in that sample. These single-pass differences do not establish a repeatable small decode speedup. +- The earlier short-prompt MMLU server campaign showed MTP improving OV unified decode from 36.47 to 51.35 t/s for one request and from 21.73 to 25.91 t/s per request with four in flight. Those server measurements used the earlier rotation implementation. The current fused-only cleanup has passed functional MTP checks, but has no new 512-token server performance campaign. + +### Earlier mixed-batch snapshot + +Each entry is **prefill seconds @ aggregate decode tokens/s**. In four-slot rows, entries are **one active / four active sequences**. Prefill time is synchronized prompt evaluation time, not streaming TTFT; decode rates exclude prefill. MTP is off, prompts use random token IDs, and each completed row generates 512 tokens per sequence. One-slot context capacity is 131072; four-slot capacity is 524288 total. + +**Batch settings:** latest OV 1K/8K rows and one-slot/split 32K rows use `-b 8192 -ub 8192`. The OV unified 32K cell marked `[D]` uses defaults, `-b 2048 -ub 512`, with neither flag passed. Vulkan references use those defaults and come from the earlier 2026-10-23 source. This matrix collects the latest available rows; its prefill comparisons are not a matched batch-size experiment. The complete historical default-batch matrix remains under [Result matrices](#result-matrices). + +| Backend/configuration | 1K prompt | 8K prompt | 32K prompt | 64K prompt | +|---|---:|---:|---:|---:| +| OV fused `-npl 1` | 1.052 @ 38.82 | 5.596 @ 34.31 | 24.133 @ 24.66 | Not measured | +| OV fused `-npl 1,4` split | 2.768 @ 4.56 / 4.113 @ 27.36 | 12.157 @ 5.17 / 88.200 @ 22.47 | 37.953 @ 4.47 / Skipped | Not measured / Not measured | +| OV fused `-npl 1,4 --kv-unified` | 1.069 @ 38.40 / 2.421 @ 93.43 | 6.290 @ 33.98 / 29.394 @ 71.90 | 31.029 @ 24.57 / 175.468 @ 40.79 [D] | Not measured / Not measured | +| Vulkan reference `-npl 1` | 1.498 @ 32.49 | 18.785 @ 30.59 | 255.503 @ 25.99 | 1013.906 @ 19.80 | +| Vulkan reference `-npl 1,4` split | 1.508 @ 32.45 / 5.931 @ 72.39 | 18.901 @ 30.31 / 75.542 @ 65.11 | 258.362 @ 25.99 / 1021.572 @ 41.53 | Skipped / Skipped | +| Vulkan reference `-npl 1,4 --kv-unified` | 1.492 @ 32.44 / 5.964 @ 71.82 | 18.785 @ 30.69 / 75.933 @ 55.31 | 254.584 @ 25.42 / Skipped | Skipped / Skipped | + +`Not measured` means no row for the latest OV implementation; some earlier OV 64K split measurements remain in the historical matrix. `Skipped` means an unfinished or canceled row. No missing value is extrapolated. Measured OV peak process RSS is about 21.3 GiB; it excludes some GPU/system allocations. Vulkan batched peak memory was not recorded. + +### Effect of batch size + +`-b` limits the logical batch submitted to llama.cpp. `-ub` limits each physical microbatch executed by the model; prompt processing may split one logical batch into several microbatches. Defaults are `-b 2048 -ub 512`. + +| Phase | Actual tokens in a model step | Expected effect of raising the limits to 8192 | +|---|---|---| +| Prefill | Up to the microbatch limit | Can materially change latency and throughput through fewer graph executions, different kernel/layout choices and larger temporary allocations. An 8K single prompt can fit one 8192-token microbatch rather than sixteen 512-token chunks. Larger is not necessarily faster. | +| Non-MTP decode | One token per active sequence: 1 or 4 here | Little direct effect: both limits already fit each step. Setting 8192 does not turn a four-token decode step into an 8192-token step. | +| Two-token MTP verification | Normally up to 3 tokens per active sequence: 12 with four active | Also well below the default 512-token microbatch limit. Raising the limits does not directly increase this verification batch. | + +Larger limits can still affect decode indirectly through reserved compute/output memory, memory pressure and runtime kernel or cache behavior. These historical samples had no controlled same-source, same-layout comparison that changed only `-b`/`-ub`; the earlier-to-later implementation improvements must not be attributed to batch size. The matched campaign at the top addresses that gap. Native GenAI supports chunked prefill, while its latency-oriented client configuration permits a much larger token budget; that does not establish the optimal llama.cpp microbatch size. + +Next work: extend in-place attention KV updates to split streams, profile the remaining single-sequence long-context decode gap, optimize fused convolution memory access and output layouts, and measure MTP performance on the current implementation. Cleanup validation and the unresolved MoE-slice numerical experiment are documented below. + +## Current implementation + +Current implementation after the convolution cleanup: `RecurrentConvCacheUpdate` always fuses depthwise convolution and takes nine inputs. The separate-convolution mode and `GGML_OPENVINO_SEPARATE_RECURRENT_CONV` switch are removed in both repositories. Unified KV is recommended for multi-slot OV GPU execution because the upstream in-place attention KV update supports that layout. Translation revision 12 requires rebuilding both repositories and repopulating compiled-model caches. + +The fused/separate comparisons below are historical measurements. Separate convolution showed no advantage in the unified-KV samples, so future work can focus on the fused computation. Historical runner commands require llama.cpp revision `626aae390`; the current runner runs fused convolution only. Existing timing rows are preserved. + +## Fused convolution cleanup and validation (2026-10-27) + +Validation and benchmarks used the working-tree patches over llama.cpp `626aae390` and OV `40d69210bf`, recorded with the binary identities in the campaign metadata. The inference changes are now committed as llama.cpp `da95d1b1c` (fused-convolution cleanup) and `c1ae62002` (zero-logits/sampler fixes) on `qwen-openvino-inplace-perf`, and OV `9299cc3d78` on `qwen-mtp-inplace-primary`. The binaries were built before these commits; the inference source is unchanged. + +The cleanup removes the eight-input history-only convolution contract, its GPU kernel branch, and the llama.cpp environment switch and benchmark selection. The native convolution op now requires weights and produces convolution plus the updated cache. Generic reset, reorder, snapshots, in-place USM binding and the fallback with private outputs retain their semantics. The new OV op specifications and both backend integration documents describe this contract. The summary script shows only fused rows for new runs and can still read archived comparisons. + +Short-prompt validation also exposed existing view-translation errors when a server prompt chunk updates recurrent caches but requests no logits. Integer MoE routing views could match the packed-activation and recurrent-state stride heuristics. Both heuristics now require floating-point inputs. GET_ROWS uses runtime-shape Reshapes to remove leading singleton dimensions, preserving zero dimensions that the GPU Squeeze conversion lost. `recurrent_no_logits_prefill` covers alternating batches with and without logits, changing active sequence counts, and zero/two rollback positions. + +The initial full-model MTP smoke returned the requested tokens but logged a missing sampler input when only one of four requests remained active. The local graph key used node counts and end names, which could match for different active sequence IDs even though their sampler row Parameters differed. Those Parameter names are now always included in the key. The top-k row regression adds a sequence-0-only -> sequence-1-only -> sequence-0-only transition; it reproduced the input-lookup failure before the fix. + +- Release builds of OpenVINO runtime/GPU plugin and llama.cpp server, batched benchmark and sampler test passed. +- All 12 native cache-update GPU/core tests passed, including cycles, duplicates, overlapping windows, precision, host/device USM, reader restrictions and export/import. +- The unchanged Qwen3.5-2B Q4_0 recurrent reset/copy/rollback test passed 50 replay comparisons; maximum relative logit error was 0.004191. +- The extended Qwen3.5-2B Q4_0 `top_k_rows`, `top_k_rollback` and `top_k_hidden_rollback` regressions passed, including the active sampler-ID transition that failed before the cache-key fix. Numerical thresholds are unchanged. +- The four-layer UD MoE slice passed `recurrent_no_logits_prefill` with `q4_asym64_all` and zero/two rollback positions. Its server test also completed one request and four concurrent requests, each generating 32 tokens. +- The full target UD model passed one request followed by four concurrent requests, with MTP off and on. Each request processed 14 prompt tokens and generated exactly 32 tokens; responses contained the expected answer, and the successful logs contain no errors. All five MTP requests generated and accepted drafts. + +Full-model smoke settings: `llama-server -np 4 -c 8192 --kv-unified --temp 0`, default batch sizes, GPU, native softplus, `q4_asym64_all` and `GGML_OPENVINO_ENABLE_KV_4D=1`. KV slicing is enabled. MTP adds `--spec-type draft-mtp --spec-draft-n-max 2`. The checks use fresh compilation rather than cache-only mode. Successful commands, responses and logs are in `tmp/fused-conv-cleanup-20261027/target-final/mtp-off.*` and `tmp/fused-conv-cleanup-20261027/target-keyed/mtp-on.*`. The initial MTP attempt and its sampler error remain in `target-final/mtp-on.*` for reference. + +An additional experiment inserted a no-logits prefix into the numerical replay test on the four-layer MoE slice. It differed by 0.041318 at the first comparison and did not meet the existing 0.01 threshold. That experiment is not a numerical-equivalence result and is not included in the passed checks above. The original numerical test and threshold are unchanged; the focused regression tests the observed compute failure without asserting equivalence across different prefill chunk boundaries. + +Raw cleanup build/test logs are under `tmp/fused-conv-cleanup-20261027*`; server commands and responses are under `tmp/fused-conv-cleanup-20261027/` in the original llama.cpp workspace. These are functional checks, not replacements for the 512-token performance campaign. Validation is on the GPU stateless path; CPU, NPU and stateful execution were not retested. ## In-place KV and recurrent convolution rerun (2026-10-27) -This is a separate campaign; earlier tables use the previous translation and -`-b 2048 -ub 512`. The current code merges `origin/dev_backend_openvino` +This historical campaign predates the fused-only cleanup above; its commands and mode switches require the recorded source revisions. Earlier tables use the previous translation and +`-b 2048 -ub 512`. The measured code merges `origin/dev_backend_openvino` `0974aef91`, removes recurrent rotation, and compares fused convolution against history/QKV output plus ordinary GroupConvolution. No new server or Vulkan measurements are part of this rerun. @@ -35,7 +188,7 @@ measurements are part of this rerun. The upstream merge, cache implementation and batch sizes all changed from the earlier campaign. These results do not isolate the effect of any one change. -Reproducible runner: [qwen36_ud_inplace_batched.py](benchmarks/qwen36_ud_inplace_batched.py). +Historical runner: [qwen36_ud_inplace_batched.py](benchmarks/qwen36_ud_inplace_batched.py) at revision `626aae390`. Raw commands, outputs, memory samples and status: `tmp/inplace-kv-retest-20261027/target/` in the original llama.cpp workspace. The six compiled blobs total approximately 108 GiB on disk. They are shared @@ -68,7 +221,7 @@ export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 "$BINARY" -m "$MODEL" -c 524288 -npp 1024,8192,32768 -ntg 512 -npl 1,4 --kv-unified -b 8192 -ub 8192 ``` -### Validation +### Validation of the historical comparison All 13 native shape, attribute and GPU test cases pass, including history-only convolution, cyclic/duplicate reorders, overlapping windows/snapshots, mixed @@ -215,9 +368,7 @@ Separate convolution improves some prefill cases, but not all. Four-active split 8K prefill takes 27.930 seconds versus fused 88.200; unified 8K takes 24.270 versus 29.394. Conversely, one-slot 32K takes 30.124 seconds versus fused 24.133. First-use shape/kernel preparation and different memory-pressure samples remain -in these timings. Keep fused convolution as the default and retain the explicit -separate mode for controlled follow-up; a universal long-prefill selection rule -is not justified by this matrix. +in these timings. The later default-batch unified-KV results also show no separate-convolution advantage, so the cleanup above removes that mode and retains fused convolution. A universal long-prefill selection rule is not justified by this matrix. The largest decode gap remains split attention KV. With one active sequence in four slots, fused 1K decode is 4.56 t/s split versus 38.40 unified, although both @@ -228,8 +379,7 @@ its layout as the next priority; it does not isolate individual copies or kernels. Extend the 4D KV translation and StatelessKV fusion to split streams, then measure actual binding/copy traffic before assigning the residual gap. -For recurrent computation, optimize fused convolution output stores and layouts, -or remove the separate path's materialization/reorder costs. The kernel control +For recurrent computation, optimize fused convolution output stores and layouts. The historical kernel control shows why ordinary convolution arithmetic alone cannot predict full-chain latency. Both variants retain staged in-place handling for cycles and duplicate sources, with private output/copy-back for incompatible caller bindings. @@ -238,7 +388,7 @@ sources, with private output/copy-back for incompatible caller bindings. ## Default-batch completion of the OV 32K cases (2026-10-27) -This continuation measures the four unified-KV rows left unfinished by the +This historical continuation uses the pre-cleanup runner, including its removed `--mode` option. It measures the four unified-KV rows left unfinished by the 30-minute large-batch campaign. The initial plan also included three split-KV rows, but the user skipped those comparisons until the split KV cache bottleneck is addressed. Vulkan and 64K cases are outside this continuation. Model, @@ -354,6 +504,8 @@ The OpenVINO binary was rebuilt after reverting an experimental input fallback. ## Result matrices +These are historical measurements from the 2026-10-23 implementation with recurrent rotation and default batch sizes, `-b 2048 -ub 512`. See the overview for the latest fused in-place OV rows and their batch settings. The tables below retain the original completed measurements. + The campaign is finished: 32 batched timing rows, 16 original server cases and 8 Vulkan server reruns completed. Eight remaining batched rows were canceled. No benchmark is pending. All completed cases decode 512 tokens per sequence. diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_batch_size_bench.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_batch_size_bench.py new file mode 100644 index 000000000000..1588ff292bea --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_batch_size_bench.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Run matched default/large-batch OV and Vulkan benchmarks, resuming completed cases.""" +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +from qwen36_ud_inplace_batched import run_case +from qwen36_ud_inplace_summary import summarize_batch_comparison + + +def validate_result(result, binary, model, layout, prompt, decode, default_batch, backend, allow_canceled=False): + expected = [1] if layout == 'one' else [1, 4] + canceled = allow_canceled and result.get('canceled', False) + if (result['exit_code'] != 0 or result['timed_out']) and not canceled: + raise RuntimeError(f'{result["name"]} did not finish successfully; inspect its log.') + if result['command'][0] != str(binary) or result['command'][2] != str(model): + raise RuntimeError('Saved result uses another binary path or model.') + if result.get('backend', 'openvino') != backend or result['default_batch'] != default_batch: + raise RuntimeError('Saved result uses another backend or batch configuration.') + parallel = sorted(row['pl'] for row in result['rows']) + if (not canceled and parallel != expected) or (canceled and not set(parallel).issubset(expected)): + raise RuntimeError(f'{result["name"]} does not contain all requested parallel rows.') + for row in result['rows']: + if (row['pp'], row['tg']) != (prompt, decode): + raise RuntimeError('Saved prompt/decode counts do not match the campaign.') + batch = (2048, 512) if default_batch else (8192, 8192) + if (row['n_batch'], row['n_ubatch']) != batch: + raise RuntimeError('Effective batch sizes do not match the campaign.') + + +def record_binary(directory, backend, binary): + paths = [binary] + for name in ('libllama.so', 'libggml-openvino.so', 'libggml-vulkan.so'): + path = binary.parent / name + if path.exists(): + paths.append(path) + identities = {} + for path in paths: + digest = hashlib.sha256() + with path.open('rb') as file: + for data in iter(lambda: file.read(1048576), b''): + digest.update(data) + identities[str(path)] = digest.hexdigest() + path = directory / f'{backend}-binary.json' + if path.exists() and json.loads(path.read_text()) != identities: + raise RuntimeError('Binary identities changed; use a new campaign output directory.') + path.write_text(json.dumps(identities, indent=2) + '\n') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--openvino-binary', required=True, type=Path) + parser.add_argument('--vulkan-binary', required=True, type=Path) + parser.add_argument('--model', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--report', type=Path) + parser.add_argument('--openvino-source', type=Path) + parser.add_argument('--skip-canceled', action='store_true', help='Retain explicitly canceled result records and continue remaining cases.') + cases = [f'{backend}/{batch}/{layout}/{prompt}' for backend in ('openvino', 'vulkan') + for batch in ('default', 'large') for layout in ('one', 'split', 'unified') + for prompt in (1024, 8192, 32768)] + parser.add_argument('--skip-case', action='append', choices=cases, default=[], + help='Skip a backend/batch/layout/prompt process; the selection is saved for resumption.') + args = parser.parse_args() + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + model = args.model.resolve() + metadata = output / 'metadata' + metadata.mkdir(exist_ok=True) + selection = metadata / 'skipped-cases.json' + skipped = set(args.skip_case) + if selection.exists(): + skipped.update(json.loads(selection.read_text())) + selection.write_text(json.dumps(sorted(skipped), indent=2) + '\n') + source = Path(__file__).resolve().parents[5] + for name, directory in [('llamacpp', source), ('openvino', args.openvino_source)]: + if directory: + path = metadata / f'{name}-source.json' + if not path.exists(): + base = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=directory, text=True).strip() + patch = subprocess.check_output(['git', 'diff'], cwd=directory) + path.write_text(json.dumps({'directory': str(directory), 'base': base}, indent=2) + '\n') + (metadata / f'{name}.patch').write_bytes(patch) + cache = output / 'model-cache' + prime = output / 'prime' + prime.mkdir(exist_ok=True) + ov_binary = args.openvino_binary.resolve() + record_binary(metadata, 'openvino', ov_binary) + summarize_batch_comparison(output, args.report) + for layout in ('one', 'split', 'unified'): + path = prime / f'prime-fused-{layout}-16.result.json' + result = json.loads(path.read_text()) if path.exists() else run_case( + ov_binary, model, prime, layout, 16, 1, False, cache_dir=cache) + validate_result(result, ov_binary, model, layout, 16, 1, False, 'openvino') + for backend, binary in [('openvino', ov_binary), ('vulkan', args.vulkan_binary.resolve())]: + record_binary(metadata, backend, binary) + for prompt in (1024, 8192, 32768): + for layout in ('one', 'split', 'unified'): + for batch in ('default', 'large'): + case = f'{backend}/{batch}/{layout}/{prompt}' + if case in skipped: + print(f'Skipped by selection: {case}', flush=True) + continue + directory = output / backend / batch + directory.mkdir(parents=True, exist_ok=True) + name = f'timed-{"fused" if backend == "openvino" else "vulkan"}-{layout}-{prompt}' + path = directory / f'{name}.result.json' + if path.exists(): + result = json.loads(path.read_text()) + print(f'Resuming: retained {backend}/{batch}/{name}', flush=True) + else: + print(f'Running {backend}/{batch}/{name}', flush=True) + result = run_case(binary, model, directory, layout, prompt, 512, + backend == 'openvino', default_batch=batch == 'default', + cache_dir=cache, backend=backend, phase='timed') + summarize_batch_comparison(output, args.report) + validate_result(result, binary, model, layout, prompt, 512, batch == 'default', backend, + allow_canceled=args.skip_canceled) + summarize_batch_comparison(output, args.report, finished=True) + + +if __name__ == '__main__': + main() diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py index c4f164f3c029..dbf1cd00a498 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_batched.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Populate caches, then run the bounded in-place convolution comparison serially.""" +"""Populate caches, then benchmark fused in-place recurrence serially.""" import argparse import json import os @@ -16,27 +16,22 @@ def memory_available_kib(): return None -def run_case(binary, model, output, mode, layout, prompt, decode, cache_only, deadline=None, probe=None, - default_batch=False, cache_dir=None): - name = f'{"timed" if cache_only else "prime"}-{mode}-{layout}-{prompt}' +def run_case(binary, model, output, layout, prompt, decode, cache_only, deadline=None, probe=None, + default_batch=False, cache_dir=None, backend='openvino', phase=None): + phase = phase or ('timed' if cache_only else 'prime') + name = f'{phase}-{"fused" if backend == "openvino" else "vulkan"}-{layout}-{prompt}' cache = cache_dir if cache_dir is not None else output / 'model-cache' spill = output / 'spill' - cache.mkdir(exist_ok=True) - spill.mkdir(exist_ok=True) - env = os.environ.copy() - if default_batch: - env.pop('LLAMA_ARG_BATCH', None) - env.pop('LLAMA_ARG_UBATCH', None) - for key in ('GGML_OPENVINO_DISABLE_KV_SLICE', 'GGML_OPENVINO_RECURRENT_CACHE_INPLACE', - 'GGML_OPENVINO_SEPARATE_RECURRENT_CONV', 'GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY'): - env.pop(key, None) - env.update(GGML_OPENVINO_DEVICE='GPU', GGML_OPENVINO_NATIVE_SOFTPLUS='1', - GGML_OPENVINO_REQUANT_KQUANT='q4_asym64_all', GGML_OPENVINO_ENABLE_KV_4D='1', - GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=str(cache), GGML_OPENVINO_SPILL_DIR=str(spill)) - if mode == 'separate': - env['GGML_OPENVINO_SEPARATE_RECURRENT_CONV'] = '1' - if cache_only: - env['GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY'] = '1' + env = {key: value for key, value in os.environ.items() + if not key.startswith(('GGML_OPENVINO_', 'GGML_VULKAN_', 'LLAMA_ARG_')) and key != 'LD_PRELOAD'} + if backend == 'openvino': + cache.mkdir(parents=True, exist_ok=True) + spill.mkdir(parents=True, exist_ok=True) + env.update(GGML_OPENVINO_DEVICE='GPU', GGML_OPENVINO_NATIVE_SOFTPLUS='1', + GGML_OPENVINO_REQUANT_KQUANT='q4_asym64_all', GGML_OPENVINO_ENABLE_KV_4D='1', + GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=str(cache), GGML_OPENVINO_SPILL_DIR=str(spill)) + if cache_only: + env['GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY'] = '1' if probe: env['LD_PRELOAD'] = str(probe) cmd = [str(binary), '-m', str(model), '-c', '131072' if layout == 'one' else '524288', @@ -46,9 +41,10 @@ def run_case(binary, model, output, mode, layout, prompt, decode, cache_only, de cmd.extend(['--output-format', 'jsonl']) if layout == 'unified': cmd.append('--kv-unified') - meta = dict(name=name, mode=mode, layout=layout, prompt=prompt, decode=decode, command=cmd, + meta = dict(name=name, mode='fused' if backend == 'openvino' else 'gguf', backend=backend, + layout=layout, prompt=prompt, decode=decode, command=cmd, default_batch=default_batch, requested_parallel=cmd[cmd.index('-npl') + 1], - environment={k: v for k, v in env.items() if k.startswith('GGML_OPENVINO_')}, + environment={k: v for k, v in env.items() if k.startswith(('GGML_OPENVINO_', 'GGML_VULKAN_'))}, initial_available_kib=memory_available_kib()) (output / f'{name}.command.json').write_text(json.dumps(meta, indent=2) + '\n') started = time.monotonic() @@ -65,7 +61,8 @@ def run_case(binary, model, output, mode, layout, prompt, decode, cache_only, de except FileNotFoundError: pass available = memory_available_kib() - minimum_available = min(minimum_available, available) + if available is not None: + minimum_available = available if minimum_available is None else min(minimum_available, available) if deadline is not None and time.monotonic() >= deadline: timed_out = True os.killpg(proc.pid, signal.SIGTERM) @@ -97,8 +94,8 @@ def main(): parser.add_argument('--model', required=True, type=Path) parser.add_argument('--output', required=True, type=Path) parser.add_argument('--phase', choices=('prime', 'timed'), required=True) - parser.add_argument('--minutes', type=float, default=30) - parser.add_argument('--mode', choices=('fused', 'separate')) + parser.add_argument('--minutes', type=float, default=30, help='Timed-run limit; zero disables the limit.') + parser.add_argument('--backend', choices=('openvino', 'vulkan'), default='openvino') parser.add_argument('--layout', choices=('one', 'split', 'unified')) parser.add_argument('--default-batch', action='store_true', help='Omit batch flags and use the binary defaults.') parser.add_argument('--prompts', type=int, nargs='+', help='Prompt lengths to run instead of the phase defaults.') @@ -106,21 +103,21 @@ def main(): args = parser.parse_args() output = args.output.resolve() output.mkdir(parents=True, exist_ok=True) - modes = [args.mode] if args.mode else ['fused', 'separate'] layouts = [args.layout] if args.layout else ['one', 'split', 'unified'] - deadline = time.monotonic() + args.minutes * 60 if args.phase == 'timed' else None + deadline = time.monotonic() + args.minutes * 60 if args.phase == 'timed' and args.minutes > 0 else None cache_dir = args.cache_dir.resolve() if args.cache_dir else None for prompt in (args.prompts or ([16] if args.phase == 'prime' else [1024, 8192, 32768])): for layout in layouts: - for mode in modes: - if deadline is not None and time.monotonic() >= deadline: - print('Benchmark deadline reached; remaining cases are skipped.', flush=True) - return - result = run_case(args.binary.resolve(), args.model.resolve(), output, mode, layout, prompt, - 1 if args.phase == 'prime' else 512, args.phase == 'timed', deadline, - default_batch=args.default_batch, cache_dir=cache_dir) - if result['exit_code'] != 0 and not result['timed_out']: - raise SystemExit(f'{result["name"]} failed; inspect its raw log before continuing.') + if deadline is not None and time.monotonic() >= deadline: + print('Benchmark deadline reached; remaining cases are skipped.', flush=True) + return + result = run_case(args.binary.resolve(), args.model.resolve(), output, layout, prompt, + 1 if args.phase == 'prime' else 512, + args.phase == 'timed' and args.backend == 'openvino', deadline, + default_batch=args.default_batch, cache_dir=cache_dir, + backend=args.backend, phase=args.phase) + if result['exit_code'] != 0 and not result['timed_out']: + raise SystemExit(f'{result["name"]} failed; inspect its raw log before continuing.') if __name__ == '__main__': diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py index 28af9c981af1..822dd169433a 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py @@ -1,11 +1,91 @@ #!/usr/bin/env python3 -"""Summarize completed rows from qwen36_ud_inplace_batched.py.""" +"""Summarize fused benchmarks and archived convolution comparisons.""" import argparse import json from pathlib import Path import re +def summarize_batch_comparison(output, report=None, finished=False): + observations = {} + complete = 0 + selection = output / 'metadata' / 'skipped-cases.json' + skipped = set(json.loads(selection.read_text())) if selection.exists() else set() + for backend in ('openvino', 'vulkan'): + for batch in ('default', 'large'): + directory = output / backend / batch + for layout in ('one', 'split', 'unified'): + for prompt in (1024, 8192, 32768): + name = f'timed-{"fused" if backend == "openvino" else "vulkan"}-{layout}-{prompt}' + path = directory / f'{name}.result.json' + log = directory / f'{name}.log' + result = json.loads(path.read_text()) if path.exists() else None + rows = result['rows'] if result else [] + if result is None and log.exists(): + rows = [json.loads(line) for line in log.read_text(errors='replace').splitlines() + if line.startswith('{"n_kv_max"')] + rows = {row['pl']: row for row in rows if row['tg'] == 512} + complete += len(rows) + state = ('Skipped' if f'{backend}/{batch}/{layout}/{prompt}' in skipped else + 'Canceled' if result and result.get('canceled') else + 'Failed' if result and result['exit_code'] else + 'Incomplete' if finished else 'Running' if log.exists() else 'Pending') + observations[backend, batch, layout, prompt] = (rows, result, state) + lines = [f'Completed {complete}/60 originally planned timing rows. ' + ('Selected campaign finished.' if finished else 'Campaign in progress.'), '', + 'This campaign compares default `-b 2048 -ub 512` with large `-b 8192 -ub 8192` on the same llama.cpp source. Default batch flags are omitted. OV uses fused in-place recurrent caches, GPU, native softplus, `q4_asym64_all`, `ENABLE_KV_4D=1`, enabled KV slicing and compiled-model cache-only loading. Vulkan uses the stored GGUF weights. GPU workloads run serially, with no elapsed-time cap.', '', + 'Each cell is **prefill seconds @ aggregate decode tokens/s**; four-slot rows show **one active / four active sequences**. Prompt lengths are 1024/8192/32768 tokens per sequence, with 512 generated tokens each. One-slot context is 131072 and four-slot context is 524288 total. MTP and shared-prompt processing are off; batched-bench uses random token IDs. Each timing row is one pass. Prefill includes first-use runtime shape/kernel preparation, excludes model loading and is not streaming TTFT. Decode excludes prefill.', ''] + if finished: + missing = {} + for (_, _, layout, _), (rows, _, state) in observations.items(): + count = sum(pl not in rows for pl in ((1,) if layout == 'one' else (1, 4))) + if count: + missing[state] = missing.get(state, 0) + count + if missing: + lines[0] += ' Missing rows: ' + ', '.join(f'{count} {state.lower()}' for state, count in missing.items()) + '.' + labels = {'one': '`-npl 1`', 'split': '`-npl 1,4` split', 'unified': '`-npl 1,4 --kv-unified`'} + for batch, settings in [('default', '2048 / 512'), ('large', '8192 / 8192')]: + lines.extend([f'### {batch.capitalize()} batch: `-b / -ub = {settings}`', '', + '| Backend/configuration | 1K prompt | 8K prompt | 32K prompt |', + '|---|---:|---:|---:|']) + for backend in ('openvino', 'vulkan'): + for layout in labels: + cells = [] + for prompt in (1024, 8192, 32768): + rows, _, state = observations[backend, batch, layout, prompt] + cells.append(' / '.join(f'{rows[pl]["t_pp"]:.3f} @ {rows[pl]["speed_tg"]:.2f}' + if pl in rows else state + for pl in ((1,) if layout == 'one' else (1, 4)))) + lines.append(f'| {"OV fused" if backend == "openvino" else "Vulkan"} {labels[layout]} | ' + ' | '.join(cells) + ' |') + lines.append('') + for backend in ('openvino', 'vulkan'): + results = [result for (name, size, _, _), (_, result, _) in observations.items() + if name == backend and size == batch and result] + if results: + rss = [result['peak_process_rss_kib'] / 1048576 for result in results] + available = [result['minimum_available_kib'] / 1048576 for result in results + if result['minimum_available_kib'] is not None] + memory = f'{"OpenVINO" if backend == "openvino" else "Vulkan"} recorded-process peak RSS: {min(rss):.2f}-{max(rss):.2f} GiB.' + if available: + memory += f' Lowest sampled system MemAvailable: {min(available):.2f} GiB.' + lines.extend([memory, '']) + for (backend, batch, _, _), (_, result, _) in observations.items(): + if result and result.get('canceled'): + lines.extend([f'Canceled `{backend}/{batch}/{result["name"]}`: {result["cancel_reason"]} ' + 'Completed timing rows and sampled memory are retained; missing timings are not extrapolated.', '']) + lines.extend(['Process RSS does not include every GPU/system allocation. Per-process command, timing and memory records are stored with the raw results.', '', + f'Raw artifacts: `{output}`. Source patches, base commits and binary identities are recorded in the campaign metadata.', '']) + section = '\n'.join(lines) + (output / 'matrix.md').write_text(section + '\n') + if report: + text = report.read_text() + pattern = r'(?s)(\n).*?()' + text, count = re.subn(pattern, lambda match: match[1] + section + '\n' + match[2], text) + if count != 1: + raise SystemExit('Report must contain exactly one batch-comparison marker pair.') + report.write_text(text) + print(f'Updated batch-size comparison: {complete}/60 rows.', flush=True) + + def summarize_continuation(args): cases = [('fused', 'unified', (1, 4)), ('separate', 'unified', (1, 4))] observations = [] @@ -54,23 +134,31 @@ def main(): parser.add_argument('--output', required=True, type=Path) parser.add_argument('--report', type=Path) parser.add_argument('--finished', action='store_true') - parser.add_argument('--default-continuation', action='store_true', help='Summarize the four default-batch OV unified-KV 32K continuation rows.') + parser.add_argument('--batch-comparison', action='store_true', help='Summarize the matched default/large OV and Vulkan campaign.') + parser.add_argument('--default-continuation', action='store_true', help='Summarize the four archived default-batch OV unified-KV 32K continuation rows.') args = parser.parse_args() + if args.batch_comparison: + summarize_batch_comparison(args.output, args.report, args.finished) + return if args.default_continuation: summarize_continuation(args) return results = [json.loads(path.read_text()) for path in args.output.glob('timed-*.result.json')] results = [result for result in results if result['prompt'] in (1024, 8192, 32768)] lookup = {(r['mode'], r['layout'], r['prompt']): r for r in results} + modes = ['fused'] + if any(result['mode'] == 'separate' for result in results): + modes.append('separate') + total = 15 * len(modes) complete = sum(len(result['rows']) for result in results) status = 'Finished' if args.finished else 'In progress' - lines = [f'{status}: {complete}/30 timing rows retained. A row is retained only after its prefill and all 512 decode steps finish.', '', + lines = [f'{status}: {complete}/{total} timing rows retained. A row is retained only after its prefill and all 512 decode steps finish.', '', 'Decode throughput below excludes prefill. Values are aggregate tokens/s, using `speed_tg = pl * tg / t_tg`. In four-slot configurations, `A / B` means one active sequence / four active sequences; divide B by four for the simultaneous per-sequence rate.', ''] labels = {'one': '`-npl 1`', 'split': '`-npl 1,4` split', 'unified': '`-npl 1,4 --kv-unified`'} def table(metric, fmt): lines.extend(['| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt |', '|---|---:|---:|---:|']) - for mode in ('fused', 'separate'): + for mode in modes: for layout in labels: cells = [] for prompt in (1024, 8192, 32768): @@ -89,7 +177,7 @@ def table(metric, fmt): table('speed_pp', '.2f') lines.extend(['Peak process RSS in GiB for each process (both active-sequence rows together). This is a host process measurement, not dedicated GPU memory or total system consumption.', '', '| OV convolution / KV configuration | 1K prompt | 8K prompt | 32K prompt |', '|---|---:|---:|---:|']) - for mode in ('fused', 'separate'): + for mode in modes: for layout in labels: cells = [] for prompt in (1024, 8192, 32768): @@ -109,7 +197,7 @@ def table(metric, fmt): if count != 1: raise SystemExit('Report must contain exactly one inplace-results marker pair.') args.report.write_text(text) - print(f'Updated matrix: {complete}/30 rows, {status.lower()}.') + print(f'Updated matrix: {complete}/{total} rows, {status.lower()}.') if __name__ == '__main__': From 2803132ec100faf8fd64d33bdc7e5b5f5baedfc8 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 07:02:44 +0100 Subject: [PATCH 53/65] docs: use the historical Vulkan default-batch reference consistently Assisted-by: Codex --- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 17 ++++++++------- .../benchmarks/qwen36_ud_inplace_summary.py | 21 ++++++++++++++++++- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index 4011875a6468..5f641f6202c9 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -1,9 +1,10 @@ # Qwen3.6 UD multi-slot benchmark -## Matched default and large batch measurements (2026-10-28) +## Batch-size measurements with a historical Vulkan reference (2026-10-28) OV prefill benefits from larger batches in every completed one-slot and unified-KV comparison. The unresolved exception is unified 32K with four active sequences, which became extremely slow and was canceled. The completed Vulkan comparisons show no useful large-batch prefill advantage. Decode throughput is generally unchanged. + Completed 47/60 originally planned timing rows. Selected campaign finished. Missing rows: 1 canceled, 12 skipped. @@ -11,6 +12,8 @@ This campaign compares default `-b 2048 -ub 512` with large `-b 8192 -ub 8192` o Each cell is **prefill seconds @ aggregate decode tokens/s**; four-slot rows show **one active / four active sequences**. Prompt lengths are 1024/8192/32768 tokens per sequence, with 512 generated tokens each. One-slot context is 131072 and four-slot context is 524288 total. MTP and shared-prompt processing are off; batched-bench uses random token IDs. Each timing row is one pass. Prefill includes first-use runtime shape/kernel preparation, excludes model loading and is not streaming TTFT. Decode excludes prefill. +The default-batch Vulkan rows below use the 2026-10-23 Release build at `dd06588b1`, selected as the reference because the current-build results were similar. OV and large-batch Vulkan rows use the current campaign. This displayed comparison spans source revisions; the 47 measured campaign rows and their original values remain in the raw artifacts. Historical reference rows do not increase the campaign completion count. + ### Default batch: `-b / -ub = 2048 / 512` | Backend/configuration | 1K prompt | 8K prompt | 32K prompt | @@ -18,13 +21,13 @@ Each cell is **prefill seconds @ aggregate decode tokens/s**; four-slot rows sho | OV fused `-npl 1` | 1.197 @ 34.61 | 7.703 @ 33.77 | 32.539 @ 24.51 | | OV fused `-npl 1,4` split | 8.959 @ 4.54 / 7.095 @ 27.22 | 10.842 @ 5.19 / 38.769 @ 23.06 | 43.922 @ 4.47 / 170.131 @ 14.54 | | OV fused `-npl 1,4 --kv-unified` | 1.158 @ 37.46 / 3.479 @ 91.95 | 7.224 @ 33.51 / 30.785 @ 71.41 | 30.326 @ 24.42 / 179.282 @ 40.84 | -| Vulkan `-npl 1` | 1.591 @ 32.37 | 18.586 @ 30.69 | 253.293 @ 26.04 | -| Vulkan `-npl 1,4` split | 1.454 @ 32.59 / 5.808 @ 73.90 | 18.586 @ 30.49 / 74.234 @ 66.32 | Skipped / Skipped | -| Vulkan `-npl 1,4 --kv-unified` | 1.459 @ 32.56 / 5.844 @ 73.63 | 18.573 @ 30.76 / 74.996 @ 56.38 | Skipped / Skipped | +| Vulkan reference `-npl 1` | 1.498 @ 32.49 | 18.785 @ 30.59 | 255.503 @ 25.99 | +| Vulkan reference `-npl 1,4` split | 1.508 @ 32.45 / 5.931 @ 72.39 | 18.901 @ 30.31 / 75.542 @ 65.11 | 258.362 @ 25.99 / 1021.572 @ 41.53 | +| Vulkan reference `-npl 1,4 --kv-unified` | 1.492 @ 32.44 / 5.964 @ 71.82 | 18.785 @ 30.69 / 75.933 @ 55.31 | 254.584 @ 25.42 / Skipped | OpenVINO recorded-process peak RSS: 21.30-21.31 GiB. Lowest sampled system MemAvailable: 11.45 GiB. -Vulkan recorded-process peak RSS: 0.24-0.66 GiB. Lowest sampled system MemAvailable: 22.14 GiB. +Memory usage was not recorded for the historical Vulkan reference rows. Current-build memory records remain in the raw artifacts. ### Large batch: `-b / -ub = 8192 / 8192` @@ -57,9 +60,9 @@ Every completed OV one-slot and unified-KV prefill comparison improved with the Larger batches are not a universal improvement. Split four-active 8K/32K prefill is about 7% slower at 8192. Unified four-active 32K with 8192 was stopped with user approval after 2147.7 seconds of process wall time; its completed one-active row is retained. A stack snapshot mapped to the prefill call inside GPU inference, before decode timing, but did not identify the responsible kernel. Defaults are the safer choice for long multi-sequence prefill until this case is profiled. No missing prefill or decode rate is inferred from the process wall time. -The Vulkan rows do not show a useful large-batch prefill advantage. One-slot 8K prefill increases from 18.586 to 24.700 seconds (33% more), and four-active 1K split/unified prefill increases from 5.808/5.844 to 9.641/9.658 seconds (about 65-66% more). Decode is nearly unchanged. This supports keeping Vulkan defaults for this workload; kernel optimization, dispatch/layout choices and first-use preparation need profiling before assigning a cause. +The Vulkan rows do not show a useful large-batch prefill advantage. Against the old default-batch reference, one-slot 8K prefill increases from 18.785 to 24.700 seconds (32% more), and four-active 1K split/unified prefill increases from 5.931/5.964 to 9.641/9.658 seconds (about 62-63% more). The default reference and large-batch measurements use different source revisions; the original same-build measurements remain available in the campaign artifacts and support the same preliminary conclusion. Decode is nearly unchanged. This supports keeping Vulkan defaults for this workload; kernel optimization, dispatch/layout choices and first-use preparation need profiling before assigning a cause. -With default batches, OV unified four-active decode is 91.95 t/s at 1K and 71.41 t/s at 8K, versus Vulkan split's 73.90/66.32 t/s and Vulkan unified's 73.63/56.38 t/s. OV is about 24%/8% ahead of the faster Vulkan layout in these two cases. At one-slot 32K, OV decode is about 5.9% below Vulkan (24.51 versus 26.04 t/s), while OV prefill is about 7.8 times faster (32.539 versus 253.293 seconds). Fresh Vulkan 32K multi-slot comparisons were deliberately skipped; the older references below remain historical. +With default batches, OV unified four-active decode is 91.95 t/s at 1K and 71.41 t/s at 8K, versus the old Vulkan split reference's 72.39/65.11 t/s and unified reference's 71.82/55.31 t/s. OV is about 27%/10% ahead of the faster Vulkan layout in these two cases. At one-slot 32K, OV decode is about 5.7% below the old Vulkan reference (24.51 versus 25.99 t/s), while OV prefill is about 7.9 times faster (32.539 versus 255.503 seconds). At four-active 32K, OV unified decode is about 1.7% below the old Vulkan split reference (40.84 versus 41.53 t/s). Vulkan unified four-active 32K remains unmeasured in both builds. ### Profiling limits and next work diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py index 822dd169433a..54a4a765446c 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py @@ -7,6 +7,17 @@ def summarize_batch_comparison(output, report=None, finished=False): + reference = {} + if report: + text = report.read_text() + if '' in text: + historical = text.split('', 1)[1].split('### Server:', 1)[0] + for line in historical.splitlines(): + if line.startswith('| Vulkan `'): + cells = [cell.strip() for cell in line.split('|')[1:-1]] + reference[cells[0]] = cells[1:4] + if len(reference) != 3: + raise ValueError('Expected three historical Vulkan default-batch rows.') observations = {} complete = 0 selection = output / 'metadata' / 'skipped-cases.json' @@ -43,6 +54,8 @@ def summarize_batch_comparison(output, report=None, finished=False): if missing: lines[0] += ' Missing rows: ' + ', '.join(f'{count} {state.lower()}' for state, count in missing.items()) + '.' labels = {'one': '`-npl 1`', 'split': '`-npl 1,4` split', 'unified': '`-npl 1,4 --kv-unified`'} + if reference: + lines.extend([f'The default-batch Vulkan rows below use the 2026-10-23 Release build at `dd06588b1`, selected as the reference because the current-build results were similar. OV and large-batch Vulkan rows use the current campaign. This displayed comparison spans source revisions; the {complete} measured campaign rows and their original values remain in the raw artifacts. Historical reference rows do not increase the campaign completion count.', '']) for batch, settings in [('default', '2048 / 512'), ('large', '8192 / 8192')]: lines.extend([f'### {batch.capitalize()} batch: `-b / -ub = {settings}`', '', '| Backend/configuration | 1K prompt | 8K prompt | 32K prompt |', @@ -55,9 +68,15 @@ def summarize_batch_comparison(output, report=None, finished=False): cells.append(' / '.join(f'{rows[pl]["t_pp"]:.3f} @ {rows[pl]["speed_tg"]:.2f}' if pl in rows else state for pl in ((1,) if layout == 'one' else (1, 4)))) - lines.append(f'| {"OV fused" if backend == "openvino" else "Vulkan"} {labels[layout]} | ' + ' | '.join(cells) + ' |') + if reference and backend == 'vulkan' and batch == 'default': + cells = reference[f'Vulkan {labels[layout]}'] + backend_label = 'OV fused' if backend == 'openvino' else ('Vulkan reference' if reference and batch == 'default' else 'Vulkan') + lines.append(f'| {backend_label} {labels[layout]} | ' + ' | '.join(cells) + ' |') lines.append('') for backend in ('openvino', 'vulkan'): + if reference and backend == 'vulkan' and batch == 'default': + lines.extend(['Memory usage was not recorded for the historical Vulkan reference rows. Current-build memory records remain in the raw artifacts.', '']) + continue results = [result for (name, size, _, _), (_, result, _) in observations.items() if name == backend and size == batch and result] if results: From f9b648a52b9a2af03028c7b1ac5a40984e0cb5d7 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 07:38:05 +0100 Subject: [PATCH 54/65] server-bench: use an integer histogram bin count Assisted-by: Codex --- 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 0d9cfdb62f2d..a96c595d9b9f 100755 --- a/scripts/server-bench.py +++ b/scripts/server-bench.py @@ -287,7 +287,7 @@ def benchmark( plt.ylabel("Time to first token [ms]") plt.savefig("prompt_time.png", dpi=240) - bin_max = np.ceil(token_t_last) + 1 + bin_max = int(np.ceil(token_t_last)) + 1 plt.figure() plt.hist(token_t, np.linspace(0, bin_max, bin_max, endpoint=False).tolist()) plt.xlim(0, bin_max + 1) From 88c46eef8cc2c24000582eb9ba922b9bed5b875f Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 08:20:01 +0100 Subject: [PATCH 55/65] benchmarks: summarize current OV unified MMLU timings Assisted-by: Codex --- .../benchmarks/qwen36_ud_inplace_summary.py | 72 +++++++++++++++++++ .../dev_doc/benchmarks/qwen36_ud_mmlu.py | 6 ++ 2 files changed, 78 insertions(+) diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py index 54a4a765446c..61bb3c1b691f 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py @@ -4,6 +4,74 @@ import json from pathlib import Path import re +import statistics + + +def summarize_mmlu(output, report=None): + rows = [] + for mode in ('off', 'mtp'): + for concurrency in (1, 4): + name = f'ov-unified-{mode}-c{concurrency}' + directory = output / name + if not (directory / 'complete.json').exists(): + continue + responses = [json.loads(path.read_text()) for path in sorted((directory / 'responses').glob('request-*.json'))] + assert len(responses) == 8 + assert all(response['timings']['predicted_n'] == 512 for response in responses) + assert all(len(response['token_arrival_times']) == 512 for response in responses) + log = (output / f'{name}.log').read_text() + duration_match = re.search(r'Benchmark duration:\s+([\d.]+)', log) + if duration_match is None: + raise ValueError(f'Missing benchmark duration for {name}.') + duration = float(duration_match.group(1)) + assert duration > 0 + drafted = sum(response['timings'].get('draft_n', 0) for response in responses) + accepted = sum(response['timings'].get('draft_n_accepted', 0) for response in responses) + assert mode != 'mtp' or all(response['timings'].get('draft_n', 0) > 0 for response in responses) + ttfts = [response['token_arrival_times'][0] - response['submitted_at'] for response in responses] + rows.append(dict(mode=mode, concurrency=concurrency, requests=len(responses), + prompt_tokens=[response['timings']['prompt_n'] for response in responses], + ttft=statistics.mean(ttfts), ttft_median=statistics.median(ttfts), ttft_max=max(ttfts), + decode_tps=statistics.mean(response['timings']['predicted_per_second'] for response in responses), + duration=duration, end_to_end_tps=4096 / duration, + drafted=drafted, accepted=accepted)) + (output / 'server-summary.json').write_text(json.dumps(rows, indent=2) + '\n') + lookup = {(row['mode'], row['concurrency']): row for row in rows} + lines = [f'Completed {len(rows)}/4 current OV unified-KV MMLU cases.', '', + 'The target UD model uses the current fused in-place GPU backend, `q4_asym64_all`, native softplus, `ENABLE_KV_4D=1`, enabled KV slicing and compiled-model cache-only loading. Every server has `-np 4 -c 524288`, unified KV and default `-b 2048 -ub 512`; columns distinguish client concurrency from server slot count. MTP uses two draft tokens.', '', + 'Each case sends the same first eight local MMLU question texts with the native chat template, greedy sampling, `ignore_eos=true`, `cache_prompt=false`, and exactly 512 generated tokens per request. This is a throughput sample using natural text, not an MMLU accuracy evaluation.', '', + '| MTP | Requests in flight | TTFT mean / median (s) | Decode t/s per request, excludes prefill | End-to-end aggregate t/s, includes prefill | Draft accepted / generated |', + '|---|---:|---:|---:|---:|---:|'] + for mode in ('off', 'mtp'): + for concurrency in (1, 4): + row = lookup.get((mode, concurrency)) + values = [f'{row["ttft"]:.3f} / {row["ttft_median"]:.3f}', f'{row["decode_tps"]:.2f}', f'{row["end_to_end_tps"]:.2f}', + f'{row["accepted"]}/{row["drafted"]} ({row["accepted"] / row["drafted"]:.1%})' if row['drafted'] else '-'] if row else ['Pending'] * 4 + lines.append(f'| {"On" if mode == "mtp" else "Off"} | {concurrency} | ' + ' | '.join(values) + ' |') + lines.extend(['', 'TTFT is measured from client submission to the first counted token arrival. Decode is the mean native server-reported rate per request; four-request values are per request, not aggregate. End-to-end throughput is 4096 generated tokens divided by the harness wall duration, including prefill and scheduling. That duration is printed to 0.01-second precision. Cache preparation and server startup are excluded. First-use compiled-graph import and runtime preparation during requests are included; no request warmup precedes the eight measured questions. TTFT shows both mean and median to expose outliers. Draft acceptance uses native timing counters. Streaming may group buffered tokens at the same observed arrival time.', '']) + if rows: + lengths = rows[0]['prompt_tokens'] + assert all(row['prompt_tokens'] == lengths for row in rows) + lines.extend([f'Templated prompt lengths: {min(lengths)}-{max(lengths)} tokens, mean {statistics.mean(lengths):.2f}.', '']) + if len(rows) == 4: + lines.extend(['Native decode comparison, mean tokens/s per request:', '', + '| Requests in flight | MTP off -> on | Change |', + '|---|---:|---:|']) + for concurrency in (1, 4): + before = lookup[('off', concurrency)]['decode_tps'] + after = lookup[('mtp', concurrency)]['decode_tps'] + lines.append(f'| {concurrency} | {before:.2f} -> {after:.2f} | {after / before - 1:+.1%} |') + lines.append('') + lines.extend([f'Raw commands, provenance, logs, response timings and stream arrivals: `{output}`.', '']) + section = '\n'.join(lines) + (output / 'server-matrix.md').write_text(section + '\n') + if report: + text, count = re.subn(r'(?s)(\n).*?()', + lambda match: match[1] + section + '\n' + match[2], report.read_text()) + if count != 1: + raise ValueError('Expected one current-MMLU marker pair in the report.') + report.write_text(text) + print(f'Updated current MMLU server table: {len(rows)}/4 cases.', flush=True) def summarize_batch_comparison(output, report=None, finished=False): @@ -153,9 +221,13 @@ def main(): parser.add_argument('--output', required=True, type=Path) parser.add_argument('--report', type=Path) parser.add_argument('--finished', action='store_true') + parser.add_argument('--mmlu', action='store_true', help='Summarize current OV unified-KV MMLU server cases.') parser.add_argument('--batch-comparison', action='store_true', help='Summarize the matched default/large OV and Vulkan campaign.') parser.add_argument('--default-continuation', action='store_true', help='Summarize the four archived default-batch OV unified-KV 32K continuation rows.') args = parser.parse_args() + if args.mmlu: + summarize_mmlu(args.output, args.report) + return if args.batch_comparison: summarize_batch_comparison(args.output, args.report, args.finished) return diff --git a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py index ba16ccf136b4..dda8713f2563 100644 --- a/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py +++ b/ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py @@ -66,6 +66,7 @@ def reject_missing_signature(): return server except BaseException: if 'server' in locals(): + print('Server exit status:', server['process'].poll(), flush=True) server['process'].terminate() server['process'].wait() raise @@ -95,9 +96,12 @@ def reject_missing_signature(): 'GGML_OPENVINO_DEVICE': 'GPU', 'GGML_OPENVINO_NATIVE_SOFTPLUS': '1', 'GGML_OPENVINO_REQUANT_KQUANT': 'q4_asym64_all', + 'GGML_OPENVINO_ENABLE_KV_4D': '1', 'GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR': os.environ.get('UD_COMPILED_CACHE', str(root / 'tmp/mtp-regression-20261022/rotation-cache')), 'GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY': os.environ.get('UD_CACHE_ONLY', '1'), }) + if os.environ.get('UD_SPILL_DIR'): + os.environ['GGML_OPENVINO_SPILL_DIR'] = os.environ['UD_SPILL_DIR'] else: binary = Path(os.environ.get('UD_VULKAN_BIN_DIR', str(root / 'build/vulkan/bin'))) / 'llama-server' if mode == 'mtp': @@ -124,6 +128,8 @@ def reject_missing_signature(): assert all(r['timings']['predicted_n'] == n_predict for r in responses) assert all(r['events'][-1].get('stop') and r['events'][-1]['tokens_predicted'] == n_predict for r in responses) assert all(len(r['token_arrival_times']) == n_predict for r in responses) +if mode == 'mtp': + assert all(r['timings'].get('draft_n', 0) > 0 for r in responses), 'MTP must draft tokens for every request' server_log = (out / 'server.log').read_text() assert 'missing or incompatible compiled model' not in server_log, 'Missing draft signatures invalidate MTP timing' assert 'returned -3' not in server_log, 'Draft computation failed' From 7a3c18b7579ca0434e56d34259841f449026133b Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 08:20:01 +0100 Subject: [PATCH 56/65] docs: record cache-only unified KV MMLU results Assisted-by: Codex --- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 91 ++++++++++++++++++- 1 file changed, 88 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index 5f641f6202c9..4a642882c5d9 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -54,7 +54,92 @@ Raw artifacts: `/home/zijun/llama.cpp/tmp/batch-size-matrix-20261028`. Source pa -### Interpretation +## MMLU llama-server: current OV unified KV, fresh servers (2026-10-28) + + +Completed 4/4 current OV unified-KV MMLU cases. + +The target UD model uses the current fused in-place GPU backend, `q4_asym64_all`, native softplus, `ENABLE_KV_4D=1`, enabled KV slicing and compiled-model cache-only loading. Every server has `-np 4 -c 524288`, unified KV and default `-b 2048 -ub 512`; columns distinguish client concurrency from server slot count. MTP uses two draft tokens. + +Each case sends the same first eight local MMLU question texts with the native chat template, greedy sampling, `ignore_eos=true`, `cache_prompt=false`, and exactly 512 generated tokens per request. This is a throughput sample using natural text, not an MMLU accuracy evaluation. + +| MTP | Requests in flight | TTFT mean / median (s) | Decode t/s per request, excludes prefill | End-to-end aggregate t/s, includes prefill | Draft accepted / generated | +|---|---:|---:|---:|---:|---:| +| Off | 1 | 0.555 / 0.471 | 37.22 | 35.83 | - | +| Off | 4 | 1.800 / 1.781 | 21.58 | 80.36 | - | +| On | 1 | 10.249 / 0.667 | 48.62 | 24.61 | 2626/2913 (90.1%) | +| On | 4 | 57.373 / 57.412 | 22.79 | 25.40 | 2619/2935 (89.2%) | + +TTFT is measured from client submission to the first counted token arrival. Decode is the mean native server-reported rate per request; four-request values are per request, not aggregate. End-to-end throughput is 4096 generated tokens divided by the harness wall duration, including prefill and scheduling. That duration is printed to 0.01-second precision. Cache preparation and server startup are excluded. First-use compiled-graph import and runtime preparation during requests are included; no request warmup precedes the eight measured questions. TTFT shows both mean and median to expose outliers. Draft acceptance uses native timing counters. Streaming may group buffered tokens at the same observed arrival time. + +Templated prompt lengths: 35-73 tokens, mean 53.25. + +Native decode comparison, mean tokens/s per request: + +| Requests in flight | MTP off -> on | Change | +|---|---:|---:| +| 1 | 37.22 -> 48.62 | +30.6% | +| 4 | 21.58 -> 22.79 | +5.6% | + +Raw commands, provenance, logs, response timings and stream arrivals: `/home/zijun/llama.cpp/tmp/mmlu-inplace-20261028`. + + + +MTP improves the mean native decode rate by 31% for one request and 6% for four requests in this sample. Acceptance is about 90% in both cases. These native rates exclude each request's prompt evaluation, but still include work and scheduling delays during generation; they are not isolated kernel timings or fully warmed serving rates. + +The MTP end-to-end rates are lower because first-use graph loading dominates these short fresh-server campaigns. In the one-request run, question 1 has 77.291 seconds of native prompt evaluation, compared with 0.423-1.015 seconds for the other seven questions. In the four-request run, the first four questions each report about 110.689 seconds of prompt evaluation; the last four report 0.931-1.353 seconds. The logs show compiled-model cache hits and no compilation or missing-cache errors. Importing a cached graph and preparing it on the GPU still takes time, and some draft graph imports occur during generation when the active subset changes. The precise split between disk reading, runtime import, GPU weight preparation and memory pressure was not profiled. Cache-only loading removes weight requantization and graph compilation, not all first-use costs. + +No first-use requests are removed from the primary table. A serving-throughput follow-up should warm the required graph variants inside the same server process before starting timed requests; its warmed TTFT/end-to-end figures must be reported separately. These results establish current functional throughput with the full context allocation, but do not establish the steady four-request MTP gain relative to the earlier rotation implementation. The historical Vulkan server table below retains its original measurements and is not a matched warmed comparison with this fresh-server campaign. + +### Reproduce the MMLU server runs + +Run from `/home/zijun/llama.cpp-inplace-perf` with the local Python environment that includes the server-bench dependencies and PyArrow. The wrapper imports `scripts/server-bench.py`, substitutes the local MMLU parquet reader, and keeps the server at four slots while changing client concurrency. This avoids the raw script's coupling between slot count and request concurrency. The recorded inference sources are llama.cpp fused-convolution cleanup `da95d1b1c` plus sampler fixes `c1ae62002`, and OpenVINO `9299cc3d78`. The harness started at `2803132ec`; the plotting fix is `f9b648a52`. Per-case checkout commits, the harness source patch and binary SHA-256 are retained in the artifacts. + +```sh +export UD_BENCH_DIR=/home/zijun/llama.cpp/tmp/mmlu-inplace-20261028 +export UD_MMLU_PARQUET=/home/zijun/llama.cpp/tmp/mmlu-dataset/all/test-00000-of-00001.parquet +export UD_COMPILED_CACHE=/home/zijun/llama.cpp/tmp/batch-size-matrix-20261028/model-cache +export UD_FORCE_GPU=1 +export UD_LOG_VERBOSITY=4 +export UD_OPENVINO_COMMIT=9299cc3d78 + +for mode in off mtp; do + for concurrency in 1 4; do + /home/zijun/venv/bin/python \ + ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py \ + ov unified "$mode" "$concurrency" \ + > "$UD_BENCH_DIR/ov-unified-$mode-c$concurrency.log" 2>&1 + done +done +``` + +The wrapper defaults to GPU `q4_asym64_all`, enabled KV slicing and 4D in-place KV fusion, unified KV, context 524288, eight questions, 512 output tokens and compiled-model cache-only mode. Full GPU offload and disabled automatic fitting preserve the requested context allocation. The server logs confirm `n_ctx=524288`, `n_batch=2048`, `n_ubatch=512` and a 10240 MiB attention KV allocation; unified slots report a 262144-token per-request model limit. These short prompts do not test that limit. Peak memory was not sampled for this server campaign. + +For a fresh compiled cache, prepare both modes before timing. Create the spill directory on real disk storage before running; disk-backed repacked weights reduce preparation RAM pressure and do not change the compiled-cache key. Each preparation uses a small context and primes all 15 nonempty subsets of the four slots; it is excluded from the reported durations. + +One shared directory contains multiple compiled graphs, rather than one blob per MTP mode. Context length is generally dynamic, but recurrent slot capacity, rollback mode, split/unified KV translation and graph input/output contracts can distinguish variants. The MTP draft graph contains GPU sampling branches with slot-specific Parameter names. For example, slot 3 uses `sampling_row_logits_seq_3_0`, while slots 0 and 2 have two separately named row inputs and two sets of top-k outputs. The current cache key distinguishes these interfaces to prevent the sampler-input lookup bug described below. Four slots have 15 nonempty active subsets, which can occur as concurrent requests finish at different times. Most additional subset variants contain the MTP layer and output head, rather than the full trunk. A single sampler interface with runtime active-row/slot lists could reduce compilation count, cache footprint and first-use latency; it needs a separate implementation and correctness review. + +MTP preparation initially stopped before all slots were covered. The subsequent cache-only attempt hit a missing fourth-slot draft graph and was discarded. A second preparation lost the server connection while entering two active slots; its log has no explicit cause, and kernel logs were unavailable, so an OOM cause is not established. Preparation with disk-backed weights subsequently completed all 15 subsets in about 13 minutes, including roughly five minutes of weight conversion. The interrupted and failed attempts are preserved separately. Every reported timing run uses cache-only mode and rejects missing graphs or draft-computation failures. + +```sh +for mode in off mtp; do + UD_CACHE_ONLY=0 UD_PRIME_SUBSETS=1 UD_TEST_CTX=8192 \ + UD_N_PROMPTS=1 UD_N_PREDICT=16 UD_RUN_LABEL="prime-unified-$mode" \ + UD_SPILL_DIR=/home/zijun/llama.cpp/tmp/ov_spill \ + /home/zijun/venv/bin/python \ + ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_mmlu.py \ + ov unified "$mode" 4 \ + > "$UD_BENCH_DIR/prime-unified-$mode.log" 2>&1 +done +``` + +```sh +python3 ggml/src/ggml-openvino/dev_doc/benchmarks/qwen36_ud_inplace_summary.py \ + --output "$UD_BENCH_DIR" --mmlu \ + --report ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +``` + +## Batched-benchmark interpretation Every completed OV one-slot and unified-KV prefill comparison improved with the larger batch, including unified KV with one active sequence at 32K. The unresolved exception is 32K with four active sequences, which became extremely slow and was canceled. Single-slot prefill improves as follows: 8K drops from 7.703 to 5.147 seconds (33% less), and 32K from 32.539 to 22.989 seconds (29% less). Unified four-active prefill also improves at 1K/8K, from 3.479/30.785 to 2.402/25.233 seconds (31%/18% less). Decode rates are generally unchanged. These are single-pass observations. @@ -94,7 +179,7 @@ Unified KV with in-place attention and recurrent cache updates is the recommende - At default batch sizes, the combined upstream/backend changes raise unified four-active 32K decode from 7.72 to 40.79 aggregate t/s and reduce prefill from 1279.25 to 175.47 seconds. These improvements do not isolate in-place KV, recurrent cache handling or batch size as the sole cause. - The latest OV unified four-active 32K result is about 1.8% below the older Vulkan split reference, 41.53 t/s. The one-slot 32K OV result is about 5% below the older Vulkan one-slot reference. Vulkan unified four-active 32K remains unmeasured; source revisions and compressed weight representations differ between backends. - Separate convolution provides no consistent full-model advantage. At default-batch 32K, fused/separate four-active decode is 40.79/40.72 t/s, and fused prefill is faster in that sample. These single-pass differences do not establish a repeatable small decode speedup. -- The earlier short-prompt MMLU server campaign showed MTP improving OV unified decode from 36.47 to 51.35 t/s for one request and from 21.73 to 25.91 t/s per request with four in flight. Those server measurements used the earlier rotation implementation. The current fused-only cleanup has passed functional MTP checks, but has no new 512-token server performance campaign. +- The earlier short-prompt MMLU server campaign showed MTP improving OV unified decode from 36.47 to 51.35 t/s for one request and from 21.73 to 25.91 t/s per request with four in flight. Those server measurements used the earlier rotation implementation. The current fused-only implementation now has the four-case cache-only 512-token campaign at the top of this report: native decode is 37.22 -> 48.62 t/s for one request and 21.58 -> 22.79 t/s per request for four. First-use graph imports affect the fresh-server timings, so this does not isolate a warmed implementation-to-implementation speedup. ### Earlier mixed-batch snapshot @@ -125,7 +210,7 @@ Each entry is **prefill seconds @ aggregate decode tokens/s**. In four-slot rows Larger limits can still affect decode indirectly through reserved compute/output memory, memory pressure and runtime kernel or cache behavior. These historical samples had no controlled same-source, same-layout comparison that changed only `-b`/`-ub`; the earlier-to-later implementation improvements must not be attributed to batch size. The matched campaign at the top addresses that gap. Native GenAI supports chunked prefill, while its latency-oriented client configuration permits a much larger token budget; that does not establish the optimal llama.cpp microbatch size. -Next work: extend in-place attention KV updates to split streams, profile the remaining single-sequence long-context decode gap, optimize fused convolution memory access and output layouts, and measure MTP performance on the current implementation. Cleanup validation and the unresolved MoE-slice numerical experiment are documented below. +Next work: extend in-place attention KV updates to split streams, profile the remaining single-sequence long-context decode gap, optimize fused convolution memory access and output layouts, and separate warmed MTP serving performance from first-use graph loading. Cleanup validation and the unresolved MoE-slice numerical experiment are documented below. ## Current implementation From 8daa74cb4cc8bd1993cf5b8b83454f295436cd12 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 10:16:23 +0100 Subject: [PATCH 57/65] openvino: preserve the TopK index port in GET_ROWS Assisted-by: Codex --- ggml/src/ggml-openvino/openvino/op/get_rows.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index d439c9670250..01c060ed9913 100644 --- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp @@ -73,7 +73,7 @@ OutputVector translate_get_rows(const NodeContext & context) { if (indices_rank.get_length() > 2) { // Keep zero-token batches: GPU Squeeze-to-Reshape can treat a zero dimension as a copy marker. indices = std::make_shared( - indices, get_dimensions(indices.get_node_shared_ptr(), + indices, get_dimensions(std::make_shared(indices), {int(indices_rank.get_length() - 2), int(indices_rank.get_length() - 1)}), false); } if (row_offset != 0) { From 71c0bbc4d4377247d9bf7ae91d038dc293310d4c Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 28 Oct 2026 10:16:34 +0100 Subject: [PATCH 58/65] openvino: reuse the MTP sampling model across active slots Keep pure top-k branches and their output names stable, pack runtime sampling rows into one input, and bind inactive results to private buffers. Add four-slot cache-only reuse coverage and document UD server validation. Assisted-by: Codex --- ggml/src/ggml-openvino/README.md | 10 ++- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 50 +++++++++++- ggml/src/ggml-openvino/ggml-decoder.cpp | 19 +++-- ggml/src/ggml-openvino/ggml-decoder.h | 6 ++ .../openvino/translate_session.cpp | 17 ++++ ggml/src/ggml-openvino/utils.cpp | 79 ++++++++++++++++--- ggml/src/ggml-openvino/utils.h | 2 +- tests/test-backend-sampler.cpp | 61 ++++++++++---- 8 files changed, 206 insertions(+), 38 deletions(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 0cf161c20a37..655107473c5c 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -15,7 +15,7 @@ Rotation banks and the older three-op native path are removed. The convolution Update op always takes depthwise weights and produces convolution and the updated cache; the separate history/QKV mode is removed. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary GGML decomposition. -Rebuild both repos and regenerate compiled-model blobs for translation revision 12. +Rebuild both repos for these native ops. The current backend translation revision is 13; regenerate compiled-model blobs once without cache-only mode. Set `GGML_OPENVINO_ENABLE_KV_4D=1` to enable the upstream stateless in-place attention KV update pattern where eligible. It binds full-capacity cache tensors @@ -66,6 +66,14 @@ Cache-only mode uses the settings provided by the current process. Keep these va A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode. +## MTP sampling and active slots + +Qwen3.5/Qwen3.6 MTP uses a pure top-k backend sampler. Dynamic stateless execution retains its sampling branches for every configured slot and output row, including inactive branches. One packed `sampling_rows` input selects logits rows at runtime. Graph node names and candidate-output ports stay fixed, so changing the active subset of four slots reuses the same compiled draft model instead of creating up to 15 variants. + +Active candidate IDs and scores are written to the normal GGML outputs. Inactive branches read row 0 (the padding row when there are no logits) and write to private scratch tensors (device USM on GPU), without changing sampler state or touching inactive GGML buffers. The top-k computations remain separate per branch; this trades some extra sampling work for a stable graph interface. Other sampler chains retain their existing branch-selection behavior. + +This is one draft model per compatible graph configuration, not one compiled blob for the whole server. The trunk and other graph stages still have their own entries. Different sampler configurations, recurrent capacities, rollback modes or incompatible KV layouts can require additional models. Cache-only mode still requires initial preparation; changing just the active subset no longer requires exhaustive subset priming. See the [sampling validation](dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md#stable-mtp-sampling-graph-2026-10-28) for the cache-only reuse tests. + The generic recurrent-cache translation invalidates blobs made with the former single-slot shortcuts. Run once without `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` to populate compatible entries before enabling cache-only mode again. ## Restrictions diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md index 4a642882c5d9..131793154e82 100644 --- a/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md +++ b/ggml/src/ggml-openvino/dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md @@ -54,7 +54,51 @@ Raw artifacts: `/home/zijun/llama.cpp/tmp/batch-size-matrix-20261028`. Source pa -## MMLU llama-server: current OV unified KV, fresh servers (2026-10-28) +## Stable MTP sampling graph (2026-10-28) + +Dynamic stateless translation now keeps all pure top-k sampling branches used by Qwen3.5/Qwen3.6 MTP. Their node names and candidate-output ports remain fixed when active slots change. A single packed `sampling_rows` Parameter selects rows at runtime; inactive results use private scratch tensors, with device USM on GPU. This preserves the existing GGML sampling graph and does not add or modify any OpenVINO native op. Other sampler chains continue to respect their selected branches. + +The top-k computations are still separate per configured branch, including inactive branches. This avoids compiling a model for each active subset but does not yet combine top-k computations into one batched operation. The trunk, draft and any genuinely different graph stages still have distinct compiled models. Translation revision 13 invalidates previous blobs; prepare a compatible cache once without cache-only mode. + +Validation on Qwen3.5-0.8B-F16: + +- OpenVINO CPU and GPU pass changing output-row counts and a no-logits batch. +- GPU passes recurrent rollback and hidden-state output with rollback. +- CPU passes the existing multi-output distribution transaction test, covering an unaffected stateful sampling chain. +- A fresh GPU cache is primed with only slot 3 active. A new process in cache-only mode passes all 15 nonempty four-slot subsets, with both one and two output rows per active sequence. All 97 candidate rows match CPU top-k selection applied to a raw-logit reference context on the same backend, allowing the existing f16 boundary tolerance. +- The cache contains two blobs: one sampling model and one raw-logit reference model. No additional models are compiled for the subset sweep. This tests candidate selection and cache reuse, not full-model numerical equivalence between CPU and GPU. + +Target UD validation also passes with GPU `q4_asym64_all`, native softplus, `ENABLE_KV_4D=1`, enabled KV slicing, `-np 4 -c 8192 --kv-unified`, default batch sizes, and two-token MTP. `--no-warmup` isolates the serving graphs from the ordinary startup probe. Fresh preparation sends one 64-token generation to slot 3 and writes exactly two blobs: the trunk and the MTP draft model. Preparation takes 5m43s, including about 5m07s of model loading and weight conversion. + +A fresh cache-only process then tests all 15 requested slot subsets with differing output lengths so batches drain, followed by eight 512-token MMLU requests at each concurrency. All 49 requests complete (8,960 generated tokens); the cache still contains only the same two blobs. The first request imports the graphs and has 7.704s of native prompt evaluation; it is excluded from the timing table. The compiled models and runtime paths are warmed before timing begins. + +| Requests in flight | Native prompt evaluation, mean (s) | Decode t/s per request, excludes prefill | Draft accepted / generated | +|---|---:|---:|---:| +| 1 | 0.418 | 47.33 | 2626/2913 (90.1%) | +| 4 | 1.129 | 29.09 | 2622/2924 (89.7%) | + +These use the same eight MMLU questions and 35-73 templated prompt tokens as the earlier server campaign. All eight sequential generated texts and the total acceptance counters exactly match the earlier run. This follow-up uses direct non-streaming `/completion` requests; client TTFT was not measured. Whole-campaign aggregate throughput, including prefill and scheduling, is 45.36 t/s at concurrency 1 and 105.94 t/s at concurrency 4. These are separate metrics from the per-request decode column. + +The earlier table used fresh servers, a 524288-token total context and streaming `server-bench.py`; this follow-up uses warmed graphs and an 8192-token total context. The rates are not a controlled before/after performance comparison. The established result is one reusable MTP draft model across active subsets, with correct sampling and no subset-triggered cache misses. Different graph configurations or startup probes can still require other compiled entries. + +Reproduce the compiled reuse test after building `test-backend-sampler`: + +```sh +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_NATIVE_SOFTPLUS=1 +export GGML_OPENVINO_ENABLE_KV_4D=1 +export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/new-sampling-cache +SMALL_MODEL="$HOME/models/Qwen3.5-0.8B-GGUF/Qwen3.5-0.8B-F16.gguf" + +GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=0 \ + build/MtpOVPerf/bin/test-backend-sampler --test top_k_subsets_prime --device gpu "$SMALL_MODEL" +GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ + build/MtpOVPerf/bin/test-backend-sampler --test top_k_subsets --device gpu "$SMALL_MODEL" +``` + +Logs, cache manifests and target-server validation artifacts: `/home/zijun/llama.cpp/tmp/stable-sampling-20261028`. + +## MMLU llama-server: before stable sampling, fresh servers (2026-10-28) Completed 4/4 current OV unified-KV MMLU cases. @@ -115,9 +159,9 @@ done The wrapper defaults to GPU `q4_asym64_all`, enabled KV slicing and 4D in-place KV fusion, unified KV, context 524288, eight questions, 512 output tokens and compiled-model cache-only mode. Full GPU offload and disabled automatic fitting preserve the requested context allocation. The server logs confirm `n_ctx=524288`, `n_batch=2048`, `n_ubatch=512` and a 10240 MiB attention KV allocation; unified slots report a 262144-token per-request model limit. These short prompts do not test that limit. Peak memory was not sampled for this server campaign. -For a fresh compiled cache, prepare both modes before timing. Create the spill directory on real disk storage before running; disk-backed repacked weights reduce preparation RAM pressure and do not change the compiled-cache key. Each preparation uses a small context and primes all 15 nonempty subsets of the four slots; it is excluded from the reported durations. +The preparation below reproduces the earlier revision-12 campaign; revision 13 no longer needs exhaustive active-subset priming. For that earlier campaign, both modes were prepared before timing. Create the spill directory on real disk storage before running; disk-backed repacked weights reduce preparation RAM pressure and do not change the compiled-cache key. Each preparation uses a small context and primes all 15 nonempty subsets of the four slots; it is excluded from the reported durations. -One shared directory contains multiple compiled graphs, rather than one blob per MTP mode. Context length is generally dynamic, but recurrent slot capacity, rollback mode, split/unified KV translation and graph input/output contracts can distinguish variants. The MTP draft graph contains GPU sampling branches with slot-specific Parameter names. For example, slot 3 uses `sampling_row_logits_seq_3_0`, while slots 0 and 2 have two separately named row inputs and two sets of top-k outputs. The current cache key distinguishes these interfaces to prevent the sampler-input lookup bug described below. Four slots have 15 nonempty active subsets, which can occur as concurrent requests finish at different times. Most additional subset variants contain the MTP layer and output head, rather than the full trunk. A single sampler interface with runtime active-row/slot lists could reduce compilation count, cache footprint and first-use latency; it needs a separate implementation and correctness review. +One shared directory contains multiple compiled graphs, rather than one blob per MTP mode. Context length is generally dynamic, but recurrent slot capacity, rollback mode, split/unified KV translation and graph input/output contracts can distinguish variants. Before revision 13, the MTP draft graph contained GPU sampling branches with slot-specific Parameter names. For example, slot 3 uses `sampling_row_logits_seq_3_0`, while slots 0 and 2 have two separately named row inputs and two sets of top-k outputs. The revision-12 cache key distinguished these interfaces to prevent the sampler-input lookup bug described below. Four slots have 15 nonempty active subsets, which can occur as concurrent requests finish at different times. Most additional subset variants contain the MTP layer and output head, rather than the full trunk. Revision 13 replaces this subset-dependent interface with the stable sampling graph described above. These earlier timings are retained as measured, including their first-use imports. MTP preparation initially stopped before all slots were covered. The subsequent cache-only attempt hit a missing fourth-slot draft graph and was discarded. A second preparation lost the server connection while entering two active slots; its log has no explicit cause, and kernel logs were unavailable, so an OOM cause is not established. Preparation with disk-backed weights subsequently completed all 15 subsets in about 13 minutes, including roughly five minutes of weight conversion. The interrupted and failed attempts are preserved separately. Every reported timing run uses cache-only mode and rejects missing graphs or draft-computation failures. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index e84ffba0570e..637684449e47 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -192,10 +192,10 @@ std::string GgmlOvDecoder::get_tensor_name(const ggml_cgraph * cgraph, const ggm if (tensor == nullptr) { return ""; } - if ((tensor->flags & GGML_TENSOR_FLAG_COMPUTE) || is_kvcache(tensor, nullptr)) { + if (tensor->op != GGML_OP_NONE || is_kvcache(tensor, nullptr)) { // Hash-table slots depend on tensor addresses and differ between contexts. // Graph ordinals disambiguate duplicate names while keeping compiled-model - // ports identical for equivalent graphs in different contexts. + // ports identical for equivalent graphs in different contexts, including inactive sampling branches. const auto * node = std::find(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, tensor); if (node != cgraph->nodes + cgraph->n_nodes) { return std::string(tensor->name) + "#n" + std::to_string(node - cgraph->nodes); @@ -1135,7 +1135,8 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr compute_params.gdn_attention_rows[get_tensor_ov_name(cgraph, node)] = node->src[2]->ne[2] * node->src[2]->ne[3]; } if (is_sampling_view(node)) { - compute_params.sampling_rows[get_tensor_ov_name(cgraph, node)] = node->view_offs / node->src[0]->nb[1]; + compute_params.sampling_rows[get_tensor_ov_name(cgraph, node)] = + (node->flags & GGML_TENSOR_FLAG_COMPUTE) ? node->view_offs / node->src[0]->nb[1] : 0; } if (is_gdn_snapshot_writeback(node)) { const auto * source = node->src[0]; @@ -1570,8 +1571,13 @@ void GgmlOvDecoder::add_extra_inputs() { } } #endif - for (const auto & [node_name, row] : m_compute_params.sampling_rows) { - create_1d_input("sampling_row_" + node_name, row); + if (!m_is_static && !m_compute_params.sampling_rows.empty()) { + m_model_extra_inputs["sampling_rows"] = + {ov::element::i64, ov::Shape{m_compute_params.sampling_rows.size()}, 0, true, {}, -1}; + } else { + for (const auto & [node_name, row] : m_compute_params.sampling_rows) { + create_1d_input("sampling_row_" + node_name, row); + } } for (const auto & [node_name, rows] : m_compute_params.gdn_attention_rows) { create_1d_input("gdn_attention_rows_" + node_name, rows); @@ -1701,7 +1707,8 @@ void GgmlOvDecoder::compute_model_outputs() { if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0 && !runtime_recurrent_write) { continue; } - if (cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) { + 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) { const auto name = get_tensor_ov_name(m_cgraph, cur_node); m_model_outputs[name] = cur_node; m_model_output_names.insert(name); diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index c2b9b6db00a7..03874f7388d8 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -446,6 +446,7 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { // may read them. USM host allocations let the GPU consume them without tiny uploads. std::map runtime_input_storage; std::map runtime_input_tensors; + std::map runtime_output_scratch; bool m_is_static = false; bool m_is_stateful = false; @@ -571,6 +572,11 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { node->ne[1] == 1 && node->ne[2] == 1 && node->ne[3] == 1; } + static bool is_sampling_top_k(const ggml_tensor * node) { + return node != nullptr && node->op == GGML_OP_TOP_K && node->src[0] != nullptr && + node->src[0]->op == GGML_OP_RESHAPE && is_sampling_view(node->src[0]->src[0]); + } + bool is_direct_gdn_view(const ggml_tensor * node) const; inline static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index d87aeb21523c..fb1cc151e6ce 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -315,6 +316,22 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo (*tensor_map)[it.first] = it.second; } + if (tensor_map->count("sampling_rows")) { + // Match ComputeParams::sampling_rows ordering without one Parameter per sampling branch. + std::set names; + ggml_model_decoder->visit_subgraph([&](const std::shared_ptr & decoder, int node_idx) { + if (decoder->get_op_type(node_idx) == "GGML_OP_VIEW" && decoder->get_op_case(node_idx) == 3) { + names.insert("sampling_row_" + decoder->get_op_name(node_idx)); + } + }); + int64_t index = 0; + for (const auto & name : names) { + (*tensor_map)[name] = std::make_shared(tensor_map->at("sampling_rows"), + v0::Constant::create(element::i64, {1}, {index++}), + v0::Constant::create(element::i64, {}, {0})); + } + } + #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map); #endif diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 6a95b1d00631..f232b3e4e3ef 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -170,7 +170,7 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : ggml_openvino_is_gpu(); - uint64_t extra_cfg = 12; // Fused convolution with stable in-place caches. + uint64_t extra_cfg = 13; // Stable sampling branches with packed row controls. #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ? 0u : 1u); #else @@ -642,7 +642,12 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod } } input_tensor = cached; - if (param_name.compare(0, 11, "rs_offsets_") == 0 || param_name.compare(0, 11, "rs_windows_") == 0) { + if (param_name == "sampling_rows") { + auto * data = input_tensor.data(); + for (const auto & row : ggml_decoder->get_compute_params().sampling_rows) { + *data++ = row.second; + } + } else if (param_name.compare(0, 11, "rs_offsets_") == 0 || param_name.compare(0, 11, "rs_windows_") == 0) { const auto & controls = ggml_decoder->get_compute_params(); const auto & values = controls.recurrent_controls.at(param_name); std::copy(values.begin(), values.end(), input_tensor.data()); @@ -1622,14 +1627,30 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share continue; } auto * ggml_tensor = model_output_it->second; - if (ggml_nbytes(ggml_tensor) == 0) { - continue; - } ggml_decoder->take_last_kv_tensor_id(); // clear - auto output_tensor = create_ov_output_tensor(ggml_decoder, infer_request, i, ggml_tensor); + ov::Tensor output_tensor; + const bool inactive = (ggml_tensor->op != GGML_OP_NONE && !(ggml_tensor->flags & GGML_TENSOR_FLAG_COMPUTE)) || + ggml_nbytes(ggml_tensor) == 0; + if (inactive) { + // Inactive pure sampling branches have no scheduler allocation. Never bind a stale active output. + auto & scratch = ggml_decoder->runtime_output_scratch[ov_output_names[i]]; + const auto type = GgmlOvDecoder::get_ov_type(ggml_tensor); + const auto shape = GgmlOvDecoder::get_shape(ggml_tensor); + if (!scratch || scratch.get_element_type() != type || scratch.get_shape() != shape) { + if (ggml_openvino_is_gpu() && ggml_nbytes(ggml_tensor) > 0) { + auto context = ggml_openvino_get_remote_context()->as(); + scratch = context.create_usm_device_tensor(type, shape); + } else { + scratch = ov::Tensor(type, shape); + } + } + output_tensor = scratch; + } else { + output_tensor = create_ov_output_tensor(ggml_decoder, infer_request, i, ggml_tensor); + } uint64_t id = ggml_decoder->take_last_kv_tensor_id(); auto & binding = out_bindings[i]; - if (id == 0 && io_staging_enabled() && !ggml_openvino_buffer_is_remote(ggml_tensor) && + if (!inactive && id == 0 && io_staging_enabled() && !ggml_openvino_buffer_is_remote(ggml_tensor) && stageable_size(output_tensor)) { void * dst = output_tensor.data(); const size_t bytes = output_tensor.get_byte_size(); @@ -2356,19 +2377,53 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } } // namespace -// Nodes on the unselected branches of ggml_build_forward_select() stay in the graph but must not be -// computed. Keep them out of the OV model, or their inputs become parameters with fixed shapes. -static ggml_cgraph * get_compute_graph(ggml_cgraph * cgraph, ov_runtime_context & r_ctx) { +// Drop unselected branches except pure top-k sampling. Keeping those branches gives MTP a stable +// model interface as active slots change; inactive results use private output buffers. +static ggml_cgraph * get_compute_graph(ggml_cgraph * cgraph, ov_runtime_context & r_ctx, bool stable_sampling) { auto is_skipped = [](const ggml_tensor * node) { return node->op != GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_COMPUTE); }; if (std::none_of(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, is_skipped)) { return cgraph; } + std::unordered_set retained; + if (stable_sampling) { + auto use_count = [&](const ggml_tensor * node) { + return cgraph->use_counts[ggml_hash_find(&cgraph->visited_hash_set, node)]; + }; + for (int i = 0; i < cgraph->n_nodes; ++i) { + const auto * scores = cgraph->nodes[i]; + if (scores->op != GGML_OP_GET_ROWS || !GgmlOvDecoder::is_sampling_top_k(scores->src[1])) { + continue; + } + const auto * top_k = scores->src[1]; + const auto * flat = top_k->src[0]; + const auto * rows = scores->src[0]; + if (!rows || rows->op != GGML_OP_RESHAPE || rows->src[0] != flat || + use_count(scores) != 0 || use_count(top_k) != 1 || use_count(rows) != 1 || + use_count(flat) != 2 || use_count(flat->src[0]) != 1) { + continue; + } + // Retain only read-only top-k chains. Stateful samplers must keep their branch selection semantics. + std::vector pending = {scores}; + while (!pending.empty()) { + const auto * node = pending.back(); + pending.pop_back(); + if (!is_skipped(node) || !retained.insert(node).second) { + continue; + } + for (const auto * src : node->src) { + if (src) { + pending.push_back(src); + } + } + } + } + } auto & compute = r_ctx.compute_graphs[cgraph]; compute.nodes.clear(); std::copy_if(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, std::back_inserter(compute.nodes), - [&](const ggml_tensor * node) { return !is_skipped(node); }); + [&](const ggml_tensor * node) { return !is_skipped(node) || retained.count(node); }); compute.graph = *cgraph; compute.graph.nodes = compute.nodes.data(); compute.graph.n_nodes = (int) compute.nodes.size(); @@ -2393,7 +2448,7 @@ enum ggml_status ov_graph_compute(ggml_cgraph * cgraph, ggml_backend_t backend) GGML_ASSERT(ctx->runtime_context != nullptr); std::shared_ptr r_ctx = std::static_pointer_cast(ctx->runtime_context); std::lock_guard execution_lock(r_ctx->execution_mutex); - cgraph = get_compute_graph(cgraph, *r_ctx); + cgraph = get_compute_graph(cgraph, *r_ctx, !is_static && !r_ctx->stateful); return is_static ? ov_graph_compute_static(cgraph, r_ctx) : ov_graph_compute_dynamic(cgraph, r_ctx); } catch (const ov::Exception & e) { diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 17c591825a53..aca01b7a1162 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -19,7 +19,7 @@ // graph during inference, where the same few graphs repeat for the whole session. The list of // external input names below tells those apart more precisely, but it walks every node and every // src slot, so it is built only when GGML_OPENVINO_FULL_GRAPH_KEY is set. Sampler row names are -// always included because changing the active sequence changes those Parameters. Op tests run +// always included to distinguish sampler configurations, even when active subsets share the packed input. Op tests run // many small graphs that can share a node count and end names, and need the full key. struct graph_key { int n_nodes; diff --git a/tests/test-backend-sampler.cpp b/tests/test-backend-sampler.cpp index 5622ae6b3ae3..759dc7b9e95f 100644 --- a/tests/test-backend-sampler.cpp +++ b/tests/test-backend-sampler.cpp @@ -1137,16 +1137,19 @@ static sampler_comparison_stats compare_sampler_outputs( return result; } -static void test_backend_top_k_rows_impl(const test_params & params, uint32_t n_rs_seq, bool hidden = false) { +static void test_backend_top_k_rows_impl(const test_params & params, uint32_t n_rs_seq, bool hidden = false, int subsets = 0) { const int32_t k = 8; - llama_sampler_ptr chain0(llama_sampler_chain_init(llama_sampler_chain_default_params())); - llama_sampler_ptr chain1(llama_sampler_chain_init(llama_sampler_chain_default_params())); - llama_sampler_chain_add(chain0.get(), llama_sampler_init_top_k(k)); - llama_sampler_chain_add(chain1.get(), llama_sampler_init_top_k(k)); - std::vector configs = {{0, chain0.get()}, {1, chain1.get()}}; + const int n_seq = subsets ? 4 : 2; + std::vector chains; + std::vector configs; + for (int seq = 0; seq < n_seq; ++seq) { + chains.emplace_back(llama_sampler_chain_init(llama_sampler_chain_default_params())); + llama_sampler_chain_add(chains.back().get(), llama_sampler_init_top_k(k)); + configs.push_back({seq, chains.back().get()}); + } std::vector reference_configs; - test_context ctx(params, configs, 2, 6, 8, 3, n_rs_seq); - test_context reference(params, reference_configs, 2, 6, 8, 3); + test_context ctx(params, configs, n_seq, n_seq * 3, n_seq * 4, 3, n_rs_seq); + test_context reference(params, reference_configs, n_seq, n_seq * 3, n_seq * 4, 3); if (hidden) { llama_set_embeddings_nextn(ctx.ctx.get(), true, false); llama_set_embeddings_nextn(reference.ctx.get(), true, false); @@ -1154,18 +1157,32 @@ static void test_backend_top_k_rows_impl(const test_params & params, uint32_t n_ llama_sampler_ptr cpu_top_k(llama_sampler_init_top_k(k)); struct batch_case { - int counts[2]; + int counts[4]; bool output; }; - const batch_case cases[] = {{{2, 2}, true}, {{1, 1}, true}, {{2, 0}, false}, - {{0, 3}, true}, {{2, 1}, true}, {{1, 1}, true}, {{1, 0}, true}, - {{0, 1}, true}, {{1, 0}, true}}; - int32_t positions[2] = {0, 0}; + std::vector cases = {{{2, 2}, true}, {{1, 1}, true}, {{2, 0}, false}, + {{0, 3}, true}, {{2, 1}, true}, {{1, 1}, true}, {{1, 0}, true}, + {{0, 1}, true}, {{1, 0}, true}}; + if (subsets) { + // Prime only slot 3, then exercise every subset with one and multiple output rows. + cases = {{{0, 0, 0, 1}, true}}; + for (int mask = 1; mask <= subsets && subsets > 1; ++mask) { + for (int count : {1, 2}) { + batch_case c = {{0, 0, 0, 0}, true}; + for (int seq = 0; seq < n_seq; ++seq) { + c.counts[seq] = (mask & (1 << seq)) ? count : 0; + } + cases.push_back(c); + } + } + } + int32_t positions[4] = {0, 0, 0, 0}; int case_index = 0; for (const auto & c : cases) { + fprintf(stderr, "top_k_rows case %d: counts=%d,%d,%d,%d output=%d\n", case_index, c.counts[0], c.counts[1], c.counts[2], c.counts[3], c.output); auto make_batch = [&](llama_context * context) { common_batch batch(context); - for (llama_seq_id seq = 0; seq < 2; ++seq) { + for (llama_seq_id seq = 0; seq < n_seq; ++seq) { const int rejected = n_rs_seq > 0 && context == reference.ctx.get() ? (case_index == 4 && seq == 0 ? 1 : case_index == 3 && seq == 1 ? 2 : 0) : 0; const int count = c.counts[seq] - rejected; @@ -1230,6 +1247,10 @@ static void test_backend_top_k_rows_impl(const test_params & params, uint32_t n_ std::unordered_map selected_logits; for (const auto token : actual.candidates) { GGML_ASSERT(token >= 0 && token < ctx.n_vocab); + if (raw[token] < cutoff - tolerance) { + fprintf(stderr, "top_k_rows: case=%d row=%d token=%d raw=%.6f cutoff=%.6f\n", + case_index, i, token, raw[token], cutoff); + } GGML_ASSERT(raw[token] >= cutoff - tolerance); GGML_ASSERT(selected_logits.emplace(token, raw[token]).second); } @@ -1239,7 +1260,7 @@ static void test_backend_top_k_rows_impl(const test_params & params, uint32_t n_ // GPU f16 rounding can exchange candidates at the top-k boundary. GGML_ASSERT(compare_sampler_outputs("top_k_rows", selected_logits, actual, false, tolerance).n_mismatch == 0); } - for (int seq = 0; seq < 2; ++seq) { + for (int seq = 0; seq < n_seq; ++seq) { positions[seq] += c.counts[seq]; } if (n_rs_seq > 0 && case_index == 4) { @@ -1267,6 +1288,14 @@ static void test_backend_top_k_hidden_rollback(const test_params & params) { test_backend_top_k_rows_impl(params, 2, true); } +static void test_backend_top_k_subsets(const test_params & params) { + test_backend_top_k_rows_impl(params, 0, false, 15); +} + +static void test_backend_top_k_subsets_prime(const test_params & params) { + test_backend_top_k_rows_impl(params, 0, false, 1); +} + // Compare slot transitions against a fresh, independently replayed sequence. This catches // resets of the wrong cache row and writes that clobber inactive or copied sequences. static void test_backend_recurrent_slots(const test_params & params) { @@ -2344,6 +2373,8 @@ static const backend_test_case BACKEND_TESTS[] = { { "top_k_rows", test_backend_top_k_rows, true }, { "top_k_rollback", test_backend_top_k_rows_rollback, false }, { "top_k_hidden_rollback", test_backend_top_k_hidden_rollback, false }, + { "top_k_subsets", test_backend_top_k_subsets, false }, + { "top_k_subsets_prime", test_backend_top_k_subsets_prime, false }, { "recurrent_slots", test_backend_recurrent_slots, false }, { "recurrent_no_logits_prefill", test_backend_recurrent_no_logits_prefill, false }, }; From 67ae1b8a284de40fc1b3a8dc48ae677d05f65021 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 29 Oct 2026 04:59:37 +0100 Subject: [PATCH 59/65] openvino: expose selection flags and offsets in graph dumps Assisted-by: Codex --- ggml/src/ggml-openvino/ggml-decoder.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 637684449e47..19fd358d4a5f 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -2106,6 +2106,9 @@ void GgmlOvDecoder::dump_cgraph(const ggml_cgraph * cgraph, std::string & filena << std::setw(5) << node->nb[2] << ", " << std::setw(5) << node->nb[3] << "] " << std::right << std::setw(15) << buf_name << std::right + << " compute=" << ((node->flags & GGML_TENSOR_FLAG_COMPUTE) != 0) + << " output=" << ((node->flags & GGML_TENSOR_FLAG_OUTPUT) != 0) + << " view_offs=" << node->view_offs << "\n"; for (int i = 0; i < GGML_MAX_SRC; i++) { From c805e2a9b86fe87011e7eee689c5f9bd1ac5de12 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 29 Oct 2026 04:59:38 +0100 Subject: [PATCH 60/65] docs: consolidate Qwen OpenVINO defaults and performance evidence Keep current in-place and stable-sampling guidance, measured benchmark matrices and a concise decision history. Preserve historical Vulkan rows when regenerating the compact report. Assisted-by: Codex --- ggml/src/ggml-openvino/README.md | 6 +- .../dev_doc/MTP-SAMPLING-GRAPH.md | 45 + .../dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md | 189 --- .../OPENVINO-QWEN35-08B-PERF-RESULTS.md | 335 ----- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 404 +----- .../dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md | 1118 +---------------- .../dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md | 1109 +--------------- ggml/src/ggml-openvino/dev_doc/README.md | 14 + .../benchmarks/qwen36_ud_inplace_summary.py | 9 +- 9 files changed, 213 insertions(+), 3016 deletions(-) create mode 100644 ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md delete mode 100644 ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md delete mode 100644 ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md create mode 100644 ggml/src/ggml-openvino/dev_doc/README.md diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 655107473c5c..d101732d5f22 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -1,6 +1,6 @@ # Qwen MTP -Dynamic GPU execution supports Qwen MTP sampling and recurrent state snapshots. Build against the OpenVINO runtime and GPU plugin that provide ordinary `GatedDeltaNet` with `snapshot_count` and the two-output contract: output 0 is attention; output 1 is the final state when `snapshot_count=1`, or newest-first snapshots when it is greater than one. Snapshot entry 0 is the final state and entry i is the state after token T-i; only min(K,T) entries are valid. The initial state before the batch is not included. The backend and runtime must be rebuilt together. +The default Qwen3.5/Qwen3.6 GPU path is dynamic stateless execution with in-place fused recurrent ops and stable MTP sampling. Build against the matching OpenVINO runtime/GPU plugin with independent `RecurrentConvCacheUpdate` and `RecurrentGatedDeltaNetUpdate` ops. The native Update ops return computation results plus the full updated cache, including rollback snapshots where required. No recurrent/sampling opt-in flag is needed on supported graphs. See the [development documentation index](dev_doc/README.md) for implementation, validation, graph examples and benchmarks. Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. CPU snapshot execution, NPU execution, and forced static MTP are not supported. @@ -25,11 +25,11 @@ split multi-slot KV retains the ordinary full-cache path. This option does not change recurrent cache handling. Unified KV is recommended for multi-slot GPU execution because it enables this in-place attention update. -The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_DISABLE_KV_SLICE` unset to use live-prefix attention cache bindings where supported. The [large-context comparison](dev_doc/OPENVINO-RECURRENT-FUSION-PERF.md#large-context-attention-kv-slicing-2026-10-22) measures the benefit and documents the single-stream restriction. Earlier [performance measurements](dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md) used disabled slicing; yamini-model results remain historical references. +The current performance target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, using GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_DISABLE_KV_SLICE` unset. See [attention KV layout](dev_doc/OPENVINO-RECURRENT-CACHE.md#attention-kv-layout) for eligibility and [benchmark results](dev_doc/QWEN36-UD-MULTISLOT-BENCHMARK.md) for measured limits. `q4_asym64_all` converts Q4_K/Q5_K/Q6_K/Q8_0/Q5_1 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. `token_embd.weight` and `output.weight` retain symmetric channel-wise INT8. Q8_0/Q5_1 rows whose width is not divisible by 64 also use channel-wise INT8. This follows the primary/backup precision scheme of NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM` for these supported source types; it requantizes GGUF values rather than the original floating-point model and leaves floating-point weights unchanged. Earlier versions kept dense Q8_0 at INT8/group-32. Repopulate compiled-model caches without cache-only mode after this change; the cache fingerprint invalidates the old precision policy. -See the [recurrent-cache report](dev_doc/OPENVINO-RECURRENT-CACHE.md) for the measured baseline and proposed native cache-operation fusions. +See the [implementation guide](dev_doc/OPENVINO-RECURRENT-CACHE.md) for buffer ownership, rollback and validation. # Compiled model cache diff --git a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md new file mode 100644 index 000000000000..ac56fc2cd72b --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md @@ -0,0 +1,45 @@ +# Stable multislot MTP graph + +The captured UD draft graph contains 107 nodes regardless of which of four slots are active. It is the single MTP attention/MoE layer, not the recurrent trunk. Two speculative tokens require two consecutive draft calls, batched over active sequences. + +```text +MTP token IDs + input hidden state + | + 0-84: MTP layer and normalization, N active sequences + | + 85: logits [248320, N] + 86: PAD adds one safe row + | + +-- 87-91: slot 0 sampling + +-- 92-96: slot 1 sampling + +-- 97-101: slot 2 sampling + +-- 102-106: slot 3 sampling +``` + +Each branch contains VIEW, two Reshapes, TopK (ten candidate IDs), and GET_ROWS (their scores). Ten is the candidate count, not the speculative-token count. + +| Active slots | Sampling COMPUTE flags, slots 0-3 | Raw/current nodes | Old filtered nodes | Packed sampling_rows | +|---|---|---:|---:|---| +| 3 | `[0,0,0,1]` | 107 | 92 | `[0,0,0,0]` | +| 0,2 | `[1,0,1,0]` | 107 | 97 | `[0,0,1,0]` | +| All four | `[1,1,1,1]` | 107 | 107 | `[0,1,2,3]` | + +Old counts apply the old COMPUTE filter to the captures. Unselected nodes remain in the raw cgraph. Previously, removing them changed translated topology, slot-specific row Parameter names and output ports; even equal-sized subsets such as `{0,1}` and `{0,2}` differed. This could trigger up to 15 draft variants, with compilation/import on first use or a missing-cache error in cache-only mode. + +Now all pure top-k branches remain. Their names include stable graph ordinals even when inactive. One int64 `sampling_rows` Parameter supplies row indices at runtime. For `{0,2}`, the two logits rows belong to slots 0 and 2: + +```text +sampling_rows = [0, 0, 1, 0] +slot 0 -> row 0 -> normal candidate buffers +slot 1 -> row 0 -> private scratch, ignored +slot 2 -> row 1 -> normal candidate buffers +slot 3 -> row 0 -> private scratch, ignored +``` + +The vector is not an active mask. Host-side COMPUTE flags select normal versus scratch output destinations. PAD provides a valid row when there are no logits. Inactive outputs use device USM on GPU and do not affect sampler state or acceptance. Other sampler chains retain their selected-branch semantics. + +Only small sampling work executes for inactive slots. The MTP layer and output projection still process N active rows. Top-k is separate per branch, not yet one batched TopK. The observed draft interface has 10 inputs and 12 outputs: eight candidate ID/score outputs, hidden state, full logits and two KV Results. + +Dump shapes use GGML order `[width, rows, dim2, dim3]`; OV reverses it. `view_offs` is in bytes: one logits row occupies `248320 * 4 = 993280` bytes. Buffer labels describe GGML storage, not the device executing imported GPU operations. + +Actual full cgraphs, sampling excerpts, compiled ports and capture scripts remain under `/home/zijun/llama.cpp/tmp/mtp-graph-examples-20261029`: `draft-slots-3.txt`, `draft-slots-0-2.txt`, and `draft-slots-0-1-2-3.txt`. `WORK-NOTE.md` is the user's standalone OneNote copy. Captures used cache-only mode, four slots, context 8192 and the default two-token MTP settings. The [benchmark report](QWEN36-UD-MULTISLOT-BENCHMARK.md) contains reuse validation and measured performance. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md deleted file mode 100644 index 477b0d7110ca..000000000000 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-PLAN.md +++ /dev/null @@ -1,189 +0,0 @@ -# Qwen3.5 0.8B F16: OpenVINO GPU investigation and optimization plan - -Date: 2026-10-16. This document records the original investigation and plan. Steps 1–3 are now implemented locally; measurements and validation are recorded in [OPENVINO-QWEN35-08B-PERF-RESULTS.md](OPENVINO-QWEN35-08B-PERF-RESULTS.md). The baseline findings below describe the pre-optimization implementation. The current target has since changed to `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`, keeping GPU, `q4_asym64_all`, native softplus, and disabled KV slicing; the results report records its retest separately. - -OpenVINO GPU currently reaches **43.5–43.8 tokens/s**, compared with **57.91 tokens/s** for a new Vulkan Release build from the same working tree. The next priority is eliminating runtime shape synchronization: an ordinary single-token inference calls `clFinish` **164 times**, of which **163 are shape-inference synchronizations: 108 Reshapes and 55 Slices**. Cache allocations and bindings already use device USM. Native cache fusion helps, but leaves this synchronization problem and matrix-state writeback/layout work intact. - -The user's 18.99 tokens/s OpenVINO example selected **CPU**, so it is not the GPU baseline. The user's expectation of further improvement is reasonable; reaching a particular throughput on the 35B model still needs measurement after the small-model changes. - -## Reproducible baseline - -Hardware: Intel Arc B390 integrated GPU / Core Ultra X7 358H. Model: `~/models/Qwen3.5-0.8B-GGUF/Qwen3.5-0.8B-F16.gguf`. This dense, unquantized model removes MoE and requantization from the comparison. - -- OpenVINO frontend: Release `build/MtpOVPerf`, llama.cpp HEAD `73f61e1cb`, with the existing uncommitted native recurrent-cache implementation. -- Runtime: `/home/zijun/openvino-build-mtp`, OpenVINO HEAD `21cacac33d`, with the existing native-op changes. -- Matched Vulkan: new Release `build/VulkanPerf08`, same current llama.cpp working tree, Vulkan SDK 1.4.357.1. The existing Debug `build/vulkan` was left unchanged. -- GPU workloads ran serially. No stateful tests or execution. No backend implementation files changed during this investigation. -- Environment is scrubbed of inherited OpenVINO/Vulkan controls before each run. Requantization and compiled-model disk caching are unset. Throughput excludes initial loading/compilation through llama-bench's warmup. - -```sh -GGML_OPENVINO_DEVICE=GPU \ -GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ -GGML_OPENVINO_DISABLE_KV_SLICE=1 \ -build/MtpOVPerf/bin/llama-bench \ - -m "$HOME/models/Qwen3.5-0.8B-GGUF/Qwen3.5-0.8B-F16.gguf" \ - -p 0 -n 128 -r 3 -``` - -| Run | tokens/s, benchmark mean ± SD | Approx. ms/token | -| --- | ---: | ---: | -| OV GPU, native cache ops | 43.76 ± 0.10 | 22.85 | -| OV GPU, independent repeat | 43.51 ± 0.11 | 22.98 | -| OV GPU, `GGML_OPENVINO_DISABLE_RECURRENT_CACHE=1` | 39.14 ± 0.12 | 25.55 | -| OV GPU, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS=1` | 43.26 ± 0.11 | 23.12 | -| Existing Vulkan Debug, older build | 55.69 ± 0.25 | 17.96 | -| Matched Vulkan Release | 57.91 ± 0.17 | 17.27 | - -Native fusion saves approximately **2.70 ms/token**, or 11.8% higher throughput, on this model. Approximately **5.6–5.7 ms/token** remains to match Vulkan Release. Disabling remote outputs changes latency by only about 0.26 ms relative to the first native run; this is a small, order-sensitive control, not a complete measurement of memory-copy cost. - -Timing instrumentation is separate from these baselines. One profiling-level-1 run measured 41.24 tokens/s; a later verbose level-1 run measured 43.57. Its warmed medians were 0.100 ms for graph decoding, 22.637 ms for the inference phase including bindings, and 22.193 ms inside `InferRequest::infer`. Most latency is inside the runtime, rather than llama.cpp graph construction or tensor binding. Do not use the noisier instrumented result as a new baseline. - -## Controlled token-count and snapshot comparison - -The existing `tmp/mtp-gap-20261014/batch-bench.cpp` harness was reused, including a newly linked Vulkan Release executable. Each case uses a 128-token prefix, eight warmups, 16 measured calls, context 4096, one active sequence, hidden output enabled, and all input rows requesting logits. Means below are milliseconds per complete synchronized decode call. - -| Case | OV GPU | Vulkan Release | -| --- | ---: | ---: | -| 1 token, snapshots disabled | 23.49 | 17.07 | -| 3 tokens, snapshots disabled | 24.44 | 18.40 | -| 1 token, two rollback positions configured | 29.84 | 17.85 | -| 3 tokens, two rollback positions configured | 31.82 | 19.32 | -| 3 tokens, reject two after each call | 32.01 | 18.59 | - -On OV, ordinary T1→T3 adds only **0.95 ms**. Enabling snapshot storage adds **7.38 ms** to T3. Actual rejection adds approximately **0.19 ms** in this run. The slightly lower Vulkan reject-case timing is not evidence that rejection accelerates inference; the cases advance context length differently and are separate short measurements. - -This isolates a substantial generic/snapshot-path penalty without any MoE or quantization. These are target-call measurements, not an MTP throughput prediction: draft generation, catch-up, acceptance, and host sampling must be measured separately on the target model. - -## What the runtime actually does - -### USM and model I/O - -A scratch `LD_PRELOAD` probe inspects bound tensors and intercepts OpenCL submissions and USM copies. A warmed native T1 call has: - -| Item | Count / size | -| --- | ---: | -| OV Parameters | 184 | -| OV Results | 51 | -| Cache inputs, all USM | 48 | -| Cache outputs, all USM | 48 | -| Host inputs | 136, mostly scalar metadata | -| Cache-r allocation represented at I/O | 18 × 73,728 bytes | -| Cache-s allocation represented at I/O | 18 × 1,048,576 bytes | -| Cache-k/cache-v allocation represented at I/O | 12 × 262,144 bytes | -| Host→device USM copies per inference | 136 calls, **1,588 bytes total** | -| USM-host→ordinary-host output copies | 3 calls, **1,001,472 bytes total** | -| OpenCL NDRange submissions | **789** | -| `clFinish` calls | **164** | - -The three host outputs are logits (993,280 bytes), `h_nextn` (4,096 bytes), and `result_norm` (4,096 bytes). The cache byte counts are bound capacities, not host-transfer volumes. No full recurrent-cache host round trip appears in the intercepted copies. Device kernels still read, convert, transpose, and write cache data. - -Code confirms the binding behavior: `ggml-openvino.cpp` allocates GPU `cache_*` buffers with `create_usm_device_tensor`; `ggml-openvino-extra.cpp` wraps their pointers as USMTensors; `utils.cpp` reuses them for both inputs and outputs. There is already **one final Result per cache per layer**. Reducing duplicate cache Results is therefore not the immediate opportunity. - -The small host inputs are different: `get_ov_input_tensor()` allocates a fresh tensor for each extra scalar on every invocation. The runtime uploads them individually. Per-layer `rs_slot_begin_*` and `rs_src_begin_*` parameters are combined into small device-side Concat/Reshape expressions even for the native cache ops. - -### Synchronization and shape inference - -The probe measures roughly **12.9–13.3 ms spent inside `clFinish`** per warmed call, with raw inference around 22.4 ms. This includes completion of useful GPU work; it is **not** 13 ms of independently removable overhead. - -An additional GPU verbose trace (`OV_VERBOSE=4`, `OV_VERBOSE_COLOR=0`) confirms three consecutive calls each contain exactly: - -- **108 Reshape shape-inference synchronizations**, six per recurrent layer: QKV mixed, alpha, beta, gate, z, and final-output reshapes. -- **55 StridedSlice shape-inference synchronizations**. -- The remaining finish is inference completion; the probe records a separate final event wait as well. - -`primitive_inst::update_shape()` waits for runtime value dependencies before calculating output layouts. The in-order shared OpenCL queue takes the `finish()` path. In `openvino/op/reshape.cpp`, cases 6 and 10 build shape vectors using **the tensor value** of `s_copy_active_slot_len`. This introduces synchronization even though the active sequence count is already known by the frontend on every call. `recurrent_cache_fusion.cpp` also slices the row map using that value; other active-state views and cache writeback slices retain similar dependencies. - -This explains why fusing many GGML nodes does not eliminate the gap: arithmetic fusion does not automatically remove the surrounding shape computations or their queue drains. Removing waits blindly would be incorrect; their data dependencies must first be eliminated or satisfied safely. - -### Device execution profile - -Level-2 profiling substantially changes synchronization/timing (the short OV run reports only 17.34 tokens/s). Use it to locate kernels, not as an end-to-end benchmark. A warmed native profile has 1,180 entries marked EXECUTED, versus 1,777 with native cache fusion disabled. These entries include CPU/shape nodes and are not equivalent to kernel dispatches. - -| Profiled work | Native OV device-time sum | -| --- | ---: | -| FullyConnected, 187 nodes | 14.697 ms | -| Transpose, 48 nodes | 1.032 ms | -| Convert, 180 entries | 0.377 ms | -| GatedDeltaNet, 18 | 0.274 ms | -| RecurrentStateGather, 18 | 0.246 ms | -| RecurrentConvCache, 18 | approximately 0.073 ms | -| All recorded executed entries | 17.837 ms | - -The matched Vulkan instrumented profile sums to 17.858 ms, including approximately 15.573 ms of matmul work. The huge F16 vocabulary projection alone is approximately 4.45 ms in OV and 4.41 ms in Vulkan. Different profilers change scheduling, so these sums cannot be subtracted from plain wall time to calculate an exact overhead budget. They do suggest that dense matrix computation is not the first issue to address. - -The matrix-state path still materializes gather output, transposes between GGML `[B,H,V,K]` and native GDN `[B,H,K,V]`, transposes results back, and assembles cache writeback. Snapshot routing adds more state-selection/writeback work. The current `RecurrentStateGather` also produces a complete prepared-cache copy before the final update. These are more promising fusion targets than micro-tuning the already small convolution-cache kernel. - -## Implementation plan, in order - -### 1. Remove active-count value dependencies from shapes - -**Files:** `ggml-decoder.{h,cpp}`, `utils.cpp`, `openvino/op/reshape.cpp`, `openvino/op/view.cpp`, `openvino/utils.cpp`, `openvino/recurrent_cache_fusion.cpp`. - -1. Expose a runtime active-row-map input whose **shape** is `[1,1,1,B]`, where B comes from the actual active recurrent-state view each compute. Bind the corresponding prefix of `rs_s_copy`; retain the full map separately for remainder reordering. Do not assume B=1 or equate B with configured slot capacity, total tokens, or snapshot count. -2. Derive `s_copy_active_slot_len` for shape expressions from `ShapeOf(active_rows)` through the existing shape-source mechanism. Use constant reshape patterns with `-1`/copied dimensions wherever that expresses the same shape. This targets all 108 recurrent reshape waits while preserving changing B and T. -3. Feed the native cache ops the already-shaped active map, removing their value-dependent prefix Slice. Remove redundant active-prefix slices only when the producer structurally guarantees that exact active output, for every supported B/T. -4. Inspect the executed graph to ensure the new expressions remain shape-only through GPU lowering. A frontend ShapeOf is insufficient if the plugin still makes the dependency value-driven. - -**Gate:** changing-slot/rollback correctness tests pass; the 108 identified reshape waits disappear or any surviving dependency is individually explained. Repeat uninstrumented tg128. The first performance target is **at least 50 tokens/s** (≤20 ms/token), not a promised gain. - -### 2. Pack and reuse recurrent control inputs - -**Files:** decoder runtime-parameter collection and binding, `recurrent_cache_fusion.cpp`, native op metadata interfaces if needed. - -1. Materialize reset range, remainder offsets, and convolution snapshot windows on the host into persistent, correctly shaped metadata tensors. Feed native ops directly instead of building their metadata with GPU Concats/Reshapes. -2. Share metadata across layers only when graph structure and runtime provenance guarantee equality. Never deduplicate merely because values match in the first batch. Keep per-node descriptors for genuinely different writes. -3. Use reusable USM-host storage for small host-produced controls where supported; measure against one packed device upload. Keep caches in device USM. Avoid moving shape metadata to device-only storage and forcing a readback for shape inference. -4. Reuse bindings when tensor identity, address, type, and shape are unchanged. Rebind after allocation/view/shape changes. Increment the compiled-model cache ABI/revision for any input-interface change. - -**Gate:** reduce the current 136 tiny uploads to a small number of packed controls, verify no stale metadata across reset/reorder/rejection, and record input count, upload count, and uninstrumented latency. Binding alone has only about a 0.44 ms observed budget; a larger gain must come from removing device metadata work/synchronization. - -### 3. Fuse matrix-state writeback and eliminate state-layout traffic - -**Files:** `openvino/op/cpy.cpp`, `openvino/op/gated_delta_net.cpp`, native recurrent-cache/GDN core ops, GPU primitive and kernel implementations. - -1. Add a generic native **RecurrentStateUpdate** operation, or extend the current cache operation, to combine the prepared full cache with active final states/snapshots in one kernel. Output shape equals cache shape; runtime offsets and snapshot selections affect indexing, not shape inference. Preserve inactive slots, reset-before-gather semantics, cyclic/duplicate sources, and ordered overlapping-write precedence. -2. Accept GDN's native state layout in the update kernel and transpose while writing GGML cache layout. Fold active-state gather and input-layout conversion together where possible. This avoids standalone full-state transpose intermediates and Slice/Concat/Range writeback chains. -3. If profiling still justifies it, extend GDN to consume the original cache plus active-row/reset metadata and emit active results/snapshots directly in cache-compatible layout. A complete fused gather→GDN→writeback path can avoid the prepared-cache intermediate. Keep old source storage immutable until all potentially aliasing reads finish; arbitrary multi-slot cycles forbid naive in-place writes. -4. Preserve the existing external cache precision and numerical contract. Do not trade throughput for a silent F32→F16 cache change. Compare native-on/off logits and replay behavior after fusion. - -**Gate:** remove the identified state writeback shape waits and standalone state transposes; reduce T3 snapshot overhead substantially from **7.38 ms toward ≤2 ms** on 0.8B. This is a target, subject to measurement. Retain all multislot/snapshot regressions and compiled-model export/import coverage. - -### 4. Optimize remaining dispatches based on a fresh profile - -Only after steps 1–3, reassess kernel submission and dense compute: - -- Consider fusing `RecurrentConvCache` with SSM convolution and SiLU, avoiding materialized history-plus-QKV and extra launches. Its current cache kernel is only ~0.073 ms aggregate; prioritize measured dispatch/synchronization savings, not an assumed large bandwidth saving. -- Remove unused `h_nextn`/`result_norm` host Results when the caller does not request them, while retaining the exact MTP/embedding/sampling contract. They are only 8 KiB here, so this is a secondary I/O cleanup. -- Compare remaining FP16 projection/gating kernels with Vulkan. Preserve accuracy and multi-token performance when adjusting fusions or kernel selection. -- If translated shape-only expressions still wait unnecessarily, make a narrowly justified GPU-plugin shape-dependency fix. Do not globally bypass `finish()` or change queue ordering without dependency correctness tests. - -**Gate:** aim for **≥55 tokens/s** on 0.8B, within roughly 5% of the current 57.91 t/s Vulkan Release reference. Report gains and counter changes separately for each retained patch. - -### 5. Validate generality, then measure the target model - -For every functional patch, exercise the existing recurrent-slots and hidden/rollback regressions with active subsets, nonzero-slot resets, copies/branches, inactive-state preservation, unequal rejection lengths, zero requested outputs, and changing B/T on a reused graph. For native-op changes, extend the existing f16/f32, i32/i64, dynamic/static, cycle/overlap, and export/import tests. Statefulness remains out of scope. - -After the small-model improvements: - -1. Run 0.8B `llama-server -np 4` reset/reuse/concurrent waves and a longer-context `-p 1024 -n 512 -d 0,1024` performance check. -2. Rebuild/reuse compiled caches with the new revision. For functional tests, unset requantization when supported; the previously observed 35B no-requant fusion failure may still require the target requant config. -3. Run the target Qwen3.6-35B-A3B with `q4_asym64_all`, GPU, native softplus, and KV slicing disabled. Repeat `-np 4` server checks without and with two-token MTP. -4. Repeat the established target bench, controlled T1/T3/snapshot matrix, and matched CLI/MTP traces. Report draft, catch-up, verification, acceptance, and complete generation throughput. -5. Compare against the current generic/native target baselines: **23.05 t/s non-MTP tg512**, **22.32 at depth 1024**, and **27.93 t/s MTP on the prior greeting workload**. The user's **≥30 t/s** goal is a target; small-model gains cannot simply be multiplied into the 35B result. - -Keep useful patches independently reviewable across llama.cpp and OpenVINO, with measured results and relevant files only. The existing native implementation remains uncommitted; this investigation does not create additional implementation commits. - -## Evidence and limitations - -All commands, environments, logs, profiles, and the scratch probe are under [`tmp/qwen08-perf-plan-20261016`](../../../../tmp/qwen08-perf-plan-20261016/). Useful entry points: - -- `run.py`, per-run `command.json`, and `summary.json`. -- `ov-native`, `ov-native-repeat`, `ov-unfused`, `ov-host-outputs`, `vulkan-release`: plain benchmark evidence. -- `ov-matrix`, `vulkan-matrix`: controlled target calls; `batch-vulkan` is linked to the new Release build. -- `ov-profile`, `ov-profile-unfused`, `vulkan-profile`: instrumented operation profiles. -- `probe.cpp`, `ov-probe/probe-1-io.tsv`, `ov-probe/probe-1-exec.xml`, and `ov-probe/run.log`: actual bindings, runtime graph, OpenCL call/copy counts. -- `ov-sync-trace/run.log`: `primitive_inst.cpp:481:update_shape` records proving the 108 Reshape + 55 Slice waits per inference. Do not benchmark with this verbose tracing enabled. - -The probe is investigative tooling, not production code. It counts intercepted NDRange calls and Intel USM memcpy calls, not every possible driver-internal transfer. An initial debug-input attempt failed because that helper calls `Tensor::data()` on a remote tensor; the final probe inspects remote handles safely. Early probe build/instrumentation attempts were corrected; reported probe results come from the final successful run. - -No new model-correctness claim is made from throughput tests alone. The prior native implementation's functional coverage is documented in [OPENVINO-RECURRENT-CACHE.md](OPENVINO-RECURRENT-CACHE.md); the planned changes must repeat the relevant coverage. No 35B performance rerun was performed in this investigation-only round. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md deleted file mode 100644 index acd17a4acaae..000000000000 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-QWEN35-08B-PERF-RESULTS.md +++ /dev/null @@ -1,335 +0,0 @@ -# Qwen recurrent-cache optimization results - -Original measurements: 2026-10-16; precision-policy retest: 2026-10-19. The original implementation was measured from the local changes in llama.cpp (`qwen-openvino-generic-cache`, HEAD `73f61e1cb`) and `/home/zijun/openvino` (`qwen-mtp-openvino-checkpoint`, HEAD `21cacac33d`). The matching native OpenVINO changes are committed as `9e08e52ad5` (`intel_gpu: fuse generic recurrent cache maintenance`). Builds use Release `build/MtpOVPerf` and `/home/zijun/openvino-build-mtp`. Unrelated working-tree changes were preserved. Results below exclude load/requantization/graph compilation from generation throughput. No stateful execution is involved. - - -From this retest onward, the target is `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`. GPU, `q4_asym64_all`, native softplus, and disabled KV slicing remain unchanged. The yamini-model tables below retain their original model identity; new measurements are reported separately. -## Implemented changes - -1. Added an active recurrent-row-map prefix input with dynamic length. Active sequence counts now come from its runtime shape instead of an uploaded scalar value. This preserves changing slot counts and removes all 108 recurrent Reshape shape-inference waits in the 0.8B graph. -2. Reuse per-request runtime control tensors in USM host allocations. This removes almost all tiny scalar uploads while keeping shape metadata CPU-readable. Ordinary cache buffers remain in device USM, as before. -3. Materialize convolution windows and remainder offsets as packed host controls. Metadata varies per actual graph write; it is not deduplicated by coincidentally equal first-batch values. -4. Added native `RecurrentStateUpdate`: a full-cache output with runtime active/snapshot offsets and ordered overlap handling. It replaces Slice/Concat/Range state writeback, removing the remaining 36 ordinary-decode shape-inference waits. -5. StateUpdate converts native GDN state/snapshot matrices to GGML cache layout while writing. RecurrentStateGather converts gathered matrices into native GDN layout while reading. Standalone recurrent input/output state transposes are eliminated on the structurally matched path. Original source cache reads remain immutable, including arbitrary row-map cycles and duplicates. -6. Added native-op capability probing and updated the compiled-model cache revision. Dynamic CPU, static, and released-runtime paths retain their primitive translations. Existing disk-cache blobs need regeneration. - -## 0.8B F16 results - -The same small-model command and matched Vulkan Release reference as the [investigation](OPENVINO-QWEN35-08B-PERF-PLAN.md) are used: `llama-bench -p 0 -n 128 -r 3`, GPU, native softplus, KV slicing disabled, requant unset. Changes were measured incrementally; small differences between adjacent runs are subject to run order and machine variability. - -| Stage | Generation tokens/s | -| --- | ---: | -| Initial native cache implementation | 43.76 ± 0.10 | -| Active count from row-map shape | 46.82 ± 0.05 | -| Reusable USM host scalar controls | 50.23 ± 0.07 | -| Native full-cache state update | 51.15 ± 0.15 | -| Output state transpose folded into update | 52.60 ± 0.07 | -| Packed window/remainder metadata | 52.50 ± 0.07 | -| Input state transpose folded into gather | 53.75 ± 0.08 | -| Final independent optimized repeat | **56.21 ± 0.06** | -| Matched Vulkan Release reference | 57.91 ± 0.17 | - -The final independent repeat reaches **56.21 ± 0.06 tokens/s**, **28.4%** above the initial native path and **2.9%** below Vulkan Release. An earlier final-build repeat measured 55.51 ± 0.17 tokens/s. Both meet the ≥55 tokens/s small-model target. The independent repeat ran after the target MTP process exited, with no overlapping GPU workload. - -A longer three-repeat check (`-p 1024 -n 512 -d 0,1024`) records: - -| 0.8B workload | Optimized tokens/s | -| --- | ---: | -| pp1024 | 6781.63 ± 418.28 | -| tg512 | **55.46 ± 0.07** | -| pp1024 at depth 1024 | 5330.30 ± 1286.93 | -| tg512 at depth 1024 | **53.04 ± 0.18** | - -Prefill has high variance in this short run; the decode measurements are more stable. No matched Vulkan longer-context baseline was rerun. - -The intercepted warmed ordinary-decode work changes as follows: - -| Counter | Initial native | Optimized | -| --- | ---: | ---: | -| Model Parameters | 184 | 130 | -| Model Results | 51 | 51 | -| Remote USM cache inputs/outputs | 48 / 48 | 48 / 48 | -| Tiny host→device copies | 136, 1588 bytes | 8, 560 bytes | -| Host output copies | 3, 1001472 bytes | 3, 1001472 bytes | -| `clFinish` calls | 164 | 1 | -| Kernel submissions | 789 | 606 | -| Profile entries marked EXECUTED | 1180 | 945 | - -The sole remaining finish is inference completion. The prior 163 queue drains were 108 Reshapes and 55 Slices; deriving shapes and native writeback removes them instead of bypassing synchronization. Profiling-level-2 device times are diagnostic only: the optimized trace records 16.982 ms total, of which 14.835 ms (87.4%) is FullyConnected. Profiling changes scheduling and is not the throughput baseline. - -The existing controlled target-call harness uses a 128-token prefix, 8 warmups, 16 measured calls, hidden states enabled, and all rows requesting logits: - -| Case | Initial OV ms/call | Optimized OV ms/call | Vulkan reference ms/call | -| --- | ---: | ---: | ---: | -| T1, no snapshots | 23.49 | 19.15 | 17.07 | -| T3, no snapshots | 24.44 | 19.93 | 18.40 | -| T1, rollback storage enabled | 29.84 | 22.28 | 17.85 | -| T3, rollback storage enabled | 31.82 | 24.46 | 19.32 | -| T3, reject two | 32.01 | 24.59 | 18.59 | - -Snapshot storage still adds about 4.53 ms to the optimized T3 call, compared with 7.38 ms initially. The ≤2 ms snapshot-overhead target is not met. Rejection itself remains small. Single-token throughput and snapshot verification are different performance cases. - -## Current target: Qwen3.6 UD-Q4_K_M retest - -Model: `~/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf` (22,663,387,424 bytes; 21.10 GiB). Same architecture metadata and one `nextn_predict_layers` MTP layer as the previous GGUF. The build and runtime are unchanged from the optimized measurements above. GPU workloads run serially; compiled-model disk caching and stateful execution are unset. - -```sh -GGML_OPENVINO_DEVICE=GPU \ -GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ -GGML_OPENVINO_DISABLE_KV_SLICE=1 \ -GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ -build/MtpOVPerf/bin/llama-bench \ - -m "$HOME/models/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf" \ - -p 1024 -n 512 -d 0,1024 -``` - -Five repetitions; mean ± benchmark standard deviation: - -| Workload | Previous optimized yamini tokens/s | Current UD tokens/s | -| --- | ---: | ---: | -| pp1024 | 1125.19 ± 8.25 | **1127.99 ± 7.25** | -| tg512 | 29.91 ± 0.47 | **27.41 ± 0.07** | -| pp1024 at depth 1024 | 1074.27 ± 33.48 | **1081.64 ± 19.96** | -| tg512 at depth 1024 | 28.47 ± 0.44 | **26.19 ± 0.04** | - -UD decode is 8.4% lower at depth zero and 8.0% lower at depth 1024. This compares different GGUF quantizations under the same optimized backend; it is not a before/after optimization measurement on UD. No pre-optimization or Vulkan UD baseline has been measured. - -The source quantization mix differs substantially: non-expert/non-MTP weights change from 95 Q6_K, 53 Q4_K, 94 Q8_0 and 10 Q5_K tensors to 1 Q6_K and 251 Q8_0 tensors. Their original GGUF payload grows from 1.87 GB to 2.56 GB; these are source sizes, not converted runtime sizes. Trunk MoE expert weights change from 20 Q6_K/100 Q4_K to 3 Q6_K/80 Q4_K/37 Q5_K. The full MTP block changes from 11 Q8_0/7 F32/2 BF16 (898 MB source payload) to 8 Q8_0/7 F32/2 BF16/1 Q5_K/2 Q4_K (529 MB source payload). - -A metadata-only probe on 2026-10-19 calls the built backend's `ggml_openvino_get_extracted_layout` for every quantized tensor with `q4_asym64_all`. **Before the precision-policy correction below**, this setting converts Q4_K/Q5_K/Q6_K and **3D expert** Q8_0/Q5_1 to asymmetric INT4/group-64. Ordinary **2D Q8_0 remains symmetric INT8/group-32**; `_all` adds Q4_K to the K-quant policy, rather than including every quantization type. Embedding/output take the earlier channel-wise INT8 override. The following layout table and the historical throughput measurements use that earlier policy; the corrected-policy retest is labeled separately below. - -| Converted quantized weights | yamini | UD | -| --- | ---: | ---: | -| Trunk dense INT4/group-64 tensors | 156 | 0 | -| Trunk dense INT8/group-32 tensors | 94 | 250 | -| Trunk dense packed weights + scales + zero points | 862,814,208 bytes | 1,492,910,080 bytes | -| Trunk expert INT4/group-64 tensors | 120 | 120 | -| Trunk expert packed weights + metadata | 17,364,418,560 bytes | 17,364,418,560 bytes | -| Embedding/output channel-wise INT8 packed weights + metadata | 1,018,112,000 bytes | 1,018,112,000 bytes | -| MTP quantized packed weights + metadata | 475,332,608 bytes | 475,332,608 bytes | - -The 156 tensors changing from INT4/group-64 to INT8/group-32 are 30 attention gates, 10 attention output projections, 10 attention Q projections, 30 recurrent QKV projections, 60 shared-expert FFN projections and 16 SSM output projections. UD therefore adds **630,095,872 bytes (630 MB, 73%)** to the converted dense trunk. These counts describe extracted packed constants, excluding nonquantized tensors, allocation padding and plugin repacking; they are not a measurement of GPU traffic or the compiled model's footprint. The expert, embedding/output and MTP layouts match, but the numerical weights can still differ because requantization starts from different source quantizations. The extra dense weight traffic and different INT8 kernels are a concrete explanation for a decode gap that is already present without snapshots; a controlled INT4/INT8 comparison and per-op profiling are needed to attribute it quantitatively. Probe input, code and per-tensor results are in `tmp/ud-layout-20261019/`. - -### Precision-policy correction, 2026-10-19 - -The [native OpenVINO model card](https://huggingface.co/OpenVINO/Qwen3.6-35B-A3B-int4-ov) specifies NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM`. [NNCF's compression guide](https://github.com/openvinotoolkit/nncf/blob/develop/docs/usage/post_training_compression/weights_compression/Usage.md) defines the ratio over eligible weights excluding special layers; embeddings, convolutions and the last linear layer receive backup precision by default. INT8_SYM is channel-wise. The GGUF backend approximates that precision scheme for supported quantized linear tensors, rather than reproducing compression from the original floating-point model; floating-point tensors remain unchanged. - -`q4_asym64_all` now includes ordinary Q8_0/Q5_1 in INT4/group-64 conversion. The default and non-`all` policies keep their existing dense INT8 behavior, including the expert-only GPU workaround. Embedding/output retain channel-wise INT8. Q8_0/Q5_1 rows not divisible by 64 use channel-wise INT8 backup; all affected rows in these Qwen models are divisible by 64. The compiled-model fingerprint version is incremented so old INT8/group-32 blobs cannot silently serve the updated policy. - -The updated metadata probe finds matching layouts for **all 383 quantized tensors** between yamini and UD. Both now have **250 trunk dense INT4/group-64 tensors**, occupying **757,432,320 bytes** including scales/zero points. This also reduces yamini's footprint: its 94 previously retained dense Q8_0 tensors now convert to INT4. Equal layouts do not imply equal numerical weights or expert-routing decisions. - -Release backend build passes. A targeted conversion/MatMul probe validates Q8_0 and Q5_1 on CPU and GPU against an independent reference decoded from the resulting packed INT4 weights, with dynamic token counts 1, 3 and 32. All 12 comparisons pass (maximum normalized squared error 1.19e-7). Policy checks cover default/native/non-`all` behavior, expert conversion, embedding/output overrides, incompatible-width backup and `no_requant`. Artifacts are `tmp/ud-layout-20261019/{validate.cpp,validation.log,layout-after.tsv}`. These checks validate the conversion path; the full-model performance retest is recorded next. Perplexity has not been evaluated with the corrected policy. - -### Full-model retest with corrected dense INT4 policy, 2026-10-19 - -Release llama.cpp build from HEAD `2a978aa9b` plus the dense Q8_0/Q5_1 policy and cache-fingerprint changes; native OpenVINO HEAD `9e08e52ad5` is unchanged. The exact source diff and command manifests are in `tmp/qwen36-allrequant-20261019/`. Runtime settings are GPU, native softplus, disabled KV slicing and `q4_asym64_all`. Compiled-model caching, stateful execution and profiling are unset for benchmark/CLI runs; the controlled target-call matrix enables host timing instrumentation. GPU workloads run serially. - -Five benchmark repetitions, same `-p 1024 -n 512 -d 0,1024` command; mean ± benchmark standard deviation: - -| UD workload | Earlier dense INT8 policy tokens/s | Corrected dense INT4 policy tokens/s | Change | -| --- | ---: | ---: | ---: | -| pp1024 | 1127.99 ± 7.25 | **1130.09 ± 5.11** | +0.2% | -| tg512 | 27.41 ± 0.07 | **33.17 ± 0.12** | **+21.0%** | -| pp1024 at depth 1024 | 1081.64 ± 19.96 | **1082.36 ± 18.15** | +0.1% | -| tg512 at depth 1024 | 26.19 ± 0.04 | **31.55 ± 0.06** | **+20.5%** | - -Both models with the corrected policy: - -| Workload | UD tokens/s | yamini tokens/s | -| --- | ---: | ---: | -| pp1024 | 1130.09 ± 5.11 | 1133.57 ± 7.88 | -| tg512 | **33.17 ± 0.12** | **33.21 ± 0.08** | -| pp1024 at depth 1024 | 1082.36 ± 18.15 | 1074.32 ± 38.38 | -| tg512 at depth 1024 | **31.55 ± 0.06** | **31.54 ± 0.05** | - -The previous 8% UD/yamini decode gap disappears within run variation. Yamini also improves from 29.91 to 33.21 tokens/s (+11.0%) at depth zero and 28.47 to 31.54 (+10.8%) at depth 1024. Together with matching converted layouts, this supports the retained dense INT8/group-32 weights as the main cause of the previous gap. It does not isolate extra weight bandwidth from differences between INT8 and INT4 kernels. - -The controlled matrix repeats the original 128-token prefix, eight warmups, 32 measured calls, hidden output and logits for all tokens. UD median milliseconds: - -| Target call | Earlier policy ms | Corrected policy ms | -| --- | ---: | ---: | -| T1, no snapshots | 35.19 | **29.80** | -| T3, no snapshots | 44.10 | **38.17** | -| T1, snapshots | 43.42 | **36.75** | -| T3, snapshots | 58.83 | **53.38** | -| T3, reject two | 59.42 | **53.28** | - -Ordinary T1→T3 adds **8.37 ms**. Snapshot storage adds **15.21 ms** to T3, versus 14.73 ms previously; these sequential runs do not establish a meaningful change in that overhead. The consistent 5–7 ms target-call improvement comes from the precision-policy change, with recurrent execution unchanged. - -The corrected-policy yamini matrix also closely matches UD: - -| Target call | UD median ms | yamini median ms | -| --- | ---: | ---: | -| T1, no snapshots | 29.80 | 28.79 | -| T3, no snapshots | 38.17 | 38.06 | -| T1, snapshots | 36.75 | 36.77 | -| T3, snapshots | 53.38 | 53.03 | -| T3, reject two | 53.28 | 53.01 | - -The one-slot `Hi` CLI runs use the original context 4096, two CPU threads, greedy sampling and 192-token cap. Each mode is one process run; medians exclude positions below 64. - -| UD CLI measurement | Earlier policy | Corrected policy | -| --- | ---: | ---: | -| Non-MTP generation tokens/s | 27.15 | **33.07** | -| MTP generation tokens/s | 35.93 | **39.04** | -| Non-MTP target T1 median ms | 35.88 | **28.97** | -| MTP verification T3 median ms | 57.74 | **50.52** | -| Draft token median ms | 5.980 | **5.888** | -| Draft catch-up T3 median ms | 1.790 | **1.736** | -| Draft proposals accepted/generated | 114/136 | **119/143** | -| Mean emitted tokens per cycle | 2.68 | **2.65** | - -MTP generation improves 8.7%, and exceeds the new non-MTP run by 18.1%. The MTP result includes a final two-token verification call (90.77 ms) when reaching the cap; the warmed T3 median describes the usual three-token loop. Both corrected-policy runs reach the 192-token cap, versus 182 tokens previously. Requantization changes the greedy continuation, so the fixed-token matrix is the stronger timing comparison; these CLI runs do not establish unchanged model quality or identical non-MTP/MTP output. - -Both models with the corrected policy, same CLI setup: - -| CLI measurement | UD | yamini | -| --- | ---: | ---: | -| Non-MTP generation tokens/s | **33.07** | **33.26** | -| MTP generation tokens/s | **39.04** | **40.95** | -| Non-MTP target T1 median ms | 28.97 | 29.02 | -| MTP verification T3 median ms | 50.52 | 49.31 | -| Draft token median ms | 5.888 | 5.863 | -| Draft catch-up T3 median ms | 1.736 | 1.722 | -| Draft proposals accepted/generated | 119/143 (83.22%) | 106/126 (84.13%) | -| Mean emitted tokens per cycle | 2.65 | 2.68 | -| Generated tokens without/with MTP | 192/192 | 170/170 | - -Yamini's MTP run improves from 38.74 to 40.95 tokens/s (+5.7%) and is 23.1% faster than its new non-MTP run. The remaining 4.7% UD/yamini MTP throughput difference is from single runs with different continuations, slightly different verification latency/acceptance and UD's final T2 cap call; it cannot be attributed to a packed-weight layout difference. The controlled T3 matrix and repeated non-MTP benchmark now closely agree. All eight benchmark/matrix/CLI processes exit successfully; raw logs, command manifests, per-call distributions and `comparison.json` are in `tmp/qwen36-allrequant-20261019/`. Four-slot serving and perplexity were not rerun in this performance-only retest. - -### Target-call timings with the earlier precision policy - -The forced-token matrix uses a 128-token prefix, eight warmups, 32 measured calls, hidden output enabled, and logits on all input tokens. Median milliseconds: - -| Target call | Optimized yamini ms | Current UD ms | -| --- | ---: | ---: | -| T1, no snapshots | 29.64 | **35.19** | -| T3, no snapshots | 38.75 | **44.10** | -| T1, snapshots | 37.51 | **43.42** | -| T3, snapshots | 53.95 | **58.83** | -| T3, reject two | 53.90 | **59.42** | - -UD ordinary T1→T3 costs **8.91 ms**, and snapshot storage adds **14.73 ms** to T3. The latter is close to yamini's 15.20 ms: the extra UD cost is already present in ordinary decode and does not look like a new snapshot-path regression. Rejection raises the T3 median by 0.58 ms in this run; host sequence removal is 0.0072 ms. These differences include full inference scheduling, layout and compute, not only MoE or cache kernels. - -The `Hi` greeting runs use context 4096, one slot, two CPU threads, temperature zero and a 192-token cap. Warmed medians exclude positions below 64. These are one process run per mode, not independent repeated trials. - -| Measurement | Optimized yamini | Current UD | -| --- | ---: | ---: | -| Non-MTP generation tokens/s | 32.23 | **27.15** | -| MTP generation tokens/s | 38.74 | **35.93** | -| Non-MTP target T1 median ms | 29.76 | **35.88** | -| MTP verification T3 median ms | 51.55 | **57.74** | -| Draft token median ms | 6.010 | **5.980** | -| Draft catch-up T3 median ms | 1.808 | **1.790** | -| Accepted proposals | 95/116 (81.90%) | **114/136 (83.82%)** | -| Mean output tokens/round | 2.64 | **2.68** | - -MTP is **32.3% faster** than non-MTP on UD. Both UD continuations have 182 tokens; the yamini continuations had 162 without MTP and 154 with MTP, so cross-model generation rates do not represent an identical-output trial. The changed MTP expert quantization does not show a material draft-latency change in this run. Verification rises by about 6.2 ms, consistent with the additional UD latency observed in ordinary target inference. - -The median round compute subtotal is approximately `57.74 + 2*5.980 + 1.790 = 71.49 ms`. At the measured mean 2.68 output tokens/round this is **26.68 ms/token**, before remaining host work, close to **27.83 ms/token** reported end-to-end. Cold prompt processing is 3.57 s with MTP and 0.40 s without it; graph compilation/startup work is excluded from generation throughput. - -The UD non-MTP `llama-server -np 4 -c 16384` check passes **12/12 requests**, including concurrent four-slot waves, selected-slot reset/reuse, and cached continuation. The UD MTP server also passes **12/12 requests** with two proposals, accepting **42/64 draft tokens**. These short concurrent requests include compilation and test functionality, not warmed serving throughput. No stateful tests were run. A detached clean source checkout containing only the proposed llama.cpp commit files builds `llama-bench`, `llama-cli`, `llama-server`, and `test-backend-sampler` successfully. Its 0.8B slot/rollback and hidden-row regressions pass, and all seven native tests pass again. This confirms the changes build without the unrelated dirty files in the main workspace. Exact commands, metadata/type counts, logs and responses are in `tmp/qwen36-ud-20261016/`. - -## Historical target 35B results (yamini) - -Model: Qwen3.6-35B-A3B-Q4_K_M_yamini.gguf. Same Release build and runtime, `q4_asym64_all`, GPU, native softplus, KV slicing disabled. Baseline is the previous native implementation, rather than the removed single-slot shortcut path. Five benchmark repetitions: `-p 1024 -n 512 -d 0,1024`. - -| Workload | Previous native tokens/s | Optimized tokens/s | -| --- | ---: | ---: | -| pp1024 | 1079.26 ± 7.49 | 1125.19 ± 8.25 | -| tg512 | 23.05 ± 0.27 | 29.91 ± 0.47 | -| pp1024 at depth 1024 | 1031.68 ± 18.71 | 1074.27 ± 33.48 | -| tg512 at depth 1024 | 22.32 ± 0.03 | 28.47 ± 0.44 | - -Generation improves **29.8%** at depth zero and **27.6%** at depth 1024. The 30 tokens/s target is approached at depth zero; the five-repeat mean remains below it. These are generic stateless cache paths. - -Controlled target calls use the same forced-token stream, 128-token prefix, eight warmups, and 32 measured calls. Values below are median milliseconds; hidden states are enabled and all token rows request logits. The Vulkan column is the prior target-model reference, not a new Vulkan rerun. - -| Target call | Previous native OV ms | Optimized OV ms | Prior Vulkan ms | -| --- | ---: | ---: | ---: | -| T1, no snapshots | 42.11 | 29.64 | 43.21 | -| T3, no snapshots | 55.43 | 38.75 | 54.29 | -| T1, snapshots | 60.86 | 37.51 | 33.54 | -| T3, snapshots | 79.27 | 53.95 | 52.59 | -| T3, reject two | 79.58 | 53.90 | 52.72 | - -Three-token verification falls by **31.9%**, from 79.27 to 53.95 ms. The snapshot-enabled T3 penalty falls from 23.84 to **15.20 ms** relative to ordinary T3. Increasing ordinary token width from one to three costs 9.11 ms; rejection adds no measurable penalty in this short comparison, and host sequence removal takes about 0.0072 ms. Restoring state is included in the following target inference. These measurements distinguish snapshot preparation/storage from actual rollback and from multi-token computation; they do not isolate individual kernels. - -Optimized controlled snapshot-enabled T3 is within 2.6% of the previous Vulkan reference, while the ordinary T1 path reaches approximately 30 ms. The greeting workload uses `Hi`, context 4096, one slot, two CPU threads, temperature zero, a 192-token cap, and two draft proposals for MTP. Warmed call medians exclude positions below 64. These are one process run per mode, with many warmed calls, rather than repeated independent trials. - -| Measurement | Previous native OV | Optimized OV | Prior Vulkan reference | -| --- | ---: | ---: | ---: | -| Non-MTP generation tokens/s | 22.95 | **32.23** | — | -| MTP generation tokens/s | 27.93 | **38.74** | 49.83 | -| Non-MTP target T1 median ms | 42.39 | 29.76 | — | -| MTP verification T3 median ms | 77.10 | **51.55** | 42.56 | -| Draft token median ms | 6.015 | 6.010 | 4.99 | -| Draft catch-up T3 median ms | 1.799 | 1.808 | 2.31 | -| Accepted proposals | 95/116 | **95/116** | differing acceptance | - -MTP improves **38.7%** over the previous native path and runs **20.2%** faster than optimized non-MTP on this greeting. The new MTP continuation still has 154 tokens and identical acceptance, so the improvement is not explained by increased acceptance. Non-MTP produces 162 tokens versus 159 previously; use the forced-token table for causal comparisons. - -A round's median compute subtotal is approximately `51.55 + 2*6.010 + 1.808 = 65.38 ms`. Divide by the mean 2.64 output tokens, not always three: this gives **24.76 ms/token** before remaining host work, close to the measured **25.81 ms/token**. Draft generation/catch-up are essentially unchanged; the throughput gain comes from target verification. - -MTP remains **22.3% below** the prior 49.83 tokens/s Vulkan greeting reference. Its 51.55 ms verification is about 9 ms slower than the previous Vulkan greeting, and two draft tokens add about 2 ms more than that reference. The close controlled T3 results and larger greeting gap are different context/output/acceptance workloads; they should not be mixed into one exact overhead estimate. Vulkan's target-model reference was not rerun in this implementation round. Cold prompt time is 3.54 s for MTP versus 0.28 s without it, including first-use graph work; these values are separate from warmed generation. - -## Original optimization validation and artifacts (0.8B and yamini) - -Native GPU tests cover dynamic active counts/token widths, f16/f32, i32/i64, reset, duplicate/cyclic maps, preserved inactive rows, overlapping snapshot destinations, native matrix-layout gather/update, cloning, and compiled export/import. Model regressions replay each active sequence independently to check changing slot subsets, nonzero reset, copied sequences, inactive-state preservation and unequal rejection. Hidden-output tests cover changing selected rows and zero requested outputs. A CPU smoke run passes on 0.8B. - -The final native/type-propagation suite passes **7/7 tests**. The small-model replay regression passes **40/40 sequence comparisons**, with maximum relative logit error **0.002724** against independently replayed sequences. Hidden-state/selected-row/zero-output rollback tests pass with no sampled-token mismatches. The 0.8B `llama-server -np 4 -c 16384` run passes **12/12 requests**, covering concurrent waves, selected-slot reset/reuse, and cached continuation. The 35B non-MTP `llama-server -np 4 -c 16384` run also passes **12/12 requests** under `q4_asym64_all`. The 35B MTP server also passes **12/12 requests** with two proposals, accepting **43/64 draft tokens**. These short server requests include cold graph work and validate functionality; their timings are not warmed throughput baselines. Qwen3.5-0.8B has no MTP tensors, so MTP server validation uses the 35B target. Stateful testing remains outside this work's scope. - -A native-on/off crosscheck repeats the recurrent-slot regression and captures every compared logit vector: **80/80 records match exactly**, with maximum relative error 0 and no argmax mismatches. This checks the new native cache/state-layout translations against the retained generic decomposition. - -The full 0.8B compiled-model cache exports and reloads successfully with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`; GPU cold/export, GPU import, and CPU fallback produce the same eight-token greedy continuation. Native export/import tests additionally cover dynamic metadata and matrix attributes. Release rebuild and `git diff --check` pass for both repositories. CPU fallback is smoke-tested; static, stateful, NPU, and a released runtime without the new native ops were not tested in this implementation round. - -Commands, environments, profiles, model responses, and intermediate/final logs are in `tmp/qwen08-opt-20261016/`. The original baseline evidence is in `tmp/qwen08-perf-plan-20261016/`; the prior 35B native baseline is in `tmp/mtp-native-20261016/`. Early StateUpdate execution attempts exposed a missing GPU factory registration; it was corrected before the successful native/model tests and reported benchmarks. - -## Remaining opportunities - -- Snapshot-enabled verification still has additional state traffic and graph work. A complete native gather→GDN→cache-update operation could eliminate prepared-cache and snapshot intermediates, but requires careful multi-slot alias and overlap semantics. -- Further cache kernel tuning has a limited budget on ordinary 0.8B decode; dense matmul dominates the current profile. Remaining kernel/reorder fusion should be driven by measured latency rather than node count alone. -- Logits still cross to host for sampling, and hidden/norm outputs remain per the caller's output contract. Removing them requires caller-aware output selection; their presence is not a full-cache host-copy problem. -- Vulkan's 57.91 t/s remains ahead; the final 56.21 t/s small-model repeat meets the ≥55 t/s target. Target-model MTP also includes draft/catch-up and acceptance effects that cannot be inferred from the 0.8B target-call matrix. - -## GatedDeltaNet two-output snapshots (2026-10-19) - -The GatedDeltaNet snapshot extension was added to support Qwen3.5 (`qwen35`/`qwen35moe`) in llama.cpp's OpenVINO backend, including the current Qwen3.6 target. MTP verification can reject a draft after processing later tokens in the same batch; llama.cpp needs the earlier recurrent `cache_s` state to roll back to the accepted prefix. Snapshots provide that state without recomputing the recurrence. - -The internal OpenVINO `GatedDeltaNet` now has exactly two outputs for every `snapshot_count`. Output 0 is attention. Output 1 is the final recurrent state `[B,H_v,D_k,D_v]` when `K=1`, and the newest-first snapshot tensor `[K,B,H_v,D_k,D_v]` when `K>1`. Snapshot entry `i` contains the state after zero-based token `T-1-i`; entry 0 is the final state. Only `min(K,T)` entries are valid, and the pre-batch state is not included. - -In snapshot mode, the GPU kernel writes the final state into snapshot entry 0 and no longer writes a second copy into the input state buffer. This removes one state matrix write and one operator output per GDN layer and active batch. The input state remains unchanged, which is needed when speculative verification later rolls back. The llama.cpp translation consumes output 1 directly and selects the valid newest snapshot for its existing cache update. Ordinary `K=1` execution keeps its existing GPU state update behavior. Transformations that reconstruct GDN preserve `snapshot_count`; paged GDN fusion skips snapshot mode. The model-cache fingerprint revision is now 4. - -The UD target was measured with the same GPU, `q4_asym64_all`, native softplus, and disabled KV slicing. The ordinary benchmark uses five repeats. The MTP CLI comparison is one warmed run per mode, and the controlled target-call matrix uses the same forced-token stream, prefix, warmups, and measured calls as the previous UD run. - -| Measurement | Previous three-output path | Two-output path | -| --- | ---: | ---: | -| `llama-bench` tg512 | 33.17 ± 0.12 t/s | 33.34 ± 0.06 t/s | -| `llama-bench` tg512 at depth 1024 | 31.55 ± 0.06 t/s | 31.61 ± 0.03 t/s | -| Greeting, non-MTP | 33.07 t/s | 33.29 t/s | -| Greeting, MTP with two proposals | 39.04 t/s | 41.63 t/s | -| Ordinary T3 target call, no snapshots | 38.167 ms | 38.161 ms | -| T3 target call with snapshots | 53.382 ms | 52.853 ms | -| T3 target call with snapshots and two rejected tokens | 53.278 ms | 53.005 ms | -| MTP draft token median | 5.888 ms | 5.892 ms | -| MTP T3 verification median | 50.520 ms | 48.627 ms | -| MTP catch-up T3 median | 1.736 ms | 1.773 ms | -| Accepted proposals | 119 / 143 | 121 / 140 | - -Ordinary decode and the controlled snapshot matrix are within run variation. The one MTP CLI run is 6.6% faster, with verification about 1.9 ms shorter and a somewhat higher acceptance rate; treat this as an encouraging run rather than an isolated causal speedup estimate. Draft generation is unchanged. The structural gain is one fewer GDN state-matrix write per layer and active batch, not an expected large change to total model throughput. - -Validation for this change: the native GDN reference checks cover `K=1/3`, dynamic batches and token widths, optimized and fallback dimensions, valid snapshot ordering, unchanged initial state, and compiled-model export/import. All 21 native GPU GDN unit cases pass. Core type/visitor and transformation tests pass (17 tests), including `FuseL2NormIntoGDN`, `FuseGroupedQueryIntoGDN`, and paged-fusion snapshot preservation. The native recurrent-cache suite passes 7/7; the Qwen3.5-0.8B GPU slot replay and hidden-output rollback checks pass. UD `llama-server -np 4` passes 12/12 requests both without MTP and with two-token MTP, including concurrent requests, slot reuse/reset, and cached continuation. Logs are in `tmp/gdn-two-output-20261019/`. - - -## Generic convolution/GDN fusion (2026-10-21) - -The subsequent [fusion report](OPENVINO-RECURRENT-FUSION-PERF.md) implements two -native GPU computation/cache operations per recurrent layer for Qwen3.5/Qwen3.6 -in llama.cpp. It includes matched four-slot UD server results, runtime copy/kernel -profiling, MTP rejection/rollback validation, and remaining cache-output traffic. -The small-model vectorization experiment's GPU `llama-bench -p 1024 -n 128 -r 3` -run measured **58.71 ± 0.09 decode tokens/s** and **7,375.10 ± 82.23 prompt tokens/s**. -GDN vectorization was subsequently reverted; these are experiment results, not a -measurement of the final retained kernel. This is -a different workload from the original `-p 0` table above and has no freshly rerun -Vulkan control. The older measurements retain their original meaning. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index dbbc277dfdaa..773c32cf36a9 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -1,386 +1,70 @@ -# Current recurrent-cache implementation (2026-10-27) +# Current Qwen GPU implementation -Dynamic stateless GPU graphs use the independent `RecurrentConvCacheUpdate` and -`RecurrentGatedDeltaNetUpdate` ops for Qwen3.5/Qwen3.6 in llama.cpp. In-place USM -bindings are primary; private output and copy-back handle incompatible bindings. -The convolution op always includes depthwise computation; separate history/QKV -output and rotation banks are removed. See the backend README for current -settings and the multislot report for the benchmark comparisons. +As of 2026-10-29, the default Qwen3.5/Qwen3.6 path is dynamic stateless execution with `RecurrentConvCacheUpdate`, `RecurrentGatedDeltaNetUpdate`, and stable pure-top-k MTP translation. It supports one or multiple slots and rollback. The implementation applies to `qwen35` and `qwen35moe`; the performance target is the UD Qwen3.6-35B-A3B MTP GGUF. -The remaining sections are historical measurements and design notes. Their -rotation ops, separate-convolution mode, opt-in in-place flag and branch layout describe earlier versions. +Build against the matching OpenVINO runtime/GPU plugin with the independent Update ops. The tested runtime is `qwen-mtp-inplace-primary`, commit `9299cc3d78`; llama.cpp stable sampling is `71c0bbc4d`. Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requantization policy. The current cache translation revision is 13. ---- +## Buffer ownership and operation boundaries -# Generic recurrent-cache baseline for Qwen MTP +| State | Storage and lifetime | Update path | +|---|---|---| +| Attention K/V | Full caller-owned USM allocation, sized by context and KV layout | Native stateless KV fusion when eligible; SDPA consumes the live prefix | +| Convolution `cache_r` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, convolution and ordered history/snapshot writes | +| GDN `cache_s` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, GDN and ordered final/snapshot writes | +| Runtime controls | Reused USM host storage on GPU | Row maps, offsets and write controls remain runtime inputs | +| Protected source rows | Private device scratch | Staged before writes to protect cycles, duplicate sources and overlaps | +| Inactive sampling results | Private device-USM scratch | Discarded without touching inactive GGML output buffers | -Date: 2026-10-15. Branch: `qwen-openvino-generic-cache`. Model: Qwen3.6-35B-A3B-Q4_K_M_yamini.gguf. +Attention context capacity does not set recurrent-cache size. Cache input Parameter and cache Result bind the same stable allocation on the primary path. There are no rotation banks or pointer swaps. -Removing the single-slot shortcuts changes the matched non-MTP `tg512` baseline from **35.54 to 19.72 tokens/s** (33.62 to 19.10 at depth 1024). Four-slot serving passes both with and without MTP. On the same greeting workload, MTP now measures **23.21 tokens/s versus 19.45 without MTP**, approximately a 19% improvement against the generic path. +The GPU plugin uses two stages: first preserve required original rows in scratch while applying logical reset and precision rounding; then compute and perform ordered writes. This avoids overwriting a source before another destination has read it. Identity reorder sources need no scratch writes. In-place execution removes the spare full output bank, not every cache read or internal memory transaction. -The previous non-MTP baseline used single-slot shortcuts that were unavailable to MTP. Consequently, the earlier 36.1 versus 80.7 ms three-token comparison mixed the cost of general cache maintenance with the cost of retaining rollback snapshots. It did not isolate snapshot capture alone. The baseline below removes that confound. +`RecurrentConvCacheUpdate` has nine required inputs, including depthwise weights. Output 0 is convolution `[1,B,T,C]`; output 1 is the full updated cache. It does not expose an intermediate history/QKV tensor. `RecurrentGatedDeltaNetUpdate` emits attention and the full updated state cache; the cache retains the newest `min(T,snapshot_count)` states for MTP, newest first. -## Changes +## Generic fallback and restrictions -Stateless execution now uses the same reset, gather/reorder, and partial-writeback translations for one or multiple slots. Removed the host-side single-slot cache clear, reset/gather identity cases, and full-cache replacement/no-op CPY cases 7/8/9. Native GatedDeltaNet direct output routing, convolution-window Gather, and the TopK improvement remain: these support multiple slots. +Exact compatible layouts/storage and exclusive cache readers permit mutation, including eligible optimized Reshape aliases. Shared original-cache readers, incompatible layouts, unrelated overlaps or unsupported execution paths retain immutable-input semantics using a private output and required Result copy-back. Restore or clear state after a failed aliased inference before retrying. GPU replay is disabled for these ops because stage selection depends on bindings. -Exercising the generic paths also exposed and fixed three correctness problems: +`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary decomposition for diagnosis. The primitive/unmatched GDN path retains its snapshot support. Rotation, the former three-op cache solution, the history-only/separate-convolution mode and single-slot no-rollback shortcuts are removed. Stateful and NPU MTP are not the supported default; this validation does not claim those paths. -- Reset offsets were divided by elements per row instead of bytes per row, selecting the wrong row for nonzero offsets. -- Views of active recurrent states could retain inactive rows from the combined gather when the active sequence count changed. They now select the runtime active prefix before reshaping. -- An initially empty reset or reorder remainder could disappear from the translated in-place alias chain even when a later batch made it nonempty. Dynamic recurrent writes now remain in that chain, and remainder source/destination offsets are runtime inputs. +## Attention KV layout -The compiled-model cache translation revision is incremented. Existing blobs must be regenerated once with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` unset. The user's `tmp/qwen36_ud_cache` directory was not present in this workspace; measurements use cold model loading and exclude it from token-throughput timing. +`GGML_OPENVINO_ENABLE_KV_4D=1` enables eligible native stateless in-place attention updates. The current eligibility covers one physical stream, including unified KV. Explicit split multi-slot KV retains the full-cache path and can be much slower even with only one active slot. Use `--kv-unified` for multi-slot OV GPU serving. -## Benchmark method and results +Leave `GGML_OPENVINO_DISABLE_KV_SLICE` unset. Live-prefix slicing applies to eligible ordinary attention K/V roots, not recurrent caches. In-place KV fusion can bind the full allocation while exposing a live prefix internally. KV-slice on/off is a runtime binding choice and does not require different compiled blobs; incompatible graph layouts/capacities can still do so. -Hardware: Intel Arc B390 iGPU / Core Ultra X7 358H, 62 GiB RAM. Both locally matched runs use Release `build/MtpOVPerf`, the same existing unrelated working-tree changes, llama.cpp starting at `4f92304c2`, and the OpenVINO runtime containing `21cacac33d`. No stateful execution is used. The appendix used `build/ReleaseOV`, whose configured runtime is a different 2026.4.1 toolkit; treat that column as a reference, not the matched control. +## Stable MTP sampling -Both matched benchmark runs use: +The [graph walkthrough](MTP-SAMPLING-GRAPH.md) describes the fixed sampling interface. The backend keeps pure top-k branches for all configured slots, packs runtime row indices, and uses scratch for inactive outputs. It does not change the original cgraph or execute inactive stateful sampler chains. Only the small sampling branches stay at configured capacity; the expensive draft layer processes active rows. -```sh -GGML_OPENVINO_DEVICE=GPU \ -GGML_OPENVINO_NATIVE_SOFTPLUS=1 \ -GGML_OPENVINO_DISABLE_KV_SLICE=1 \ -GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ -build/MtpOVPerf/bin/llama-bench \ - -m "$HOME/models/Qwen3.6-35B-A3B-GGUF/Qwen3.6-35B-A3B-Q4_K_M_yamini.gguf" \ - -p 1024 -n 512 -d 0,1024 -``` - -Default five repetitions; values are reported tokens/s with the benchmark's standard deviation. GPU workloads run serially. - -| Workload | User appendix | Local before removal | Generic cache path | -| --- | ---: | ---: | ---: | -| pp1024 | 1051.29 +/- 5.21 | 1151.77 +/- 8.85 | 1058.21 +/- 7.29 | -| tg512 | 36.98 +/- 0.10 | 35.54 +/- 0.06 | 19.72 +/- 0.03 | -| pp1024 at depth 1024 | 979.10 +/- 61.42 | 1089.73 +/- 48.93 | 1016.84 +/- 17.64 | -| tg512 at depth 1024 | 34.77 +/- 0.05 | 33.62 +/- 0.05 | 19.10 +/- 0.03 | - -### Controlled target calls - -One loaded model, identical forced-token stream, context 4096, one slot, two CPU threads, hidden-state extraction enabled. Each case has a 128-token prefix, eight warmup calls, and 32 measured calls. Values are median milliseconds per target call. The previous OpenVINO and Vulkan columns are from the 2026-10-14 experiment; Vulkan was not rerun for this OpenVINO-only cleanup. - -| Target call | Previous OV path | Generic OV path | Prior Vulkan reference | -| --- | ---: | ---: | ---: | -| 1 token, no snapshots | 28.31 | 49.41 | 43.21 | -| 3 tokens, no snapshots | 36.10 | 62.55 | 54.29 | -| 1 token, snapshots | 62.01 | 76.49 | 33.54 | -| 3 tokens, snapshots, no rejection | 80.74 | 95.57 | 52.59 | -| 3 tokens, snapshots, reject 2 | 79.37 | 95.67 | 52.72 | - -With the generic baseline, moving from one to three tokens without snapshots adds **13.14 ms**; enabling snapshots at three tokens adds **33.02 ms**. Along this comparison, the snapshot-enabled path accounts for about **72%** of the increase from one-token ordinary decode to three-token verification, rather than the earlier approximately 85%. These deltas include the full graph's layout, cache, scheduling, and storage changes; they are not timings of the native GDN kernel alone. - -Rejecting two tokens changes the target median by only 0.10 ms here. The host `seq_rm` median is 0.0075 ms; the following target call includes the deferred restore. The large penalty is present even with no rejection. In the final rejection-case call, the full target call was 96.10 ms and OpenVINO `infer()` was 94.40 ms. This places most latency inside OpenVINO execution, which includes scheduling and synchronization as well as kernels. - -The old claim that a one-token call returns to roughly 28-30 ms applies to the removed shortcuts. The generic path now measures 49.41 ms without snapshots and 76.49 ms with them. - -### End-to-end generation - -Same `Hi` prompt, context 4096, one slot, two CPU threads, temperature zero, and a 192-token cap. These runs use the target requantization and the same Release build. Per-call medians exclude positions below 64. Generation rates exclude model loading and prompt processing. - -| Measurement | Generic non-MTP | Generic MTP, two proposals | -| --- | ---: | ---: | -| Generation throughput | 19.45 tokens/s | 23.21 tokens/s | -| Generated tokens | 159 | 154 | -| One-token target call, median | 49.85 ms | - | -| Three-token verification, median | - | 95.62 ms | -| One draft token, median | - | 6.09 ms | -| Three-token draft catch-up, median | - | 1.91 ms | -| Accepted proposals | - | 95 / 116 (81.90%) | -| Mean output length per round | - | 2.64 | - -MTP is approximately **19.3% faster** than the generic non-MTP path on this greeting. The generated continuations have different lengths, so use the controlled target-call table for causal comparisons of batch width and snapshots. These are one process run per mode with many warmed calls, rather than repeated independent trials. - -Compared with the earlier TopK-optimized MTP run, throughput falls from 27.55 to 23.21 tokens/s while output length and acceptance remain 154 and 95/116. Median verification rises from 78.08 to 95.62 ms; draft latency changes only from 5.93 to 6.09 ms. The generic reset/reorder correctness fixes affect snapshot-enabled graphs too, particularly operations that were empty in the first captured batch. The absolute MTP slowdown therefore accompanies removal of the misleadingly fast non-MTP baseline. - -A speculative round costs approximately `verification + catch-up + 2 * draft + host work`, divided by `1 + accepted proposals`, not always three output tokens. The measured median compute subtotal is 109.71 ms/round; at 2.64 output tokens this is 41.56 ms/token before remaining host work, close to the reported 43.09 ms/token. - -The previous Vulkan greeting reference was 49.83 tokens/s, with 42.56 ms verification, 4.99 ms per draft, and 2.31 ms catch-up. Vulkan was not rerun here. The remaining OpenVINO gap is concentrated in target verification; the controlled results still identify snapshot-enabled cache maintenance as the largest added cost, while ordinary generic cache maintenance is also substantial. Separate kernel profiling is needed to divide that cost among dispatch, shape work, layout conversion, and memory traffic. +One compatible draft graph is shared across active subsets. Trunk and genuinely different graph stages/configurations remain separate. Prepare a compatible revision-13 cache once, then use cache-only mode. Exhaustive active-subset priming is no longer required, though first-use model import and runtime preparation still have a cost. ## Validation -- Release build and `git diff --check` pass. -- New `test-backend-sampler --test recurrent_slots`: four slots with changing active subsets, nonzero-slot reset, sequence copy/branch, inactive-slot preservation, and unequal rejection lengths. Both zero and two rollback positions are compared with independently replayed single-sequence logits on Qwen3.5-2B Q4_0. Maximum relative logit error: 0.006757 across 40 sequence comparisons. -- Existing hidden-state / zero-output / changing-sequence / rollback sampler check passes. -- Selected GPU operator tests: 266/266 supported cases pass. -- Selected CPU operator tests: 262/262 supported cases pass. -- Full 35B model: 12/12 server requests pass without MTP and 12/12 with two-token MTP, using `-np 4 -c 16384`, ordinary separate KV streams (`kv_unified=false`), temperature zero, and the target requantization. Cases include two concurrent four-slot waves, reset/reuse of selected slots, and cached continuation of an inactive slot. The MTP run generated 64 draft tokens and accepted 43. These short requests include graph compilation and are functional checks, not throughput comparisons. - -The optional full-model functional attempt with requantization unset hit an OpenVINO `FullyConnectedHorizontalFusion` failure in the unchanged runtime: projection scale shapes `[8192,1]`, `[512,64]`, and `[512,64]` cannot be concatenated. Full-model validation therefore uses the target `q4_asym64_all` configuration. That runtime fusion issue is outside this cache cleanup. - -A stateless forced-static CPU smoke test (Qwen3.5-2B, prefill chunks of 8, 16 generated tokens) matches dynamic CPU generation. Stateful execution and NPU execution were not tested. CPU recurrent snapshots are not supported by the native OpenVINO runtime. - -## Generic cache fusion opportunities - -`cache_r` and `cache_s` are the convolution and recurrent matrix state of the model's linear-attention blocks; they are separate from the ordinary flash-attention K/V cache. - -The proposed graph groups are useful fusion boundaries. Their main benefit would be eliminating intermediate kernels, shape work, and repeated cache copying. The current full-model translator already publishes the final cache root after chaining in-place writes; the existing target IRs have one `cache_r` and one `cache_s` Result per recurrent layer. Older IRs with duplicate cache Results should not be used to count current output transfers. - -| Proposed native operation | GGML subgraph from cgraph_ov.txt | Inputs | Outputs | -| --- | --- | --- | --- | -| RecurrentConvCache | 7-14 and 17-27 | old convolution cache; new QKV; reset range; source/destination row maps; active count; valid-token count; snapshot window starts and destination rows | convolution input for SSM_CONV; final updated convolution cache | -| RecurrentStateGather | 28-35 | old matrix-state cache; reset range; source/destination row maps; active count | active matrix states for GatedDeltaNet; reset/reordered cache feeding the later state writeback | - -`RecurrentConvCache` must depend on the QKV projection at node 15/16. Its first output replaces node 18, while its second replaces the final cache write. A kernel can read each history/new-token element directly for both outputs without constructing separate reset, gather, concatenation, and snapshot-copy intermediates. The convolution itself can remain outside this first implementation. - -`RecurrentStateGather` alone cannot perform final GDN writeback: that data does not exist until GatedDeltaNet runs. A subsequent generic cache-update fusion, or a cache-aware GatedDeltaNet variant, would remove the remaining snapshot layout/scatter chain. Only the final cache becomes a model Result; the prepared-cache output remains internal. - -Both operations must preserve arbitrary active subsets, inactive slots, repeated gather indices/sequence copies, nonzero destination rows, reset-before-gather ordering, valid snapshot prefixes when T