diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 5bdead151942..520236dc203d 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -84,3 +84,14 @@ On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), mod # NPU host gather `GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU, opt-in) gathers the rows of large host-resident embedding tables (at least 64 MiB, raw GGUF data) on the host. The static graph gets the gathered rows through an `ggml_host_rows_` input instead of an OpenVINO Gather over the table. NPUW otherwise lifts the table to a function input, and gathering from an input that large costs about as much as streaming the whole table every call (21.6 ms of Gemma 4 E2B decode). A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all. + +## Multimodal + +Qwen3.5 and Gemma4 E2B image input work on OpenVINO CPU and GPU with their matching +projectors. Four-slot serving was validated with unified and split KV. +Qwen3.5 reuses its vision graph across image resolutions; Gemma4 uses +resolution-specific encoder graphs. + +Gemma4 audio is not enabled: preprocessing and Conformer still need dynamic length/block handling, runtime padding and view/state offsets, and cross-length compiled-model reuse. The small weightless preprocessing graph currently runs uncached because of the naive path's node-count heuristic. + +Static/NPU multimodal execution is untested. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index ac25634177d5..91e967ad99df 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -6,6 +6,7 @@ #include "ggml-quants.h" #include "ggml.h" #include "utils.h" +#include "openvino/utils.h" #include #include @@ -33,6 +34,7 @@ #include #include #include +#include #include static std::set collect_graph_output_names(const ggml_cgraph * cgraph) { @@ -302,12 +304,24 @@ static std::string get_tensor_ov_name(const ggml_cgraph * cgraph, const ggml_ten return GgmlOvDecoder::get_tensor_name(cgraph, tensor); } +std::string GgmlOvDecoder::get_position_input_ov_name(const ggml_tensor * tensor) const { + // Keep independent spatial position tensors on independent ports. + for (int i = 0; i < m_cgraph->n_nodes; ++i) { + const auto * node = m_cgraph->nodes[i]; + if (node->op == GGML_OP_ROPE) { + if (node->src[1] != tensor) { return get_tensor_name(m_cgraph, tensor); } + break; + } + } + return "inp_pos"; +} + static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder, const ggml_cgraph * cgraph, const ggml_tensor * tensor, const ggml_tensor * op) { if (GgmlOvDecoder::is_inp_pos(tensor, op)) { - return "inp_pos"; + return decoder->get_position_input_ov_name(tensor); } if (GgmlOvDecoder::is_inp_emb(tensor, op)) { return "embd"; @@ -435,6 +449,29 @@ bool GgmlOvDecoder::is_gdn_out_prescaled(const ggml_tensor * gdn) const { return has_norm; } +static bool is_gdn_output_gate_view(const ggml_tensor * node, const ggml_cgraph * graph) { + if (node->op != GGML_OP_VIEW || !ggml_is_contiguous(node) || node->view_offs != 0 || + !node->src[0] || node->src[0]->op != GGML_OP_MUL_MAT || + ggml_nelements(node) != ggml_nelements(node->src[0])) { + return false; + } + for (int i = 0; i < graph->n_nodes; ++i) { + const auto * consumer = graph->nodes[i]; + if (consumer->op != GGML_OP_MUL || std::memcmp(node->ne, consumer->ne, sizeof(node->ne)) != 0) { continue; } + 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 true; + } + } + } + return false; +} + int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { int op_case = 0; switch (node->op) { @@ -702,6 +739,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { break; } case GGML_OP_VIEW: { + if (!m_naive && !m_is_static && is_gdn_output_gate_view(node, m_cgraph)) { + return 5; + } if (is_sampling_view(node)) { return 3; } @@ -950,9 +990,114 @@ static const ggml_tensor * softmax_scores_source(const ggml_tensor * scores) { return scores; } -std::pair GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, bool is_static) { +std::vector GgmlOvDecoder::vision_reshape_pattern(const ggml_tensor * node) { + const auto * src = node->src[0]; + if (node->op == GGML_OP_CONT && std::memcmp(node->ne, src->ne, sizeof(node->ne)) == 0) { + // No reshape is emitted; all dimensions come directly from the input. + return {-2, -2, -2, -2}; + } + if (node->ne[2] == 1 && node->ne[3] == 1) { + return {1, 1, -1, node->ne[0]}; + } + if (node->op == GGML_OP_RESHAPE && src->op == GGML_OP_MUL_MAT && src->src[0] && + src->src[0]->op == GGML_OP_RESHAPE && src->src[0]->src[0]->op == GGML_OP_IM2COL && + node->ne[2] == 1 && node->ne[3] == src->ne[1]) { + // Unflatten patch convolution: [channels, 1, patch_height, patch_width]. + return {node->ne[3], 1, -2, -2}; + } + if (node->op == GGML_OP_RESHAPE && src->op == GGML_OP_CONT && src->ne[3] == 1 && + node->ne[0] == src->ne[0] && node->ne[1] == src->ne[1] && node->ne[2] * node->ne[3] == src->ne[2]) { + // Split rows into fixed-size merge groups while retaining both grid axes. + return {-2, node->ne[2], -2, node->ne[0]}; + } + if (node->op == GGML_OP_CONT && src->ne[3] == 1 && node->ne[3] == 1 && + node->ne[2] == src->ne[2] && node->ne[0] * node->ne[1] == src->ne[0] * src->ne[1]) { + // Merge adjacent patch features into each column; the feature width is fixed. + return {1, -2, -2, node->ne[0]}; + } + return {-2, -2, -2, -2}; +} + +bool GgmlOvDecoder::is_dynamic_vision_graph(const ggml_cgraph * cgraph) { + bool image_patches = false, vision_rope = false, attention = false; + // Recognize the operation patterns covered by the dynamic patch-encoder path. + // Reject language graphs before allocating the set used to check external sources. + for (int i = 0; i < cgraph->n_nodes; ++i) { + const auto * node = cgraph->nodes[i]; + switch (node->op) { + case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_PERMUTE: case GGML_OP_CONT: + case GGML_OP_VIEW: case GGML_OP_MUL_MAT: case GGML_OP_ADD: case GGML_OP_MUL: + case GGML_OP_NORM: case GGML_OP_RMS_NORM: case GGML_OP_UNARY: case GGML_OP_CPY: + break; + case GGML_OP_IM2COL: + if (node->op_params[6] != 1) { return false; } + image_patches |= node->src[1] && node->src[1]->op == GGML_OP_NONE && + (node->src[1]->flags & GGML_TENSOR_FLAG_INPUT); + break; + case GGML_OP_UPSCALE: + // Spatial position-grid interpolation; channel/batch resampling stays static. + if (node->ne[2] != node->src[0]->ne[2] || node->ne[3] != node->src[0]->ne[3]) { return false; } + break; + case GGML_OP_ROPE: + if (node->op_params[2] != GGML_ROPE_TYPE_VISION) { return false; } + vision_rope = true; + break; + case GGML_OP_FLASH_ATTN_EXT: + if (node->src[3] || node->src[4]) { return false; } + attention = true; + break; + default: + return false; + } + } + if (!image_patches || !vision_rope || !attention) { + return false; + } + std::unordered_set nodes; + nodes.reserve(cgraph->n_nodes); + for (int i = 0; i < cgraph->n_nodes; ++i) { + nodes.insert(cgraph->nodes[i]); + } + // Require declared inputs or weights at graph boundaries before enabling spatial reuse. + for (int i = 0; i < cgraph->n_nodes; ++i) { + for (const auto * src : cgraph->nodes[i]->src) { + if (!src || nodes.count(src)) { continue; } + const auto * root = src->view_src ? src->view_src : src; + if (!(root->flags & GGML_TENSOR_FLAG_INPUT) && + !(root->buffer && root->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { return false; } + } + } + return true; +} + +std::pair GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, + bool is_static, + bool dynamic_vision) { ModelParams model_params; ComputeParams compute_params; + model_params.is_dynamic_vision = !is_static && dynamic_vision; + if (model_params.is_dynamic_vision) { + for (int i = 0; i < cgraph->n_nodes; ++i) { + const auto * node = cgraph->nodes[i]; + const auto name = get_tensor_ov_name(cgraph, node); + const auto * root = node->view_src ? node->view_src : node; + const bool weight = root->buffer && root->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS; + if ((node->op == GGML_OP_RESHAPE || node->op == GGML_OP_CONT) && !weight) { + const auto shape = get_shape(node); + compute_params.vision_shapes["vision_shape_" + name] = {shape.begin(), shape.end()}; + } + if (node->op == GGML_OP_UPSCALE) { + compute_params.vision_shapes["vision_size_" + name] = {node->ne[1], node->ne[0]}; + if ((node->op_params[0] & 0xff) == GGML_SCALE_MODE_BILINEAR && + (node->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS)) { + compute_params.vision_projections["vision_y_" + name] = + ov::frontend::ggml::bilinear_antialias_projection(node->src[0]->ne[1], node->ne[1], false); + compute_params.vision_projections["vision_x_" + name] = + ov::frontend::ggml::bilinear_antialias_projection(node->src[0]->ne[0], node->ne[0], true); + } + } + } + } auto get_attention_pattern_case = [](const ggml_tensor * node) -> int { if (node == nullptr) { return -1; @@ -1492,6 +1637,11 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, ov::PartialShape input_shape; bool kv_layout_4d = false; + if (m_model_params.is_dynamic_vision && input && op->op == GGML_OP_IM2COL && + input == op->src[1]) { + return ov::PartialShape{input->ne[3], input->ne[2], -1, -1}; + } + if (is_inp_tok(input, op) || is_inp_pos(input, op)) { // tokens or positions int len = m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1; @@ -1706,6 +1856,22 @@ void GgmlOvDecoder::add_extra_inputs() { m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static, {}, -1}; }; + for (const auto & [name, shape] : m_compute_params.vision_shapes) { + m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{shape.size()}, 0, true, {}, -1}; + } + for (int i = 0; i < m_cgraph->n_nodes && !m_compute_params.vision_projections.empty(); ++i) { + const auto * node = m_cgraph->nodes[i]; + if (node->op != GGML_OP_UPSCALE) { continue; } + const auto name = get_tensor_ov_name(m_cgraph, node); + if (m_compute_params.vision_projections.count("vision_y_" + name) == 0) { continue; } + m_model_extra_inputs["vision_y_" + name] = {ov::element::f32, + ov::Shape{size_t(node->ne[1]), size_t(node->src[0]->ne[1])}, 0, true, {}, -1, + ov::PartialShape{-1, node->src[0]->ne[1]}}; + m_model_extra_inputs["vision_x_" + name] = {ov::element::f32, + ov::Shape{size_t(node->src[0]->ne[0]), size_t(node->ne[0])}, 0, true, {}, -1, + ov::PartialShape{node->src[0]->ne[0], -1}}; + } + if (m_compute_params.attention_size != -1) { create_1d_input("attention_size", m_compute_params.attention_size); } diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index f5e97efa3b0d..2085c1a36501 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -35,6 +35,7 @@ struct ModelParams { bool has_rs_rollback = false; bool mixed_rope_params = false; bool is_cacheless_attn = false; + bool is_dynamic_vision = false; // the graph writes a transposed V cache (`-fa off`: one value element per row, tokens along the row) bool v_trans = false; // the graph has FLASH_ATTN_EXT with logit soft-capping (gemma-2) @@ -140,6 +141,9 @@ struct ComputeParams { std::map sampling_rows; std::map gdn_attention_rows; std::map> recurrent_controls; + // GGML layout metadata that cannot be recovered after flattening a vision grid. + std::map> vision_shapes; + std::map> vision_projections; }; // defined below; declared here because GgmlOvDecoder uses it inline @@ -150,6 +154,12 @@ bool is_moe_expert_sum_add(const ggml_tensor * node); class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { public: + static bool is_dynamic_vision_graph(const ggml_cgraph * cgraph); + // OV order: -2 reads the runtime target; -1 infers one extent; nonnegative values are invariant. + static std::vector vision_reshape_pattern(const ggml_tensor * node); + std::vector get_vision_reshape_pattern(int node_idx) const override { + return vision_reshape_pattern(m_node_info_list[node_idx].node); + } static std::string get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor); struct NodeInfo { ggml_tensor * node; @@ -447,7 +457,10 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { void clear_model_weights() { m_model_weights.clear(); } - static std::pair compute_llm_params(ggml_cgraph * cgraph, bool is_static); + // The execution path supplies the structural vision classification once per compute. + static std::pair compute_llm_params(ggml_cgraph * cgraph, + bool is_static, + bool dynamic_vision = false); const ModelParams & get_model_params() const { return m_model_params; } @@ -526,7 +539,10 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { 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 && + // Gemma applies per-token scaling to supplied image embeddings. + const bool scaled_input = op->op == GGML_OP_MUL && (tensor->flags & GGML_TENSOR_FLAG_INPUT) && + is_inp_scale_rows(op->src[1], op); + return (op->op == GGML_OP_RMS_NORM || op->op == GGML_OP_L2_NORM || scaled_input) && op->src[0] == tensor && (tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY); } @@ -553,7 +569,10 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { // 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; + return tensor && op->op == GGML_OP_MUL && tensor == op->src[1] && + (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->type == GGML_TYPE_F32 && + tensor->ne[0] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1 && + op->src[0]->ne[1] == tensor->ne[1] && op->src[0]->ne[2] == 1 && op->src[0]->ne[3] == 1; } static bool is_rope_freqs_weight(const ggml_tensor * tensor, const ggml_tensor * op) { @@ -745,6 +764,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY; } + std::string get_position_input_ov_name(const ggml_tensor * tensor) const; + private: void set_input_output(); int compute_op_case(const ggml_tensor * node) const; diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 0fcc0e102b76..99409888078e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1542,12 +1542,20 @@ static bool is_supported_flash_attn_pattern(const ggml_tensor * op) { // PERMUTE -> RESHAPE -> base (view_src==nullptr) (whisper Q) // VIEW -> base (view_src==nullptr) (whisper K/V from kv_pad) // PERMUTE -> VIEW -> RESHAPE -> base (Q of a layer without RoPE, e.g. SmolLM3) + // PERMUTE -> ROPE (view_src==nullptr) (cacheless vision Q/K) + // PERMUTE -> RMS_NORM (view_src==nullptr) (Gemma4 vision V) for (int i = 0; i < 3; i++) { const ggml_tensor * src = op->src[i]; if (src->op == GGML_OP_PERMUTE) { if (src->src[0] == nullptr) { return false; } + if (src->src[0]->op == GGML_OP_ROPE && src->src[0]->view_src == nullptr) { + continue; + } + if (i == 2 && src->src[0]->op == GGML_OP_RMS_NORM && src->src[0]->view_src == nullptr) { + continue; + } // MLA: Q = PERMUTE -> CONCAT(q_nope_absorbed, q_pe); V = PERMUTE -> VIEW -> VIEW -> K cache // (V is the first kv_lora_rank values of each K cache row) if (i == 0 && src->src[0]->op == GGML_OP_CONCAT) { @@ -1588,6 +1596,13 @@ static bool is_gemma3n_flash_attn_pattern(const ggml_tensor * op) { return false; } + // Gemma4 vision rotates the two head halves with consecutive spatial RoPEs. + const auto * q = op->src[0]; + if (q->op == GGML_OP_PERMUTE && q->src[0]->op == GGML_OP_ROPE && + q->src[0]->src[0] && q->src[0]->src[0]->op == GGML_OP_ROPE) { + return false; + } + const ggml_tensor * q_base = op->src[0] != nullptr && op->src[0]->src[0] != nullptr ? op->src[0]->src[0]->src[0] : nullptr; const ggml_tensor * k_base = @@ -1992,8 +2007,11 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { break; } case GGML_OP_MUL_MAT: { - if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) { - return {false, "MUL_MAT with a BF16 or F32 src1 precision is not supported"}; + if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16) { + return {false, "MUL_MAT with a BF16 src1 precision is not supported"}; + } + if (ggml_prec_get_src(op, 1) == GGML_PREC_F32 && ggml_openvino_is_npu()) { + return {false, "MUL_MAT with F32 src1 precision requires CPU or GPU"}; } if (ggml_openvino_is_gpu() && op->src[0] != nullptr && op->src[1] != nullptr && ggml_is_quantized(op->src[0]->type) && strcmp(op->src[0]->name, "a") == 0 && diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 74ba8a1cecba..e4ed6e6cd89e 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -334,7 +334,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in. // Version 10 hashes only whether GGML_OPENVINO_PROFILING is 2 or more (it then compiles with enable_profiling), // and no longer GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS, which only changes the output bindings. - h = fnv1a_u64(h, 10); + // Version 11 honors explicit F32 MatMul input precision with node-level guards. + h = fnv1a_u64(h, 11); 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/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index 15a39f8166f8..4c4d3941d513 100644 --- a/ggml/src/ggml-openvino/openvino/decoder.h +++ b/ggml/src/ggml-openvino/openvino/decoder.h @@ -26,6 +26,7 @@ struct ModelExtraInputInfo { // 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; + // Optional model shape for runtime controls whose allocation changes per compute. PartialShape parameter_shape = PartialShape::dynamic(); }; @@ -135,6 +136,7 @@ class GgmlDecoder : public DecoderBase { virtual int is_swa_layer(int layer) const = 0; virtual int32_t get_op_dynamic_dim(int node_idx) const = 0; + virtual std::vector get_vision_reshape_pattern(int node_idx) const = 0; }; } // namespace ggml diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h index 51f7f63527be..d117267755cd 100644 --- a/ggml/src/ggml-openvino/openvino/node_context.h +++ b/ggml/src/ggml-openvino/openvino/node_context.h @@ -46,6 +46,7 @@ class NodeContext : public frontend::NodeContext { std::string get_output_name() const { return m_output_names[0]; } PartialShape get_output_shape() const { return m_decoder->get_output_shape(m_node_idx); } + std::vector get_vision_reshape_pattern() const { return m_decoder->get_vision_reshape_pattern(m_node_idx); } int32_t * get_input_op_params(size_t index) const { return m_decoder->get_input_op_params(m_node_idx, m_input_names[index]); @@ -120,9 +121,9 @@ class NodeContext : public frontend::NodeContext { auto base_it = m_tensor_map->find(base_name); // A multi-output translator can publish a VIEW directly without materializing // its packed parent (GatedDeltaNet attention/state). In that case the VIEW is the - // authoritative value. The node comparison retains the existing resolved-VIEW path. + // authoritative value. Compare output ports as well as nodes for resolved Split views. if (base_it == m_tensor_map->end() || - view_it->second.get_node_shared_ptr() != base_it->second.get_node_shared_ptr()) { + view_it->second != base_it->second) { return view_it->second; } return base_it->second; diff --git a/ggml/src/ggml-openvino/openvino/op/cont.cpp b/ggml/src/ggml-openvino/openvino/op/cont.cpp index 9888f6b93fd3..7ea7ee0833b7 100644 --- a/ggml/src/ggml-openvino/openvino/op/cont.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cont.cpp @@ -18,6 +18,16 @@ OutputVector translate_cont(const NodeContext & context) { auto src_shape = context.get_input_shape(0).to_shape(); auto dst_shape = context.get_output_shape().to_shape(); + if (context.has_input("vision_shape_" + context.get_name())) { + auto input = process_view_input_new(context, 0); + // CONT without a layout change already has its runtime shape. + if (src_shape == dst_shape) { + return rename_outputs_with_suffix({input}, context.get_name()); + } + auto target = vision_reshape_target(context); + return rename_outputs_with_suffix({std::make_shared(input, target, false)}, context.get_name()); + } + if (context.get_op_dynamic_dim() != -1) { dst_shape[3 - context.get_op_dynamic_dim()] = -1; } 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 ea223973f559..cd6ef1ac530d 100644 --- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp +++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp @@ -389,7 +389,9 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) { res = std::make_shared( sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3})); } else { - auto sdpa = std::make_shared(q, k, v, scale_node, causal); + // SDPA's fourth input is a mask; use a neutral mask to pass the requested scale as input five. + auto neutral_mask = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {0.0f}); + auto sdpa = std::make_shared(q, k, v, neutral_mask, scale_node, causal); res = std::make_shared( sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3})); } diff --git a/ggml/src/ggml-openvino/openvino/op/im2col.cpp b/ggml/src/ggml-openvino/openvino/op/im2col.cpp index 469d1de1f466..e278023820a0 100644 --- a/ggml/src/ggml-openvino/openvino/op/im2col.cpp +++ b/ggml/src/ggml-openvino/openvino/op/im2col.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include @@ -78,14 +80,13 @@ OutputVector translate_im2col(const NodeContext & context) { auto t1 = std::make_shared(patches, perm1); // [N, OH, OW, KH*KW*IC] → [N, OH, OW, KH*KW, IC] - const ov::Shape out_shape = t1->get_output_shape(0); - const size_t N = out_shape[0]; - const size_t OH = out_shape[1]; - const size_t OW = out_shape[2]; - auto reshape1_shape = ov::op::v0::Constant::create( - ov::element::i64, ov::Shape{5}, - std::vector{static_cast(N), static_cast(OH), static_cast(OW), - static_cast(KH * KW), static_cast(IC)}); + auto spatial_shape = std::make_shared( + std::make_shared(t1, ov::element::i64), + ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2}), + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto reshape1_shape = std::make_shared(ov::OutputVector{spatial_shape, + ov::op::v0::Constant::create(ov::element::i64, {2}, + std::vector{int64_t(KH * KW), int64_t(IC)})}, 0); auto r1 = std::make_shared(t1, reshape1_shape, false); // [N, OH, OW, KH*KW, IC] → [N, OH, OW, IC, KH*KW] @@ -93,13 +94,13 @@ OutputVector translate_im2col(const NodeContext & context) { auto t2 = std::make_shared(r1, perm2); // flatten back to [N, OH, OW, IC*KH*KW] - auto r2_shape = ov::op::v0::Constant::create( - ov::element::i64, ov::Shape{4}, - std::vector{static_cast(N), static_cast(OH), static_cast(OW), - static_cast(IC * KH * KW)}); + auto r2_shape = std::make_shared(ov::OutputVector{spatial_shape, + ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(IC * KH * KW)})}, 0); res = std::make_shared(t2, r2_shape, false); if (!is_2D) { + const auto out_shape = t1->get_output_shape(0); + const size_t N = out_shape[0], OW = out_shape[2]; // [N, 1, OW, IC * KW] -> [1, N, OW, IC * KW] auto final_reshape_shape = ov::op::v0::Constant::create( ov::element::i64, ov::Shape{4}, diff --git a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp index 45fc1a547390..4ef1c78712d6 100644 --- a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp +++ b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp @@ -1,6 +1,7 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" +#include "ggml.h" #include #include @@ -16,9 +17,13 @@ #include #include #include +#include #include namespace ov { +// Runtime SDKs omit the transformation header but export this helper. +OPENVINO_API void disable_conversion(const std::shared_ptr & node, const element::Type & to); + namespace frontend { namespace ggml { namespace op { @@ -33,10 +38,32 @@ OutputVector translate_mulmat(const NodeContext & context) { // the stateful V cache with `-fa off` is not transposed (see permute) const bool transpose_b = B.get_node()->get_rt_info().count(GGML_OV_V_TOKEN_MAJOR) == 0; - if (A.get_element_type() != B.get_element_type()) { + // MUL_MAT stores the minimum src1 precision in op_params[3]. + const auto * params = context.get_output_op_params(); + const bool preserve_f32 = params != nullptr && params[3] == GGML_PREC_F32; + if (preserve_f32) { + if (A.get_element_type() != ov::element::f32) { + A = std::make_shared(A, ov::element::f32); + } + if (B.get_element_type() != ov::element::f32) { + B = std::make_shared(B, ov::element::f32); + } + } else if (A.get_element_type() != B.get_element_type()) { B = std::make_shared(B, context.get_input_type(1)); } + auto make_matmul = [&](const ov::Output & a, const ov::Output & b) { + auto node = std::make_shared(a, b, false, transpose_b); + if (preserve_f32) { + // Keep this MatMul and its input layout/conversion paths in F32; other branches keep their precision. + ov::disable_conversion(node, ov::element::f16); + ov::disable_conversion(node, ov::element::bf16); + ov::mark_as_precision_sensitive(node->input(0)); + ov::mark_as_precision_sensitive(node->input(1)); + } + return node; + }; + auto B_shape = context.get_input_shape(0).to_shape(); auto A_shape = context.get_input_shape(1).to_shape(); int64_t A_batch = A_shape[1]; @@ -68,7 +95,7 @@ OutputVector translate_mulmat(const NodeContext & context) { A_reshape->get_input_partial_shape(0)[1] == batch_small) { A_grouped = A_reshape->input_value(0); } - ov::Output res = std::make_shared(A_grouped, B, false, transpose_b); + ov::Output res = make_matmul(A_grouped, B); res = std::make_shared( res, ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{0, batch_large, -1, 0}), true); @@ -107,7 +134,7 @@ OutputVector translate_mulmat(const NodeContext & context) { A = Z; } - ov::Output res = std::make_shared(A, B, false, transpose_b); + ov::Output res = make_matmul(A, B); const auto output_type = context.get_output_type(); if (res.get_element_type() != output_type) { diff --git a/ggml/src/ggml-openvino/openvino/op/reshape.cpp b/ggml/src/ggml-openvino/openvino/op/reshape.cpp index 203d3d396d54..c2d0ff8079c1 100644 --- a/ggml/src/ggml-openvino/openvino/op/reshape.cpp +++ b/ggml/src/ggml-openvino/openvino/op/reshape.cpp @@ -19,6 +19,11 @@ namespace op { OutputVector translate_reshape(const NodeContext & context) { num_inputs_check(context, 1, 1); + if (context.has_input("vision_shape_" + context.get_name())) { + auto target = vision_reshape_target(context); + auto res = std::make_shared(context.get_input(0), target, false); + return rename_outputs_with_suffix({res}, context.get_name()); + } if (context.get_input(0).get_partial_shape().is_static() && context.get_input_shape(0) == context.get_output_shape()) { return {context.get_input(0)}; diff --git a/ggml/src/ggml-openvino/openvino/op/upscale.cpp b/ggml/src/ggml-openvino/openvino/op/upscale.cpp index 03f3a91b2e61..e9050e0399fb 100644 --- a/ggml/src/ggml-openvino/openvino/op/upscale.cpp +++ b/ggml/src/ggml-openvino/openvino/op/upscale.cpp @@ -26,7 +26,8 @@ OutputVector translate_upscale(const NodeContext & context) { const auto input_shape = context.get_input_shape(0).to_shape(); const auto output_shape = context.get_output_shape().to_shape(); - if (input_shape == output_shape) { + const bool dynamic = context.has_input("vision_size_" + context.get_name()); + if (!dynamic && input_shape == output_shape) { return rename_outputs_with_suffix({input}, context.get_name()); } @@ -49,7 +50,7 @@ OutputVector translate_upscale(const NodeContext & context) { } // Spatial interpolation for ne[1] and ne[0] (OV axes 2 and 3) - if (input_shape[2] != output_shape[2] || input_shape[3] != output_shape[3]) { + if (dynamic || input_shape[2] != output_shape[2] || input_shape[3] != output_shape[3]) { const int32_t * op_params = context.get_output_op_params(); const int32_t mode_flags = op_params != nullptr ? op_params[0] : 0; @@ -63,65 +64,17 @@ OutputVector translate_upscale(const NodeContext & context) { const size_t H_out = output_shape[2]; const size_t W_out = output_shape[3]; - const float pixel_offset = 0.5f; - - // Height projection: [H_out, H_in] - std::vector Wy_data(H_out * H_in, 0.0f); - const float sf1 = static_cast(H_out) / H_in; - const float support1 = std::max(1.0f, 1.0f / sf1); - const float invscale1 = 1.0f / support1; - - for (size_t i1 = 0; i1 < H_out; ++i1) { - const float y = (static_cast(i1) + pixel_offset) / sf1; - const auto y_start = static_cast(y - support1 + pixel_offset); - const size_t y_min = y_start > 0 ? static_cast(y_start) : 0; - const auto y_end = static_cast(y + support1 + pixel_offset); - const size_t y_max = y_end > 0 ? std::min(static_cast(y_end), H_in) : 0; - - float total_weight = 0.0f; - for (size_t sy = y_min; sy < y_max; ++sy) { - float diff = std::abs((static_cast(sy) - y + pixel_offset) * invscale1); - float weight = std::max(1.0f - diff, 0.0f); - Wy_data[i1 * H_in + sy] = weight; - total_weight += weight; - } - if (total_weight > 0.0f) { - for (size_t sy = y_min; sy < y_max; ++sy) { - Wy_data[i1 * H_in + sy] /= total_weight; - } - } + ov::Output Wy_node, Wx_node; + if (dynamic) { + Wy_node = context.get_input("vision_y_" + context.get_name()); + Wx_node = context.get_input("vision_x_" + context.get_name()); + } else { + Wy_node = ov::op::v0::Constant::create(ov::element::f32, {H_out, H_in}, + bilinear_antialias_projection(H_in, H_out, false)); + Wx_node = ov::op::v0::Constant::create(ov::element::f32, {W_in, W_out}, + bilinear_antialias_projection(W_in, W_out, true)); } - // Width projection: [W_in, W_out] - std::vector Wx_data(W_in * W_out, 0.0f); - const float sf0 = static_cast(W_out) / W_in; - const float support0 = std::max(1.0f, 1.0f / sf0); - const float invscale0 = 1.0f / support0; - - for (size_t i0 = 0; i0 < W_out; ++i0) { - const float x = (static_cast(i0) + pixel_offset) / sf0; - const auto x_start = static_cast(x - support0 + pixel_offset); - const size_t x_min = x_start > 0 ? static_cast(x_start) : 0; - const auto x_end = static_cast(x + support0 + pixel_offset); - const size_t x_max = x_end > 0 ? std::min(static_cast(x_end), W_in) : 0; - - float total_weight = 0.0f; - for (size_t sx = x_min; sx < x_max; ++sx) { - float diff = std::abs((static_cast(sx) - x + pixel_offset) * invscale0); - float weight = std::max(1.0f - diff, 0.0f); - Wx_data[sx * W_out + i0] = weight; - total_weight += weight; - } - if (total_weight > 0.0f) { - for (size_t sx = x_min; sx < x_max; ++sx) { - Wx_data[sx * W_out + i0] /= total_weight; - } - } - } - - auto Wy_node = ov::op::v0::Constant::create(ov::element::f32, {H_out, H_in}, Wy_data); - auto Wx_node = ov::op::v0::Constant::create(ov::element::f32, {W_in, W_out}, Wx_data); - auto res_y = std::make_shared(Wy_node, res); res = std::make_shared(res_y, Wx_node); } else { @@ -163,7 +116,8 @@ OutputVector translate_upscale(const NodeContext & context) { static_cast(output_shape[3]) / static_cast(input_shape[3]), }; - auto target_shape_node = ov::op::v0::Constant::create(ov::element::i64, {2}, target_shape_vec); + ov::Output target_shape_node = dynamic ? context.get_input("vision_size_" + context.get_name()) : + ov::op::v0::Constant::create(ov::element::i64, {2}, target_shape_vec); auto scales_node = ov::op::v0::Constant::create(ov::element::f32, {2}, scales_vec); auto axes_node = ov::op::v0::Constant::create(ov::element::i64, {2}, {2, 3}); diff --git a/ggml/src/ggml-openvino/openvino/op/view.cpp b/ggml/src/ggml-openvino/openvino/op/view.cpp index 4ebe9c4b483a..eb4630bcb116 100644 --- a/ggml/src/ggml-openvino/openvino/op/view.cpp +++ b/ggml/src/ggml-openvino/openvino/op/view.cpp @@ -16,6 +16,17 @@ namespace op { OutputVector translate_view(const NodeContext & context) { num_inputs_check(context, 1, 1); + if (context.get_op_case() == 5) { + const auto shape = context.get_output_shape(); + // Keep the output gate grouped like GDN: [active sequences, tokens per sequence, heads, width]. + auto target = 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].get_length(), shape[3].get_length()})}, 0); + return rename_outputs_with_suffix({std::make_shared(context.get_input(0), target, false)}, + context.get_name()); + } + 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, diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index 0a5d5b8c05cf..23402b0a141f 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -38,6 +38,48 @@ namespace ov { namespace frontend { namespace ggml { +ov::Output vision_reshape_target(const NodeContext & context) { + auto runtime = context.get_input("vision_shape_" + context.get_name()); + const auto pattern = context.get_vision_reshape_pattern(); + ov::OutputVector dimensions; + for (size_t axis = 0; axis < pattern.size(); ++axis) { + if (pattern[axis] == -2) { + dimensions.push_back(std::make_shared(runtime, + ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(axis)}), + ov::op::v0::Constant::create(ov::element::i64, {}, {0}))); + } else { + dimensions.push_back(ov::op::v0::Constant::create(ov::element::i64, {1}, {pattern[axis]})); + } + } + return std::make_shared(dimensions, 0); +} + +std::vector bilinear_antialias_projection(size_t input_size, size_t output_size, bool transpose) { + std::vector weights(input_size * output_size, 0.0f); + const float scale = static_cast(output_size) / input_size; + const float support = std::max(1.0f, 1.0f / scale); + const float invscale = 1.0f / support; + for (size_t out = 0; out < output_size; ++out) { + const float center = (static_cast(out) + 0.5f) / scale; + const auto start = static_cast(center - support + 0.5f); + const auto end = static_cast(center + support + 0.5f); + const size_t begin = start > 0 ? static_cast(start) : 0; + const size_t finish = end > 0 ? std::min(end, input_size) : 0; + float sum = 0.0f; + for (size_t in = begin; in < finish; ++in) { + const float weight = std::max(1.0f - std::abs((static_cast(in) - center + 0.5f) * invscale), 0.0f); + weights[transpose ? in * output_size + out : out * input_size + in] = weight; + sum += weight; + } + if (sum > 0.0f) { + for (size_t in = begin; in < finish; ++in) { + weights[transpose ? in * output_size + out : out * input_size + in] /= sum; + } + } + } + return weights; +} + void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs) { auto input_size = context.get_input_size(); FRONT_END_OP_CONVERSION_CHECK(input_size >= min_inputs, "Got less inputs than expected"); @@ -558,6 +600,14 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return std::make_shared(part, target, false); } + // A translated VIEW is authoritative; packed-projection slicing applies only to its unresolved base. + const auto view_name = context.get_view_input_name(input_index, 0); + const auto base_name = context.get_view_input_src_name(input_index, view_input_size - 1); + if (context.has_input(view_name) && + (!context.has_input(base_name) || context.get_input(view_name) != context.get_input(base_name))) { + 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 && input.get_element_type().is_real()) { @@ -591,8 +641,7 @@ ov::Output process_view_input_new(const NodeContext & context, int inp } } - if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real() && - context.has_input("s_copy_active_slot_len")) { + 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); diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index 499596e6f14b..194f08be5e76 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -21,6 +21,9 @@ std::shared_ptr get_dimensions(const std::shared_ptr & node, OutputVector rename_outputs_with_suffix(const OutputVector & outputs, const std::string & suffix); +std::vector bilinear_antialias_projection(size_t input_size, size_t output_size, bool transpose); +ov::Output vision_reshape_target(const NodeContext & context); + std::pair, ov::Output> make_sin_cos(int32_t * rope_params, std::shared_ptr inp_pos, std::shared_ptr rope_freqs_weight = nullptr, diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 9470302a7efa..8f833c93b05c 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -218,8 +218,8 @@ static size_t get_static_attention_size(const std::shared_ptr & g static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) { const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); - // Preserve the fingerprint for graphs compiled without the old native cache update ops. - uint64_t extra_cfg = 18 * 131; + // Vision graphs carry runtime spatial shapes and independent position inputs. + uint64_t extra_cfg = 19 * 131; 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_ENABLE_KV_4D") > 0 ? 1u : 0u); @@ -309,9 +309,11 @@ static std::string compiled_graph_key(const ggml_cgraph * graph, for (const auto & input : decoder.get_model_extra_inputs()) { append_string(input.first); append_string(input.second.type.get_type_name()); - append(input.second.shape.size()); - for (auto dim : input.second.shape) { - append(dim); + if (input.second.parameter_shape.rank().is_static()) { + append_string(input.second.parameter_shape.to_string()); + } else { + append(input.second.shape.size()); + for (auto dim : input.second.shape) { append(dim); } } append(input.second.is_parameter); if (!input.second.is_parameter) { @@ -336,7 +338,7 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph, append(value.size()); key.append(value); }; - graph_key graph_id(graph, true); + graph_key graph_id(graph, true, params.is_dynamic_vision); append(graph_id.n_nodes); append(graph_id.n_leaves); append_string(graph_id.first_node_name); @@ -767,7 +769,13 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod } } input_tensor = cached; - if (param_name == "sampling_rows") { + if (param_name.compare(0, 13, "vision_shape_") == 0 || param_name.compare(0, 12, "vision_size_") == 0) { + const auto & values = ggml_decoder->get_compute_params().vision_shapes.at(param_name); + std::copy(values.begin(), values.end(), input_tensor.data()); + } else if (param_name.compare(0, 9, "vision_y_") == 0 || param_name.compare(0, 9, "vision_x_") == 0) { + const auto & values = ggml_decoder->get_compute_params().vision_projections.at(param_name); + std::copy(values.begin(), values.end(), input_tensor.data()); + } else if (param_name == "sampling_rows") { auto * data = input_tensor.data(); for (const auto & row : ggml_decoder->get_compute_params().sampling_rows) { *data++ = row.second; @@ -1249,7 +1257,8 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share // graph_key first (a few hundred us), and if the same key is already in decoder_cache // we know the graph is not splitted (only not-splitted graphs get inserted there). const int64_t cache_key_start_time = ggml_time_us(); - graph_key key(cgraph); + const bool dynamic_vision = GgmlOvDecoder::is_dynamic_vision_graph(cgraph); + graph_key key(cgraph, false, dynamic_vision); const int64_t cache_key_compute_time = ggml_time_us() - cache_key_start_time; int64_t cache_lookup_time = 0; bool key_seen = false; @@ -1279,7 +1288,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share ModelParams m_params; ComputeParams c_params; const int64_t graph_param_compute_start_time = ggml_time_us(); - std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static); + std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static, dynamic_vision); const int64_t graph_param_compute_time = ggml_time_us() - graph_param_compute_start_time; const bool cache_enabled = !model_is_splitted && !cache_disabled; diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 3db84a2541a7..c0b263f6fbd8 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -1,6 +1,7 @@ #include "ggml-decoder.h" #include "ggml-impl.h" #include "ggml-openvino-extra.h" +#include "ggml-openvino.h" #include "model-cache.h" #include @@ -23,24 +24,50 @@ // 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 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. +// always included, along with weight allocation generations. Static or unqualified image graphs +// also include input shapes. 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; - // External source descriptors "::" and sampler row Parameter names. + // External source descriptors, sampler row names and image shapes. std::vector input_srcs; + // Process-local identities used only by the private cache key. + std::vector weight_buffer_ids; - graph_key(const ggml_cgraph * cgraph, bool include_inputs = false) : n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) { + graph_key(const ggml_cgraph * cgraph, bool include_inputs = false, bool dynamic_vision = false) : + n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) { if (n_nodes > 0) { first_node_name = cgraph->nodes[0]->name; last_node_name = cgraph->nodes[n_nodes - 1]->name; } + std::unordered_set weight_buffers; for (int i = 0; i < n_nodes; ++i) { const auto * node = cgraph->nodes[i]; + if (node->op == GGML_OP_MUL_MAT && ggml_prec_get_src(node, 1) == GGML_PREC_F32) { + // Node precision guards are part of the compiled graph, including in the dynamic disk cache. + input_srcs.push_back("f32_matmul_" + std::to_string(i)); + } + // A later model load may use the same graph names and shapes but new + // weights. Allocation generations survive pointer reuse, whereas + // the lightweight topology key alone would select stale Constants. + for (const auto * src : node->src) { + if (!src) { + continue; + } + const auto * root = src->view_src ? src->view_src : src; + const auto buffer = root->buffer; + if (buffer && buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && + weight_buffers.insert(buffer).second) { + const auto id = ggml_backend_openvino_buffer_get_ctx_id(buffer); + if (id != 0) { + weight_buffer_ids.push_back(id); + } + } + } if (GgmlOvDecoder::is_sampling_view(node)) { input_srcs.push_back("sampling_row_" + std::string(node->name) + "#n" + std::to_string(i)); } @@ -49,6 +76,24 @@ struct graph_key { if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { input_srcs.push_back("output_" + std::string(node->name) + "#n" + std::to_string(i)); } + // Qualified vision graphs reuse a fixed model configuration; only spatial sizes vary. + // Static or unqualified image graphs keep their full input shape in the key. + if (!dynamic_vision && (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_2D_DW || + node->op == GGML_OP_IM2COL) && node->src[1] != nullptr) { + const auto * input = node->src[1]; + const auto * root = input->view_src ? input->view_src : input; + // Gemma4 normalizes image pixels with SCALE before patch extraction. + while (root->op == GGML_OP_SCALE && root->src[0]) { + root = root->src[0]->view_src ? root->src[0]->view_src : root->src[0]; + } + if (root->flags & GGML_TENSOR_FLAG_INPUT) { + std::string shape = "image_input_" + std::to_string(i) + ":" + root->name; + for (int dim = 0; dim < GGML_MAX_DIMS; ++dim) { + shape += ":" + std::to_string(root->ne[dim]); + } + input_srcs.push_back(std::move(shape)); + } + } } static const bool full_key = ggml_openvino_getenv_int("GGML_OPENVINO_FULL_GRAPH_KEY") != 0; @@ -78,7 +123,8 @@ struct graph_key { bool operator==(const graph_key & other) const { return n_nodes == other.n_nodes && n_leaves == other.n_leaves && first_node_name == other.first_node_name && - last_node_name == other.last_node_name && input_srcs == other.input_srcs; + last_node_name == other.last_node_name && input_srcs == other.input_srcs && + weight_buffer_ids == other.weight_buffer_ids; } }; @@ -93,6 +139,9 @@ struct graph_key_hash { for (const auto & s : key.input_srcs) { hash ^= std::hash{}(s) + 0x9e3779b9 + (hash << 6) + (hash >> 2); } + for (const auto id : key.weight_buffer_ids) { + hash ^= std::hash{}(id) + 0x9e3779b9 + (hash << 6) + (hash >> 2); + } return hash; } };