diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index 347c24f4f526..3ed43b9fab27 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -31,3 +31,20 @@ if (GGML_OPENVINO) message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}") endif() endif() + +# Released runtimes retain the ordinary cache translators. +include(CheckCXXSourceCompiles) +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 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_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 e8cd8dd1554c..946be24b3688 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -1,3 +1,40 @@ +# Qwen MTP + +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 the implementation and the MTP sampling graph. + +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. + +Stateless recurrent execution uses the same reset, reorder, and partial cache-writeback paths at every slot capacity, including one slot without MTP. + +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. +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 cache decomposition. +Snapshot GDN still uses the independent Update op with a temporary cache bank. +Ordinary GDN is unchanged. Snapshot/rollback (speculative decoding) on OpenVINO +requires the patched package; unpatched packages support ordinary execution and +report snapshot GDN as unsupported, allowing fallback to another backend. +Rebuild both repos for these native ops. The current backend translation revision is 14; 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 +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. Unified KV is recommended for multi-slot GPU +execution because it enables this in-place attention update. + +The recommended Qwen3.6-35B-A3B Q4_K_M setup uses GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). See [attention KV layout](dev_doc/OPENVINO-RECURRENT-CACHE.md#attention-kv-layout) for eligibility. + +`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 [implementation guide](dev_doc/OPENVINO-RECURRENT-CACHE.md) for buffer ownership and rollback. + # 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. @@ -7,7 +44,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_KV_SLICE=0 \ 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 @@ -20,7 +56,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_KV_SLICE=0 \ GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ @@ -29,10 +64,22 @@ 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_EXACT_ZERO_POINT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_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_EXACT_ZERO_POINT`, `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_KV_SLICE` is a runtime binding option for dynamic graphs 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. +## 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. + +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 - Cache-only mode requires Linux or Windows and mmap loading (`--load-mode mmap`, or the default when all selected devices support mmap). Do not use tensor validation or mlock when trying to avoid weight reads. 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..ef50e153d0e2 --- /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. + +The captures used cache-only mode, four slots, context 8192 and the default two-token MTP settings. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md new file mode 100644 index 000000000000..65cd3d6cbfa3 --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -0,0 +1,54 @@ +# Current Qwen GPU implementation + +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 reference model is the UD Qwen3.6-35B-A3B MTP GGUF. + +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 14. + +## Buffer ownership and operation boundaries + +| 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 | + +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. + +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. + +`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. + +## Generic fallback and restrictions + +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. + +`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary cache decomposition for diagnosis. Naive graphs skip full-model recurrence fusion setup. Unmatched/naive snapshot GDN uses the independent Update op with a temporary cache bank; ordinary GDN remains unchanged. Snapshot/rollback (speculative decoding) on OpenVINO requires a patched runtime/GPU plugin. Unpatched packages reject snapshot GDN with a warning and allow scheduler fallback to another backend. 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. + +## Attention KV layout + +`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. + +Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). 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. + +## Stable MTP sampling + +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. + +One compatible draft graph is shared across active subsets. Trunk and genuinely different graph stages/configurations remain separate. Prepare a compatible revision-14 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 + +Native OV tests cover shape/attribute serialization, reset, cycles, duplicates, overlapping writes, mixed precision, changing shapes, aliased/distinct buffers, exclusive Reshapes, shared readers, host/device USM and export/import. Convolution is checked against a host reference; GDN uses an independent cache mapping around ordinary GDN. See `docs/dev/qwen35-llamacpp-recurrent-cache.md` and `recurrent_cache_update.cpp` in the OV checkout for contracts and tests. + +## Debugging and source map + +- `ggml-decoder.cpp`: dynamic dimensions, control inputs, output names and `cgraph_ov.txt` dump. +- `utils.cpp`: compute-branch filtering, compiled reuse and input/output binding. +- `openvino/recurrent_cache_fusion.cpp`: structural pattern matching and native Update op translation. +- `openvino/translate_session.cpp`: runtime sampling aliases and model construction. +- OV `recurrent_cache_update` implementation: mutation eligibility, source staging and GPU computation. + +`GGML_OPENVINO_DUMP_CGRAPH=1` dumps the raw graph before filtering. It includes COMPUTE/OUTPUT flags and byte offsets and overwrites `cgraph_ov.txt` on each call. Enable dumps only for diagnosis; use the captured examples for a static view. GPU profiles and OpenCL copy traces add overhead, and lack of an explicit copy call does not prove zero traffic inside a kernel. diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md new file mode 100644 index 000000000000..6ac9ba3bce53 --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/README.md @@ -0,0 +1,7 @@ +# OpenVINO Qwen development documentation + +The default supported Qwen3.5/Qwen3.6 GPU path is **dynamic stateless execution with in-place fused recurrent ops and stable MTP sampling**. Unified KV is the recommended multi-slot layout because it enables native in-place attention KV updates. No new inference switch is needed for the recurrent/sampling default. + +- [Backend setup and cache usage](../README.md): runtime requirements, environment settings and restrictions. +- [Implementation](OPENVINO-RECURRENT-CACHE.md): buffer ownership, fusion, rollback, fallback and source map. +- [Multislot MTP graph](MTP-SAMPLING-GRAPH.md): why active-slot variants occurred and how stable translation works. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 73055fc942b5..d88cd81a0a50 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(); @@ -125,12 +139,6 @@ bool is_same_shape(const ggml_tensor * a, const ggml_tensor * b) { bool is_conv_states_all_tensor(const ggml_tensor * tensor) { return tensor != nullptr && strncmp(tensor->name, "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 @@ -184,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); @@ -340,12 +348,35 @@ 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) { + // The post-GDN projection rejoins the flat token stream. + return node->ne[2] == 1 ? 5 : 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) { @@ -355,6 +386,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) { @@ -471,16 +517,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; @@ -511,8 +552,17 @@ 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 (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; break; @@ -574,8 +624,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) { @@ -632,15 +681,16 @@ 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) { - // 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; + 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) { + // 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) { @@ -648,16 +698,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) @@ -696,7 +745,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; } @@ -1107,6 +1156,23 @@ 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->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]; + 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) { @@ -1115,7 +1181,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 @@ -1126,7 +1192,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]; @@ -1139,17 +1207,20 @@ 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); if (is_conv) { 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]; } } @@ -1180,7 +1251,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)) { @@ -1225,6 +1296,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}; @@ -1435,7 +1509,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 @@ -1447,6 +1521,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 @@ -1462,6 +1543,70 @@ 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); + } + } +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE + m_compute_params.recurrent_controls.clear(); + // Naive graphs have no full-model cache fusion and node cases are not initialized here. + if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && + !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; + 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}; + } + } + 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 + 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); } } @@ -1555,6 +1700,22 @@ void GgmlOvDecoder::compute_model_inputs() { note_kvcache_4d(src, node, m_model_inputs[src_name].shape); } } + if (!m_naive && !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() { @@ -1566,13 +1727,29 @@ 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; } + 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); + } + 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. - 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 { @@ -1956,6 +2133,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++) { @@ -2263,9 +2443,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++) { @@ -2282,6 +2475,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}; } } @@ -2290,7 +2486,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; @@ -2406,6 +2607,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; @@ -2463,6 +2668,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. @@ -2510,7 +2724,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; } @@ -2584,29 +2798,19 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { } break; case GGML_OP_CONCAT: { - // a dynamic dim of a source that is not the concat axis stays valid in the result + const int axis = node->op_params[0]; const int src0_dynamic_dim = m_node_dynamic_dims[node->src[0]]; const int src1_dynamic_dim = m_node_dynamic_dims[node->src[1]]; - // sources should agree; on conflict keep src[0] but show warning - if (src0_dynamic_dim != -1 && src1_dynamic_dim != -1 && src0_dynamic_dim != src1_dynamic_dim) { + if (src0_dynamic_dim != -1 && src0_dynamic_dim != axis && + src1_dynamic_dim != -1 && src1_dynamic_dim != axis && src0_dynamic_dim != src1_dynamic_dim) { GGML_LOG_WARN("ggml-openvino: different dynamic dims for CONCAT node '%s', src[0]: '%s', src[1]: '%s'\n", node->name, node->src[0]->name, node->src[1]->name); } - int src_dynamic_dim = -1; - for (int s = 0; s < 2 && src_dynamic_dim == -1; s++) { - auto it = m_node_dynamic_dims.find(node->src[s]); - if (it != m_node_dynamic_dims.end()) { - src_dynamic_dim = it->second; - } - } - if (src_dynamic_dim != -1) { - m_node_dynamic_dims[node] = src_dynamic_dim; - break; - } - // no source is dynamic: fall back to the dim that grew (the concat axis) - for (int i = 0; i < GGML_MAX_DIMS; i++) { - if (node->src[0]->ne[i] != node->ne[i]) { - m_node_dynamic_dims[node] = i; + 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; } } @@ -2626,6 +2830,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 599a6c1201a7..503ce24de80d 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -117,11 +117,16 @@ 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; + 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 @@ -149,6 +154,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, @@ -437,6 +444,12 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { 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; + std::map runtime_output_scratch; + bool m_is_static = false; bool m_is_stateful = false; bool m_is_prefill = false; @@ -472,6 +485,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]); @@ -498,6 +520,67 @@ 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; + } + + 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) { return is_recurrent_cache(tensor) || is_kvcache(tensor, op); } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index f41bef13e334..8e3134b712ca 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -144,6 +144,7 @@ void ggml_openvino_device_config::init() { "GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS", "GGML_OPENVINO_ENABLE_CACHE", "GGML_OPENVINO_DISABLE_CACHE", + "GGML_OPENVINO_DISABLE_FUSED_RECURRENCE", "GGML_OPENVINO_ENABLE_KV_4D", "GGML_OPENVINO_ENABLE_FALLBACK", "GGML_OPENVINO_KV_SCATTER_ELEMENTS", @@ -433,12 +434,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. @@ -459,6 +461,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; + } if (tensor->type == GGML_TYPE_Q5_0) { //return ExtraQuantType::Q4_0_128; return ExtraQuantType::Q4_0_64; @@ -728,7 +737,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, + 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.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 097c65fca7eb..0ca114dc9b0c 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -457,8 +457,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, (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); } @@ -594,8 +594,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, (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); } @@ -642,8 +642,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, (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); } @@ -672,7 +672,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, 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); return false; @@ -684,7 +685,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, 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); return false; @@ -1417,7 +1420,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) { @@ -1485,6 +1489,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"}; @@ -1781,9 +1791,19 @@ 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) { +#ifndef GGML_OPENVINO_HAS_CACHE_UPDATE + static std::atomic_flag warned = ATOMIC_FLAG_INIT; + if (!warned.test_and_set()) { + GGML_LOG_WARN("OpenVINO snapshot/rollback (speculative decoding) is not supported by this package; " + "a patched OpenVINO package with recurrent cache-update ops is required.\n"); + } + return {false, "GATED_DELTA_NET snapshots require a patched OpenVINO package"}; +#else + if (!ggml_openvino_is_gpu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC")) { + return {false, "GATED_DELTA_NET snapshots require dynamic GPU execution"}; + } +#endif } break; } @@ -1998,7 +2018,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/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index e91153fa2cb6..8f77b28f05d5 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -173,7 +173,8 @@ bool ggml_openvino_model_cache_only() { static const char * cache_settings[] = { "GGML_OPENVINO_REQUANT_KQUANT", "GGML_OPENVINO_NATIVE_SOFTPLUS", - "GGML_OPENVINO_KV_SLICE", + // GGML_OPENVINO_KV_SLICE only changes dynamic runtime bindings. Dynamic + // attention graphs accept either shape and share the same compiled blob. "GGML_OPENVINO_MANUAL_GQA_ATTN", "GGML_OPENVINO_EXACT_ZERO_POINT", "GGML_OPENVINO_STATEFUL_EXECUTION", @@ -352,7 +353,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; - h = fnv1a_u64(h, 2); + // 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/argsort.cpp b/ggml/src/ggml-openvino/openvino/op/argsort.cpp index dd0872516758..a3ae09fbd98a 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,52 @@ 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. + // 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::SORT_VALUES, 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::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}), + 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..31605ca54126 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -1,7 +1,6 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" - #include #include #include @@ -12,7 +11,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -34,6 +35,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); @@ -73,10 +113,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) { @@ -90,24 +129,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}); @@ -117,15 +145,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] @@ -145,9 +170,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); @@ -181,20 +209,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()); } - 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})); + 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); @@ -209,16 +233,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/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); 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 67f1ebf2a451..724deb521eeb 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_CACHE_UPDATE +#include "recurrent_cache_update.hpp" +#endif #include "ggml-openvino/ggml-openvino-extra.h" #include @@ -20,11 +23,15 @@ #include #include #include +#include #include +#include #include #include -#include +#include +#include #include +#include #include #include #include @@ -92,7 +99,52 @@ static bool match_gdn_l2_norm(const Output & normalized, Output & in return true; } -OutputVector translate_gated_delta_net(const NodeContext & context) { +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE +static OutputVector translate_gdn_snapshots(const Output & q, + const Output & k, + const Output & v, + const Output & state, + const Output & g, + const Output & beta, + int64_t features, + bool norm, + float q_eps, + float k_eps, + int64_t snapshot_count) { + // Standalone/unmatched graphs have no full-model cache controls. Use a temporary + // bank in GGML [head,value,key] order instead of extending ordinary GDN semantics. + auto i64 = [](const Shape & shape, const std::vector & values) { + return ov::op::v0::Constant::create(ov::element::i64, shape, values); + }; + auto shape = std::make_shared(q, ov::element::i64); + auto batch = std::make_shared(shape, i64({1}, {0}), i64({}, {0})); + auto tokens = std::make_shared(shape, i64({1}, {1}), i64({}, {0})); + auto initial = std::make_shared(state, i64({4}, {1, 1, -1, features}), false); + auto spare_rows = std::make_shared(batch, i64({1}, {snapshot_count - 1})); + auto spare_shape = std::make_shared( + OutputVector{i64({2}, {1, 1}), spare_rows, i64({1}, {features})}, 0); + auto spare = std::make_shared( + ov::op::v0::Constant::create(state.get_element_type(), {}, {0}), spare_shape); + auto cache = std::make_shared(OutputVector{initial, spare}, 2); + auto rows = std::make_shared( + i64({}, {0}), std::make_shared(batch), i64({}, {1}), ov::element::i64); + auto active = std::make_shared(rows, i64({4}, {1, 1, 1, -1}), false); + auto control = std::make_shared( + std::make_shared(OutputVector{i64({1}, {0}), batch, batch, i64({1}, {0})}, 0), + i64({4}, {1, 1, 1, 4}), false); + auto update = std::make_shared( + OutputVector{q, k, v, cache, g, beta, active, i64({1, 1, 1, 0}, {}), + i64({1, 1, 1, 1}, {0}), i64({1, 1, 1, 1}, {0}), i64({1, 1, 1, 2}, {0, 0}), control}, + norm, q_eps, k_eps, snapshot_count); + auto valid_rows = std::make_shared( + std::make_shared(tokens, i64({1}, {snapshot_count})), batch); + auto snapshots = std::make_shared( + update->output(1), i64({1}, {0}), valid_rows, i64({1}, {1}), i64({1}, {2})); + return {update->output(0), snapshots}; +} +#endif + +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] @@ -107,6 +159,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); @@ -152,7 +205,9 @@ 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); + if (!cache_inputs && snapshot_count == 1) { + 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})); @@ -183,33 +238,75 @@ 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 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; +#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()); + 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) { + return {fused->output(0), fused->output(0), fused->output(1)}; + } + return {fused->output(0), fused->output(1)}; + } +#endif + + Output attn_4d, states; + if (snapshot_count > 1) { +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE + auto outputs = translate_gdn_snapshots(q, k, v, state, g, beta, H_v * S_v * q_shape[3], + fuse_qk_l2norm, q_eps, k_eps, snapshot_count); + attn_4d = outputs[0]; + states = outputs[1]; +#else + FRONT_END_OP_CONVERSION_CHECK(false, + "GATED_DELTA_NET snapshot/rollback requires a patched OpenVINO package"); +#endif + } else { + auto gdn = std::make_shared( + q, k, v, state, g, beta, fuse_qk_l2norm, q_eps, k_eps); + attn_4d = gdn->output(0); + states = std::make_shared(gdn->output(1), state_perm); + } - // 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) { // 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. - return rename_outputs_with_suffix({attn_4d, state_transposed}, context.get_name()); + return rename_outputs_with_suffix({attn_4d, states}, context.get_name()); } 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); + 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()); } +OutputVector translate_gated_delta_net(const NodeContext & context) { + return translate_gdn(context, nullptr); +} + +#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); +} +#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 20a4cfdfe743..4b6b464606f3 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. diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index 252a450f8237..01c060ed9913 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 { @@ -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) @@ -70,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(std::make_shared(indices), + {int(indices_rank.get_length() - 2), int(indices_rank.get_length() - 1)}), false); } if (row_offset != 0) { indices = std::make_shared( @@ -90,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/op/recurrent_cache_update.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp new file mode 100644 index 000000000000..b107e878d2ce --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp @@ -0,0 +1,70 @@ +// 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: original cache, active rows, extra rows, reset begin/length, +/// 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 +/// 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. +/// 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. +/// 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/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 5b7509d853d9..3bcc202e4473 100644 --- a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp +++ b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp @@ -6,14 +6,18 @@ #include #include #include +#include #include +#include #include #include #include +#include #include #include #include #include +#include namespace ov { namespace frontend { @@ -27,13 +31,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 || op_case == 3) { @@ -42,7 +40,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); @@ -50,17 +51,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/scale.cpp b/ggml/src/ggml-openvino/openvino/op/scale.cpp index 4be2e700c20e..8a760c1b9f15 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 486c2ff28ce4..4ebe9c4b483a 100644 --- a/ggml/src/ggml-openvino/openvino/op/view.cpp +++ b/ggml/src/ggml-openvino/openvino/op/view.cpp @@ -16,6 +16,26 @@ 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() == 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/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..f2759dc44b4e 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -43,11 +43,15 @@ 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); GGML_OP_CONVERTER(translate_ssm_conv); GGML_OP_CONVERTER(translate_gated_delta_net); +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE +OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); +#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 new file mode 100644 index 000000000000..eee2a38dfb91 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp @@ -0,0 +1,307 @@ +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE +# include "recurrent_cache_fusion.h" + +# include "../ggml-openvino-extra.h" +# include "ggml-impl.h" +# include "op_table.h" +# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE +# include "op/recurrent_cache_update.hpp" +# endif +# 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_FUSED_RECURRENCE")) { + return; + } + auto actual = std::dynamic_pointer_cast(decoder); + if (!actual || actual->m_naive || !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) { + 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)) && + 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.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 + // 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 && 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; + } + 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; + } + m_nodes[group.compute] = id; + if (group.writeback >= 0) { + m_nodes[group.writeback] = 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) { + // 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.old_cache}; + } + 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(); + 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)); + 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); + } + 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}; +} +} // 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..0a2234f89b5f --- /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, compute = -1, writeback = -1; + std::vector snapshots; + Output old_cache, 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 a7e12b4e55a1..082e6269bfcb 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_CACHE_UPDATE +#include "recurrent_cache_fusion.h" +#endif #include "pass/mark_decompression_convert_constant_folding.h" #include "pass/mark_dequantization_subgraph.h" #include "pass_registry/pipeline.h" @@ -16,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -306,6 +310,25 @@ 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 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") { @@ -326,7 +349,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_CACHE_UPDATE + 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/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index d422a3fc64ba..8ff6be01bda7 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 @@ -462,6 +463,75 @@ 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 && input.get_element_type().is_real()) { + const auto source = context.get_view_input_src_ggml_shape(input_index, 0); + const auto view = context.get_view_input_ggml_shape(input_index, 0); + const auto source_stride = context.get_view_input_src_stride(input_index, 0); + const auto view_stride = context.get_view_input_stride(input_index, 0); + 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 && 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); + 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 da9a3dd13d96..f91fd65088b2 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -63,7 +63,15 @@ std::optional try_make_kv_sliced_tensor(const std::shared_ptris_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; } @@ -160,10 +168,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 = 1; // Graph-ordinal port names (invalidate older disk-cache blobs). + uint64_t extra_cfg = 14; // Snapshots use the independent cache-update op; ordinary GDN is unchanged. +#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 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_kv_slice_enabled() ? 0u : 1u); extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0 ? 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); @@ -307,6 +319,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); @@ -352,8 +368,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; } } @@ -410,27 +434,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); - } -} - static uint64_t ggml_openvino_model_cache_mix_string(uint64_t hash, const char * value) { if (!value) { return hash * 131; @@ -469,21 +472,32 @@ 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]; + } } } - // The sliced path above covers eligible KV outputs. This also covers recurrent state and full-size KV fallbacks. + // 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) && - 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 = output_data; + 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); @@ -569,6 +583,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 kv_4d = try_make_kv_4d_tensor(ggml_decoder, ggml_tensor)) { return *kv_4d; } @@ -607,11 +627,43 @@ 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); - if (extra_input->second.type == ov::element::i64) { - *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 == "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()); + } 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 { - std::memset(input_tensor.data(), 0, input_tensor.get_byte_size()); + if (extra_input->second.type == ov::element::i64) { + *input_tensor.data() = extra_input->second.value; + } else { + std::memset(input_tensor.data(), 0, input_tensor.get_byte_size()); + } } } else { input_tensor = convert_ggml_input_to_ov(ggml_decoder, param_name); @@ -952,7 +1004,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; } @@ -1095,7 +1147,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; @@ -1519,8 +1573,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); } auto & in_bindings = ggml_decoder->port_bindings(true, ov_input_names.size(), infer_request.get()); @@ -1567,14 +1619,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(); @@ -1604,7 +1672,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); } } @@ -2193,8 +2261,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++) { @@ -2242,7 +2308,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); } } } @@ -2282,7 +2348,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); } } } @@ -2302,19 +2368,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(); @@ -2339,7 +2439,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) { @@ -2567,6 +2667,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'; @@ -2600,13 +2702,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/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index aa9ebcf6ef95..aca01b7a1162 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 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; 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;