diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index 250593a3839c..a33da0677815 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -27,21 +27,3 @@ endif() if (WIN32) target_link_libraries(ggml-openvino PRIVATE psapi) endif() - -# Released runtimes retain the ordinary cache translators. -include(CheckCXXSourceCompiles) -include(CMakePushCheckState) -unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE) -cmake_push_check_state(RESET) -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) -cmake_pop_check_state() -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 497cf46df47c..5bdead151942 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -1,21 +1,10 @@ # 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 and update writable cache inputs in place, 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. +The OpenVINO backend translates Qwen recurrent replay for complete dynamic stateless GPU graphs and supports stable MTP sampling. 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. +Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. OpenVINO replay requires dynamic stateless GPU execution. -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`. Each cache is a writable Parameter backed by one -stable caller-owned USM allocation. The ops return only convolution or attention; -there are no recurrent cache Results. Required source rows are staged before -writes, preserving resets, cyclic reorders and rollback. Cache readers must be -exclusive, including Reshape aliases. -`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary cache decomposition. -Unmatched snapshot GDN uses ordinary GDN token prefixes with functional writeback. -Build both repos against the matching single-output op spec. Translation revision -15 requires regenerating compiled-model blobs once without cache-only mode. +The backend emits standard OpenVINO ops and `Assign` sinks for replay cache writeback. A GPU plugin with recurrent replay fusion replaces each matched group with an internal op that writes directly to the caller-owned GPU cache. If an `Assign` sink remains, the backend copies its state back to the GGML cache after inference. See the [replay graph contract](dev_doc/OPENVINO-RECURRENT-CACHE.md#replay-graph-contract). Cache-only MTP serving still requires the separate OpenVINO dynamic output-binding fix (PR #39354). Removing recurrent cache Results does not eliminate that independent trigger in imported MTP graphs. @@ -31,7 +20,7 @@ The recommended Qwen3.6-35B-A3B Q4_K_M setup uses GPU with `GGML_OPENVINO_REQUAN `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. +See the [implementation guide](dev_doc/OPENVINO-RECURRENT-CACHE.md) for buffer ownership and replay. # Compiled model cache diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 7dfb742b141a..9b04962f38f6 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -1,62 +1,70 @@ # Current Qwen GPU implementation -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. +The default Qwen3.5/Qwen3.6 MTP path uses pending-token replay, dynamic stateless execution, and stable pure-top-k sampling. When MTP discards a suffix, the next batch replays the retained tokens before processing new tokens. The implementation applies to `qwen35` and `qwen35moe` with one or multiple slots. The reference model is the UD Qwen3.6-35B-A3B MTP GGUF. -Build against the matching OpenVINO runtime/GPU plugin with single-output Update ops. Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requantization policy. The cache translation revision is 15. Historical measurements retain their original source revisions. - -The separate dynamic output-binding fix in OpenVINO PR #39354 remains required for cache-only MTP serving. Native cache-op export/import tests pass without it, but Qwen3.6 imported MTP graphs still trigger the missing-input-memory error without the fix. +Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requantization policy. The matching GPU plugin structurally fuses complete replay groups into its internal convolution and Gated Delta Net ops. Regenerate compiled blobs after switching to the writable-input replay interface. Historical measurements retain their original source revisions. ## 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 | +| Convolution `cache_r` | Caller-owned USM row bank with history and pending columns | Fused reset, original-row gather/reorder, convolution and ordered history/pending writes | +| GDN `cache_s`, `cache_spk`, `cache_spv`, `cache_spgb` | Caller-owned USM row banks with committed state and pending token inputs | Fused reset, original-row gather/reorder, GDN and ordered state/pending 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. Each cache input Parameter binds a stable writable allocation; recurrent cache Results are omitted. There are no rotation banks or pointer swaps. +Recurrent-cache size depends on slot capacity and pending-token capacity. Each fused cache input Parameter binds a caller-owned writable allocation. 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 inputs, including depthwise weights, and returns convolution `[1,B,T,C]`. `RecurrentGatedDeltaNetUpdate` returns attention and writes the newest `min(T,snapshot_count)` states into its cache input, newest first. Neither op returns a cache tensor. +`RecurrentConvCacheReplayUpdate` returns convolution `[1,B,T,C]` and writes history and pending columns. `RecurrentGatedDeltaNetReplayUpdate` returns attention and writes committed state and pending K, V, gate and beta. Both kernels write their cache inputs directly. ## Convolution cache stores -`build_conv_state_store` emits one CPY for the final history when rollback is disabled. With rollback enabled, it emits one SET_ROWS from overlapping `[history, window, channel, sequence]` views into strided snapshot planes. Window starts advance in time while destination planes descend, so plane zero holds the newest history. The fixed ARANGE/scale/cast chain supplies this descending slot order. +The structural replay graph gathers history using the retained-token count, concatenates live input, and uses one grouped convolution. A slice selects history and pending columns for the next batch, and ScatterNDUpdate produces the updated bank for the Assign sink. Row maps, replay counts and reset rows are runtime inputs. + +## Replay graph contract + +Qwen selects the recurrent graph when the target context is created. `n_rs_seq=0` selects the ordinary graph. With `--spec-type draft-mtp` and a positive draft limit, `n_rs_seq` is the draft limit and `rs_replay` selects the replay graph even for a fresh prefill. Both forms use `GGML_OP_GATED_DELTA_NET`. The replay form sets `op_params[1]` to the pending-token capacity and adds inputs for pending K, V, gate/beta, and the per-sequence replay count. -The backend recognizes this structure and refreshes source starts, cache heads, sequence counts, window counts and plane strides on every batch. Native fusion passes runtime `[source column, destination slot]` pairs to the existing convolution op; the pair-count dimension is dynamic. Functional translation gathers the same windows, scatters them into the full cache, and preserves unwritten slots and features. The native op spec is unchanged. +A fresh prompt supplies a replay count of zero. Prefill microbatches longer than `n_rs_seq + 1` tokens per sequence commit their final state. The unfused OpenVINO graph processes current tokens in a `Loop` and uses a bounded unrolled recurrence for the retained prefix. -## Generic fallback and restrictions +The backend emits a standard-op graph for each complete dynamic stateless replay group. The computation feeds later layers and the updated banks feed standard `Assign` sinks. Fusion requires each bank to be a direct FP32 `Parameter` of shape `[1, 1, slots, features]` backed by caller-owned writable GPU USM. The backend opts each bank into in-place fusion by giving its sink the variable ID `__ggml_replay_cache_`. -Writable cache inputs must be GPU RemoteTensors with exclusive graph readers, optionally through Reshape aliases. The GPU plugin rejects shared cache readers and computed cache banks. Other inputs and the computation output must not overlap the cache. The frontend skips fusion for unmatched cache reads and retains functional cache writeback. Restore or clear state after a failed inference before retrying. +The GPU plugin requires the transformed model to preserve its `Result` count. Sinks express writeback separately from that output interface. The pass can replace the computation and remove its matched sinks and variables while keeping the Results. The internal op then writes through the original input binding, which avoids the GPU runtime changes that would be needed to alias a cache output to its input. -`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains ordinary cache decomposition. Naive graphs skip full-model recurrence fusion. Unmatched snapshot GDN uses ordinary GDN token prefixes to preserve state outputs. The fused path requires the matching native runtime; otherwise dynamic CPU and GPU execution uses ordinary GDN. Stateful and NPU MTP are outside this change. +The variable ID supplies the write permission. `RecurrentReplayFusion` still matches the computation, row controls, reset, reordering and writeback structure, and requires exclusive bank readers and a live computation output. The kernel checks for overlapping buffer ranges. When a sink remains, including on a GPU plugin without this pass, llama.cpp uses `query_state()` to find it and copies its state to the original GGML bank after inference. Mixed-precision execution of that graph can round bank values. + +The backend builds the graph in [`openvino/op/recurrent_replay_graph.hpp`](../openvino/op/recurrent_replay_graph.hpp). The GPU matcher in `src/plugins/intel_gpu/src/plugin/transformations/recurrent_replay_fusion.cpp` compares it to a reference built from the OpenVINO copy of `recurrent_replay_graph.hpp` in the same directory. When upstream modeling changes the GGML graph, adapt the backend recognition and check what it emits. If the emitted replay pattern or its semantics change, update the reference and the relevant matcher and kernel logic with the translation. Verify that the graph still fuses and that the standard-op writeback still works. ## 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. +On dynamic CPU and GPU, `GGML_OPENVINO_KV_SLICE` is a binding switch and defaults to `1`. For an eligible contiguous ordinary attention K/V root with one active sequence at offset zero, it binds a view of the allocation sized to the attended prefix. Recurrent banks and sliding-window attention use the full binding. The 4-D in-place attention path binds the full allocation first and exposes the attended prefix inside the graph. Dynamic compiled blobs can accept either eligible binding. + +`GGML_OPENVINO_GPU_KV_ROUND_UP` controls the attended width separately on dynamic stateless GPU. With `0`, the decoder uses the GGML mask width, which ordinary GGML attention KV already pads in steps of 256 rows. The default `1` uses power-of-two windows when the graph input has more than 16 tokens and coarser aligned steps for smaller batches. The step starts at 256 rows and doubles whenever the width reaches eight times the current step. At 33,024 GGML rows, the added rounding can expand attention to 40,960 rows for decode or 65,536 for a larger prefill input, subject to the context cap. Added mask columns contain negative infinity. The current cache-only batched measurements used `GGML_OPENVINO_ENABLE_KV_4D=1`, the default `KV_SLICE` setting and `GGML_OPENVINO_GPU_KV_ROUND_UP=0`. + +On static NPU, `GGML_OPENVINO_KV_SLICE` also selects the base of the compiled KV windows. The default base is 1024 and an explicit multiple of 256 changes it. The window is the smallest `base * 2^k` that covers the attended length, capped by the context. ## 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-15 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. +One compatible draft graph is shared across active subsets. Trunk and genuinely different graph stages/configurations remain separate. Prepare compatible blobs once, then use cache-only mode. The first 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, writable cache input rebinding, 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. +Validation checks the caller's mutated convolution bank against the expected reset, reorder and history writes. The four-layer Qwen3.6 model exercises replay at one and four active sequences. ## 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/recurrent_replay_fusion.cpp`: GGML group recognition and standard-op replay translation. - `openvino/translate_session.cpp`: runtime sampling aliases and model construction. -- OV `recurrent_cache_update` implementation: writable-input validation, source staging and GPU computation. +- OV `recurrent_replay_fusion.cpp` and `recurrent_cache_replay`: structural matching, writable-input validation, 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/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index 57deb264e455..8424460a038c 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -54,7 +54,8 @@ Each variable turns off an optimization that is on by default, or sets its stren | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. CPU and GPU: a view over the cache (any non-zero value just turns it on). Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. | +| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. Dynamic CPU and GPU use a valid positive value to bind eligible ordinary attention KV as a view of the attended prefix. The 4-D GPU binding takes precedence. Dynamic compiled blobs support both bindings. Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. | +| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Controls the extra attended-width rounding on dynamic stateless GPU. With `1`, a graph input over 16 tokens uses the next power-of-two window and smaller batches use an aligned step that grows with the attended length. With `0`, the decoder uses the original GGML mask width. This setting is separate from prefix binding. | | `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | With `GGML_OPENVINO_KV_SLICE` on, decode attends the smallest `N * 2^k` rows (`N` from `GGML_OPENVINO_KV_SLICE`) that cover the next position, with one decode graph for each window, and the prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. Use the same value in the run that writes the cache and in the runs that read it. | | `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. | | `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. | @@ -63,7 +64,7 @@ Each variable turns off an optimization that is on by default, or sets its stren | `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` | CPU, GPU | Boolean | `0` | By default the model reads the sequence count and the attended KV length from the shape of the KQ mask, so the GPU plugin can select its fused attention kernel. `1` passes them as separate inputs. | | `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | CPU, GPU | Boolean | `0` | Stateful execution only. By default the sequence axis of the KV state is moved so that new tokens are appended in place. `1` keeps the original layout. | | `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS` | GPU | Boolean | `0` | By default an output tensor in a GPU buffer is bound directly to the infer request when its shape and type match. `1` turns this off. | -| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | Stateless execution only, with an OpenVINO build newer than 2026.4.1 (2026.4.1 does not build the fusion). By default the recurrent-state cache updates (Qwen3.5, LFM2) are fused into the OpenVINO model. `1` keeps the separate copies. | +| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | `1` disables the OpenVINO backend's recurrent replay translation, so replay ops require another eligible GGML backend. For an unfused OpenVINO replay graph, leave this at `0` and use a GPU plugin without the replay fusion pass. | | `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN` | GPU | Boolean | `0` | By default the operands of an element-wise op get the same rank, which works around a GPU plugin defect when the op is fused into RMS norm (gemma-4 in stateful execution gave wrong output). `1` turns the workaround off. | ```bash diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 1eb7ae9fc790..ac25634177d5 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -485,6 +485,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { seq = node; } recurrent_sequence = seq == node; + } else if (concat->op == GGML_OP_CONT && concat->src[0]->op == GGML_OP_TRANSPOSE) { + const auto * cols = concat->src[0]->src[0]; + recurrent_sequence = cols->op == GGML_OP_CONCAT && cols->op_params[0] == 1 && cols->src[1] == node; } } else if (consumer->op == GGML_OP_UNARY && ggml_get_unary_op(consumer) == GGML_UNARY_OP_SOFTPLUS) { const auto * biased = consumer->src[0]; @@ -1372,7 +1375,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr 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 bool is_gdn_rollback = is_gdn && node->src[0]->src[0]->op_params[1] == 0 && is_same_shape(node->src[0], node->src[1]); const ggml_tensor * dest_view = node->src[1]; const ggml_tensor * cache = node->view_src; @@ -1454,7 +1457,8 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr // The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of // 256. Round it up (ggml_openvino_gpu_kv_window), so that a long context uses a few lengths and not one per step. // The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov). - if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && + if (!is_static && ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_GPU_KV_ROUND_UP", 1) && + !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && !compute_params.mask_name.empty() && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) { compute_params.attention_size = ggml_openvino_gpu_kv_window(compute_params.attention_size, model_params.ctx_per_seq, compute_params.input_len); @@ -1817,62 +1821,51 @@ void GgmlOvDecoder::add_extra_inputs() { create_1d_input("rs_window_count_" + node_name, writeback.window_count); } } -#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) || is_conv_state_snapshot_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; - } - const auto & wb = it->second; - const int64_t count = wb.window_count >= 0 ? wb.window_count : 1; - for (int64_t w = 0; w < count; ++w) { - values.push_back(wb.src_begin + w); - values.push_back(wb.slot_begin + (count - 1 - w) * - (wb.window_count >= 0 ? wb.snapshot_stride : 0)); - } - break; + const auto gdn = m_cgraph->nodes[i]; + if (gdn->op != GGML_OP_GATED_DELTA_NET || gdn->op_params[1] <= 0) continue; + const auto B = gdn->src[2]->ne[3]; + const ggml_tensor * rows = gdn->src[5]; + while (rows && (rows->op == GGML_OP_VIEW || rows->op == GGML_OP_RESHAPE)) rows = rows->src[0]; + if (!rows || rows->op != GGML_OP_GET_ROWS) continue; + rows = rows->src[1]; + while (rows && rows->op == GGML_OP_VIEW) rows = rows->src[0]; + if (!rows || rows->type != GGML_TYPE_I32 || !rows->data || !gdn->src[9]->data) continue; + const ggml_tensor * root = gdn->src[5]; + while (root && (root->op == GGML_OP_VIEW || root->op == GGML_OP_RESHAPE || root->op == GGML_OP_GET_ROWS)) root = root->src[0]; + int64_t head = -1, reset_begin = 0, reset_count = 0; + for (int j = 0; j < m_cgraph->n_nodes; ++j) { + const auto t = m_cgraph->nodes[j]; + if (t->view_src != root) continue; + if (t->op == GGML_OP_CPY && t->src[0]->op == GGML_OP_VIEW && t->src[0]->src[0] == gdn) + head = t->src[1]->view_offs / root->nb[1]; + if (is_recurrent_cache_reset(t)) { + reset_begin = t->src[0]->view_offs / root->nb[1]; + reset_count = ggml_nelements(t->src[0]) / root->ne[0]; } } - 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); - } + if (head < 0) continue; + auto & map = m_compute_params.recurrent_controls["rs_replay_rows"]; + auto & control = m_compute_params.recurrent_controls["rs_replay_control"]; + auto & resets = m_compute_params.recurrent_controls["rs_replay_reset"]; + map.clear(); control.clear(); resets.clear(); + const auto * copy = static_cast(rows->data); + for (int64_t j = 0; j < ggml_nelements(rows); ++j) { + if (j < B || head + j != copy[j]) { map.push_back(head + j); map.push_back(copy[j]); } + } + const auto * counts = static_cast(gdn->src[9]->data); + for (int64_t j = 0; j < B; ++j) control.push_back(counts[j]); + control.push_back(gdn->op_params[2]); + for (int64_t j = 0; j < reset_count; ++j) resets.push_back(reset_begin + j); + m_model_extra_inputs["rs_replay_rows"] = {ov::element::i64, ov::Shape{1, 1, map.size() / 2, 2}, 0, true, {}, -1, ov::PartialShape{1, 1, -1, 2}}; + m_model_extra_inputs["rs_replay_control"] = {ov::element::i64, ov::Shape{1, 1, 1, control.size()}, 0, true, {}, -1, ov::PartialShape{1, 1, 1, -1}}; + m_model_extra_inputs["rs_replay_reset"] = {ov::element::i64, ov::Shape{1, 1, 1, resets.size()}, 0, true, {}, -1, ov::PartialShape{1, 1, 1, -1}}; + break; } } -#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}; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 4c2106df9edb..f5e97efa3b0d 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -563,7 +563,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { static bool is_recurrent_cache(const ggml_tensor * tensor) { return tensor != nullptr && (strncmp(tensor->name, "cache_r_l", strlen("cache_r_l")) == 0 || strncmp(tensor->name, "cache_s_l", strlen("cache_s_l")) == 0 || - strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0); + strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0 || + strncmp(tensor->name, "cache_sp", strlen("cache_sp")) == 0); } static bool is_recurrent_cache_reset(const ggml_tensor * node) { diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 054d78c31580..7b254e3454b5 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -193,6 +193,7 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_GDN_DECOMPOSE", env_type::BOOL}, {"GGML_OPENVINO_NPU_L0_HOST_TENSORS", env_type::BOOL}, {"GGML_OPENVINO_KV_SLICE", env_type::INT}, + {"GGML_OPENVINO_GPU_KV_ROUND_UP", env_type::BOOL}, {"GGML_OPENVINO_NPU_HFA_PREFILL", env_type::BOOL}, {"GGML_OPENVINO_NPU_DECODE_UNFOLD", env_type::BOOL}, {"GGML_OPENVINO_SELF_CONTAINED_MMAP", env_type::BOOL}, diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index f34a4b77cdc2..0fcc0e102b76 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1634,6 +1634,25 @@ static bool tensor_view_fits_src_buffer(const ggml_tensor * tensor) { return tensor_nbytes <= src_nbytes - tensor->view_offs; } +static bool supports_replay_cache_banks() { + return ggml_openvino_is_gpu() && !ggml_openvino_is_static() && !is_stateful_enabled() && + !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE"); +} + +static bool is_replay_input_store(const ggml_tensor * op) { + if (op->op != GGML_OP_CPY || !op->view_src || strncmp(op->view_src->name, "cache_sp", 8) != 0 || + op->type != GGML_TYPE_F32 || op->src[0]->op != GGML_OP_VIEW || op->src[1]->op != GGML_OP_VIEW || + !supports_replay_cache_banks()) { + return false; + } + const auto dst = op->src[1]; + const auto base = dst->src[0]; + // Pending prefixes keep the full bank row stride; the complete replay fusion owns this store. + return base && base->op == GGML_OP_RESHAPE && base->src[0] == op->view_src && + dst->ne[0] <= base->ne[0] && dst->ne[1] == base->ne[1] && dst->ne[2] <= base->ne[2] && + dst->nb[0] == base->nb[0] && dst->nb[1] == base->nb[1] && dst->nb[2] == base->nb[2] && dst->nb[3] == base->nb[3]; +} + static bool cpy_output_view_is_supported(const ggml_tensor * op) { if (op->view_src == nullptr) { return true; @@ -1644,7 +1663,7 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) { } return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op) || - GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op); + GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op) || is_replay_input_store(op); } // SET_ROWS writes whole rows of a contiguous destination. Other destination views (e.g. a permuted view of a @@ -2090,7 +2109,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, reason}; } if (((const int32_t *) op->op_params)[1] != 0) { - return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"}; + bool banks = true; + for (int port : {5, 6, 7, 8}) { + const auto * source = op->src[port]; + while (source && (source->op == GGML_OP_VIEW || source->op == GGML_OP_RESHAPE || source->op == GGML_OP_GET_ROWS)) source = source->src[0]; + banks &= GgmlOvDecoder::is_recurrent_cache(source); + } + if (!banks || !supports_replay_cache_banks()) { + return {false, "GATED_DELTA_NET replay requires the dynamic stateless GPU cache-bank translation"}; + } } break; } diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index 3a05c8b436d9..15a39f8166f8 100644 --- a/ggml/src/ggml-openvino/openvino/decoder.h +++ b/ggml/src/ggml-openvino/openvino/decoder.h @@ -26,6 +26,7 @@ struct ModelExtraInputInfo { // when set, the value is read from dimension shape_axis of this model input instead of a Parameter std::string shape_source; int64_t shape_axis = -1; + PartialShape parameter_shape = PartialShape::dynamic(); }; class GgmlDecoder : public DecoderBase { 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 eef3874fa63f..92648e212aa0 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -1,11 +1,9 @@ #include "gated_delta_net.hpp" #include "../node_context.h" +#include "recurrent_replay_graph.hpp" #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 @@ -30,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -402,7 +401,9 @@ static OutputVector translate_gdn_snapshots(const Output & q, return {attention, states}; } -static OutputVector translate_gdn(const NodeContext & context, const OutputVector * cache_inputs) { +OutputVector translate_gated_delta_net(const NodeContext & context) { + FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[1] == 0, + "GATED_DELTA_NET replay requires a complete recurrent cache group"); 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] @@ -411,7 +412,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto const bool kda = context.get_input_shape(3)[3] != 1; if (kda && !gdn_per_key_gate_supported()) { // the reference loop reads and writes the state in the ggml layout, one state per call - FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 && + FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[0] == 1 && !ggml_openvino_gdn_native_state_enabled(), "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 " "gate for recurrent caches, state snapshots or the native state layout"); @@ -479,7 +480,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto // resets and slot copies move whole states, and supports_op aborts instead of falling back to CPU. const bool native_state = ggml_openvino_gdn_native_state_enabled(); auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{0, 1, 3, 2}); - if (!native_state && !cache_inputs && snapshot_count == 1) { + if (!native_state && snapshot_count == 1) { state = std::make_shared(state, state_perm); } @@ -514,21 +515,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto g = std::make_shared(g, mask); } -#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), (*cache_inputs)[0]}; - } - return {fused->output(0), (*cache_inputs)[0]}; - } -#endif Output attn_4d, states; if (snapshot_count > 1) { @@ -570,15 +556,31 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto 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); +OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks) { + auto q = context.get_input(0), k = context.get_input(1); + const auto shape = context.get_input_shape(2); + auto v = process_view_input(context, 2, shape[2].get_length() * shape[3].get_length(), 3); + if (context.get_view_input_size(2)) { + v = std::make_shared(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0})); + v = std::make_shared(v, ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{0, 0, shape[2].get_length(), shape[3].get_length()}), true); + } + if (context.get_op_case() == 1 && ggml_openvino_gdn_prescale_enabled()) { + q = std::make_shared(q, + ov::op::v0::Constant::create(ov::element::f32, {1}, {ggml_openvino_gdn_q_scale()})); + } else { + Output raw_q, raw_k; + float q_eps, k_eps; + if (match_gdn_l2_norm(q, raw_q, q_eps) && match_gdn_l2_norm(k, raw_k, k_eps)) { + auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}); + q = std::make_shared(raw_q, axis, q_eps, ov::op::EpsMode::ADD); + k = std::make_shared(raw_k, axis, k_eps, ov::op::EpsMode::ADD); + } + } + return ov::recurrent_replay::build({ + q, k, v, banks[0], context.get_input(3), context.get_input(4), + banks[1], banks[2], banks[3], banks[4], banks[5], banks[6]}, false); } -#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/recurrent_cache_update.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp deleted file mode 100644 index a4daf8c86b63..000000000000 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp +++ /dev/null @@ -1,65 +0,0 @@ -// 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]. -/// Cache input 0 is a writable GPU RemoteTensor, updated in place. -/// Other inputs and output 0 must not overlap its allocation. -/// The cache must be a Parameter or an exclusive Reshape alias; no other op -/// may read it in the same inference. Required original rows are staged before -/// reset, reorder and window writes, preserving cycles and duplicate sources. -/// A failed inference may partially modify the cache; 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. -/// The only output is attention [B,T,H,V]. Cache input 3 is updated in place -/// under the same writable-input contract as RecurrentConvCacheUpdate. -/// snapshot_count saves the newest min(T,count) states in cache, newest first. -/// Active/nonidentity rows are staged before writes; identity rows need no copy. -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/recurrent_replay_graph.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp new file mode 100644 index 000000000000..e4b6777c2056 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp @@ -0,0 +1,228 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include "openvino/opsets/opset13.hpp" +#include "openvino/core/model.hpp" +#include "openvino/core/visibility.hpp" +#include +#include +#include + +namespace ov { +// The runtime exports this transformation attribute even when its header is not installed. +#ifndef OPENVINO_STATIC_LIBRARY +OPENVINO_CORE_IMPORTS +#endif +void disable_conversion(const std::shared_ptr& node, const element::Type& to); +} + +namespace ov::recurrent_replay { +// OpenVINO's GPU RecurrentReplayFusion checks this emitted graph against its +// reference replay graph. Keep the patterns in both repositories in sync. +namespace ops = ov::opset13; +using Value = ov::Output; + +inline Value scalar(int64_t n) { return ops::Constant::create(element::i64, {}, {n}); } +inline Value vec(std::vector v) { return ops::Constant::create(element::i64, {v.size()}, v); } +inline Value fp(float x) { return ops::Constant::create(element::f32, {}, {x}); } +inline Value f32(Value x) { + return x.get_element_type() == element::f32 ? x : Value(std::make_shared(x, element::f32)); +} +inline Value gather(Value x, Value i, int axis, int batch = 0) { + return std::make_shared(x, i, scalar(axis), batch); +} +inline Value unsqueeze(Value x, int axis) { return std::make_shared(x, scalar(axis)); } +inline Value squeeze(Value x, int axis) { return std::make_shared(x, scalar(axis)); } +inline Value reshape(Value x, std::vector dims) { return std::make_shared(x, vec(dims), true); } +inline Value dim(Value x, int axis) { return gather(std::make_shared(x, element::i64), scalar(axis), 0); } +inline Value cat(OutputVector xs, int axis) { return std::make_shared(xs, axis); } +inline Value slice(Value x, Value begin, Value end, int axis) { + return std::make_shared(x, unsqueeze(begin, 0), unsqueeze(end, 0), vec({1}), vec({axis})); +} +inline Value slice_end() { return scalar(std::numeric_limits::max()); } +inline Value add(Value x, Value y) { return std::make_shared(x, y); } +inline Value mul(Value x, Value y) { return std::make_shared(x, y); } +inline Value swap_time_channels(Value x) { return std::make_shared(x, vec({0, 2, 1})); } +inline Value linear(Value count) { return std::make_shared(scalar(0), count, scalar(1), element::i64); } + +struct RowSelection { + Value sources, destinations, extra_src, extra_dst, resets, counts, keep; + RowSelection(Value rows, Value control, Value reset, Value batch) { + rows = reshape(rows, {-1, 2}); + auto src = gather(rows, scalar(1), 1); + auto dst = gather(rows, scalar(0), 1); + sources = slice(src, scalar(0), batch, 0); + destinations = slice(dst, scalar(0), batch, 0); + extra_src = slice(src, batch, slice_end(), 0); + extra_dst = slice(dst, batch, slice_end(), 0); + resets = reshape(reset, {-1}); + auto flags = reshape(control, {-1}); + counts = slice(flags, scalar(0), batch, 0); + keep = std::make_shared(gather(flags, scalar(-1), 0), scalar(0)); + } +}; + +// A bank is logically [slots, features]. Gather original rows before any stores; +// active stores only replace their written features in the destination row. +struct Bank { + Value cleared, sources, destinations, extra_values; + const RowSelection& rows; + Bank(Value input, const RowSelection& r) : rows(r) { + auto flat = squeeze(squeeze(input, 0), 0); + auto reset_shape = cat({unsqueeze(dim(r.resets, 0), 0), unsqueeze(dim(flat, 1), 0)}, 0); + auto zeros = std::make_shared(fp(0), reset_shape); + cleared = std::make_shared(flat, unsqueeze(r.resets, 1), zeros); + sources = gather(cleared, r.sources, 0); + destinations = gather(cleared, r.destinations, 0); + extra_values = gather(cleared, r.extra_src, 0); + } + Value write(Value active) const { + // One destination per row-map entry. GGML generates these in slot order, + // including the inactive rows that need a copy. + auto indices = unsqueeze(cat({rows.destinations, rows.extra_dst}, 0), 1); + auto values = cat({reshape(active, {0, -1}), extra_values}, 0); + auto result = std::make_shared(cleared, indices, values); + return unsqueeze(unsqueeze(result, 0), 0); + } +}; +inline Value store_prefix(Value original, Value prefix) { + return cat({prefix, slice(original, dim(prefix, 1), slice_end(), 1)}, 1); +} + +inline OutputVector conv_body(const OutputVector& a) { + auto x = squeeze(a[2], 0); + const auto channels = a[3].get_partial_shape()[2].get_length(); + const auto taps = a[3].get_partial_shape()[3].get_length(); + RowSelection rows(a[1], a[4], a[5], dim(x, 0)); + Bank bank(a[0], rows); + auto history = reshape(bank.sources, {0, -1, channels}); + auto indices = add(unsqueeze(rows.counts, 1), unsqueeze(linear(scalar(taps - 1)), 0)); + auto window = gather(history, indices, 1, 1); + auto columns = cat({window, f32(x)}, 1); + auto weights = reshape(f32(a[3]), {channels, 1, 1, taps}); + auto convolved = std::make_shared(swap_time_channels(columns), weights, Strides{1}, + CoordinateDiff{0}, CoordinateDiff{0}, Strides{1}); + Value result = unsqueeze(swap_time_channels(convolved), 0); + if (a[2].get_element_type() != element::f32) + result = std::make_shared(result, a[2].get_element_type()); + // Keep the history and pending tokens, or commit only the last history window. + auto begin = std::make_shared(rows.keep, scalar(0), dim(x, 1)); + auto update = slice(columns, begin, slice_end(), 1); + return {result, bank.write(store_prefix(reshape(bank.destinations, {0, -1, channels}), update))}; +} + +inline Value expand_heads(Value x, int64_t heads, int64_t expanded) { + if (heads == expanded) + return x; + std::vector indices(expanded); + for (int64_t h = 0; h < expanded; ++h) + indices[h] = h % heads; + return gather(x, vec(indices), 2); +} +inline Value dot(Value state, Value key) { + return std::make_shared(mul(state, unsqueeze(key, 2)), scalar(3), false); +} +inline Value step(Value state, Value key, Value value, Value gate, Value beta) { + auto decayed = mul(state, unsqueeze(std::make_shared(gate), 2)); + auto delta = mul(beta, std::make_shared(value, dot(decayed, key))); + return add(decayed, mul(unsqueeze(delta, 3), unsqueeze(key, 2))); +} +inline OutputVector current_tokens(Value state, Value q, Value k, Value v, Value g, Value beta, float scale) { + auto idx = std::make_shared(element::i64, PartialShape{}); + auto carried = std::make_shared(element::f32, state.get_partial_shape()); + ParameterVector params{idx, carried}; + OutputVector inputs{q, k, v, g, beta}, token; + for (const auto& input : inputs) { + auto p = std::make_shared(input.get_element_type(), input.get_partial_shape()); + params.push_back(p); + token.push_back(gather(p, idx, 1)); + } + auto next = step(carried, token[1], token[2], token[3], token[4]); + auto attention = unsqueeze(mul(dot(next, token[0]), fp(scale)), 1); + auto yes = ops::Constant::create(element::boolean, {}, {true}); + auto body = std::make_shared(OutputVector{yes, next, attention}, params); + auto loop = std::make_shared(dim(v, 1), yes); + loop->set_function(body); + loop->set_special_body_ports({0, 0}); + loop->set_merged_input(carried, state, next); + for (size_t i = 0; i < inputs.size(); ++i) + loop->set_invariant_input(params[i + 2], inputs[i]); + return {loop->get_concatenated_slices(attention, 0, 1, 1, -1, 1), loop->get_iter_value(next, -1)}; +} + +inline OutputVector gdn_body(const OutputVector& a) { + const auto qshape = a[0].get_partial_shape(), kshape = a[1].get_partial_shape(), vshape = a[2].get_partial_shape(); + const int64_t Hq = qshape[2].get_length(), Hk = kshape[2].get_length(), Hv = vshape[2].get_length(); + const int64_t K = kshape[3].get_length(), V = vshape[3].get_length(), G = a[4].get_partial_shape()[3].get_length(); + const int64_t P = a[6].get_partial_shape()[3].get_length() / (Hk * K); + RowSelection rows(a[9], a[10], a[11], dim(a[2], 0)); + Bank states(a[3], rows), keys(a[6], rows), values(a[7], rows), gates(a[8], rows); + Value state = reshape(states.sources, {0, Hv, V, K}); + auto pk = expand_heads(reshape(keys.sources, {0, P, Hk, K}), Hk, Hv); + auto pv = reshape(values.sources, {0, P, Hv, V}); + auto pgb = reshape(gates.sources, {0, 2 * P, Hv, G}); + for (int64_t t = 0; t < P; ++t) { + auto time = scalar(t); + auto b = slice(gather(pgb, scalar(P + t), 1), scalar(0), scalar(1), 2); + auto next = step(state, gather(pk, time, 1), gather(pv, time, 1), gather(pgb, time, 1), b); + auto active = reshape(std::make_shared(rows.counts, time), {-1, 1, 1, 1}); + state = std::make_shared(active, next, state); + } + auto q = expand_heads(f32(a[0]), Hq, Hv), k = expand_heads(f32(a[1]), Hk, Hv); + auto computed = current_tokens(state, q, k, f32(a[2]), f32(a[4]), f32(a[5]), 1.0f / std::sqrt(float(K))); + auto save = [&](Value x) { return slice(f32(x), scalar(0), scalar(P), 1); }; + auto saved_g = save(a[4]), saved_b = save(a[5]); + auto gb = reshape(gates.destinations, {0, 2 * P, Hv, G}); + auto gb_gate = slice(gb, scalar(0), scalar(P), 1), gb_beta = slice(gb, scalar(P), slice_end(), 1); + if (G > 1) { + auto old_prefix = slice(gb_beta, scalar(0), dim(saved_b, 1), 1); + saved_b = cat({saved_b, slice(old_prefix, scalar(1), slice_end(), 3)}, 3); + } + Value output = computed[0]; + if (a[0].get_element_type() != element::f32) + output = std::make_shared(output, a[0].get_element_type()); + auto committed = std::make_shared(rows.keep, state, computed[1]); + return {output, states.write(committed), + keys.write(store_prefix(reshape(keys.destinations, {0, P, Hk, K}), save(a[1]))), + values.write(store_prefix(reshape(values.destinations, {0, P, Hv, V}), save(a[2]))), + gates.write(cat({store_prefix(gb_gate, saved_g), store_prefix(gb_beta, saved_b)}, 1))}; +} + +inline OutputVector build(const OutputVector& args, bool conv) { + auto outputs = conv ? conv_body(args) : gdn_body(args); + const auto bank_ports = conv ? std::vector{0} : std::vector{3, 6, 7, 8}; + for (const auto port : bank_ports) { + auto bank = args[port]; + while (ov::is_type(bank.get_node())) { + ov::disable_conversion(bank.get_node_shared_ptr(), element::f16); + bank = bank.get_node()->input_value(0); + } + ov::disable_conversion(bank.get_node_shared_ptr(), element::f16); + } + // Keep the functional replay state in FP32 under the GPU's mixed-precision + // policy. Stop at the replay inputs to preserve the upstream precision policy. + std::unordered_set visited; + for (const auto& arg : args) { + visited.insert(arg.get_node()); + } + auto pending = outputs; + while (!pending.empty()) { + const auto node = pending.back().get_node_shared_ptr(); + pending.pop_back(); + if (!visited.insert(node.get()).second) { + continue; + } + ov::disable_conversion(node, element::f16); + if (const auto loop = ov::as_type_ptr(node)) { + for (const auto& body_node : loop->get_function()->get_ordered_ops()) { + ov::disable_conversion(body_node, element::f16); + } + } + for (const auto& input : node->input_values()) { + pending.push_back(input); + } + } + return outputs; +} +} // namespace ov::recurrent_replay diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 766ca4e6f76c..b26a23373232 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -54,9 +54,7 @@ GGML_OP_CONVERTER(translate_ssm_scan); GGML_OP_CONVERTER(translate_gated_delta_net); // The device runs GatedDeltaNet with a gate per key dimension; otherwise the translator falls back to its reference loop bool gdn_per_key_gate_supported(); -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); -#endif +OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks); GGML_OP_CONVERTER(translate_repeat); GGML_OP_CONVERTER(translate_cumsum); GGML_OP_CONVERTER(translate_set); diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp deleted file mode 100644 index a3b56bb5ec29..000000000000 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ /dev/null @@ -1,313 +0,0 @@ -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -# include "recurrent_cache_fusion.h" - -# include "../ggml-openvino-extra.h" -# include "ggml-impl.h" -# include "op/recurrent_cache_update.hpp" -# include "op_table.h" -# include "utils.h" - -# include -# 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 (GgmlOvDecoder::is_recurrent_cache_reset(node) && - node->view_src == root && decoder->get_op_case(j) == 1) { - // SCALE stores (scale, bias); FILL stores its value first and leaves the second parameter 0. - 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; - } - // build_conv_state_store emits one CPY without rollback or one SET_ROWS with rollback. - 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]; - const bool copy = GgmlOvDecoder::is_conv_state_writeback(write); - const bool slots = GgmlOvDecoder::is_conv_state_snapshot_writeback(write); - if ((copy || slots) && write->view_src == root && write->src[0]->src[0] == node && - write->src[0]->ne[0] == node->src[0]->ne[0] && - write->src[0]->ne[slots ? 2 : 1] == node->src[0]->ne[1] && - (slots ? write->src[2] : write->src[1])->view_offs % root->nb[1] == 0) { - if (group.writeback >= 0) { - group.writeback = -1; - break; - } - group.writeback = k; - } - } - break; - } - } - if (group.concat >= 0) { - if (group.writeback < 0) { - 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)); - if (group.concat >= 0) { - complete &= tensors->count("rs_windows_" + decoder->get_op_name(group.concat)); - const auto & name = decoder->get_op_name(group.writeback); - complete &= tensors->count("rs_slot_begin_" + name) && tensors->count("rs_src_begin_" + name); - } - for (int j = 0; j < graph->n_nodes && complete; ++j) { - const auto node = graph->nodes[j]; - // Other cache readers or writers require functional translation. - 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 || j == group.reset; - const bool destination = (node->op == GGML_OP_CPY && source == 1) || - (GgmlOvDecoder::is_conv_state_snapshot_writeback(node) && source == 2); - if (!alias && !matched_read && !destination) { - complete = false; - } - } - if (node->view_src == root && - (node->op == GGML_OP_SCALE || node->op == GGML_OP_CPY || node->op == GGML_OP_SET_ROWS) && - j != group.reset && j != group.remainder && j != group.writeback) { - 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) { - complete &= node == graph->nodes[group.writeback]->src[0]; - } - 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; - } - group.root_name = GgmlOvDecoder::get_tensor_name(graph, root); - 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; - } - 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); - auto root = group.old_cache.get_node_shared_ptr(); - while (ov::is_type(root)) { - root = root->input_value(0).get_node_shared_ptr(); - } - group.enabled = ov::is_type(root); - if (!group.enabled) { - return {}; - } - return {group.old_cache}; - } - if (!group.enabled) { - return {}; - } - 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)); - // Runtime pairs [source column, destination slot] cover the current CPY or SET_ROWS store. - inputs.push_back(context.get_input("rs_windows_" + context.get_name())); - 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); - 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))); - return op::translate_recurrent_gated_delta_net(context, inputs); - } - return {group.old_cache}; -} - -bool RecurrentCacheFusion::is_inplace_output(const std::string & name) const { - return std::any_of(m_groups.begin(), m_groups.end(), - [&](const Group & group) { return group.enabled && group.root_name == name; }); -} -} // 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 deleted file mode 100644 index 1d9d494acd8b..000000000000 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h +++ /dev/null @@ -1,26 +0,0 @@ -#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); - bool is_inplace_output(const std::string & name) const; -private: - struct Group { - int reset = -1, gather = -1, remainder = -1, concat = -1, compute = -1, writeback = -1; - std::string root_name; - bool enabled = false; - Output old_cache, conv; - }; - - 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/recurrent_replay_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp new file mode 100644 index 000000000000..e387e1c77436 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp @@ -0,0 +1,217 @@ +#include "recurrent_replay_fusion.h" + +#include "../ggml-openvino-extra.h" +#include "ggml-impl.h" +#include "op/recurrent_replay_graph.hpp" +#include "op_table.h" +#include "utils.h" + +#include +#include +#include + +namespace ov::frontend::ggml { +namespace { +const ggml_tensor * cache_root(const ggml_tensor * node) { + while (node && (node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_GET_ROWS)) { + node = node->src[0]; + } + return node && node->op == GGML_OP_NONE && GgmlOvDecoder::is_recurrent_cache(node) ? node : nullptr; +} +} // namespace + +RecurrentReplayFusion::RecurrentReplayFusion(const std::shared_ptr & decoder, + const std::shared_ptr & tensors) : + m_decoder(decoder), + m_tensors(tensors) { + auto actual = std::dynamic_pointer_cast(decoder); + if (!actual || actual->m_naive || decoder->is_static() || decoder->is_stateful() || decoder->is_splited_model() || + !ggml_openvino_is_gpu() || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") || + !tensors->count("rs_replay_rows")) { + return; + } + m_graph = actual->get_cgraph(); + for (int i = 0; i < m_graph->n_nodes; ++i) { + const auto node = m_graph->nodes[i]; + Group group; + group.compute = i; + if (node->op == GGML_OP_GATED_DELTA_NET && node->op_params[1] > 0) { + for (int port : {5, 6, 7, 8}) { + group.banks.push_back(cache_root(node->src[port])); + } + } else if (node->op == GGML_OP_SSM_CONV && node->src[0]->op == GGML_OP_CONT && + node->src[0]->src[0]->op == GGML_OP_TRANSPOSE) { + const auto cols = node->src[0]->src[0]->src[0]; + if (cols->op != GGML_OP_CONCAT || cols->op_params[0] != 1 || cols->src[0]->op != GGML_OP_GET_ROWS) { + continue; + } + group.conv = true; + group.current = cols->src[1]; + group.banks.push_back(cache_root(cols->src[0]->src[0])); + } else { + continue; + } + if (std::any_of(group.banks.begin(), group.banks.end(), [](const ggml_tensor * bank) { + return !bank || bank->type != GGML_TYPE_F32 || bank->ne[2] != 1 || bank->ne[3] != 1; + })) { + continue; + } + auto is_bank = [&](const ggml_tensor * t) { + return std::find(group.banks.begin(), group.banks.end(), t) != group.banks.end(); + }; + // Collect only cache-owned paths. Current-token producers remain outside this group. + std::function collect = [&](const ggml_tensor * t) { + if (!t || t->op == GGML_OP_NONE || t == group.current || is_bank(t) || !group.consumed.insert(t).second) { + return; + } + for (int port = 0; port < (t->op == GGML_OP_GET_ROWS ? 1 : GGML_MAX_SRC); ++port) { + if (t->src[port]) { + collect(t->src[port]); + } + } + }; + if (group.conv) { + collect(node->src[0]); + } else { + for (int port : {5, 6, 7, 8}) { + collect(node->src[port]); + } + } + std::map resets, writes; + for (int j = 0; j < m_graph->n_nodes; ++j) { + const auto t = m_graph->nodes[j]; + if (!is_bank(t->view_src)) { + continue; + } + if (GgmlOvDecoder::is_recurrent_cache_reset(t)) { + float value; + memcpy(&value, t->op_params, sizeof(value)); + if (value != 0) { + continue; + } + ++resets[t->view_src]; + collect(t); + } else if (t->op == GGML_OP_CPY) { + const auto src = t->src[0]; + const bool extra = + src->op == GGML_OP_VIEW && src->src[0]->op == GGML_OP_GET_ROWS && cache_root(src) == t->view_src; + bool update = false; + if (group.conv) { + update = src->op == GGML_OP_VIEW && src->src[0] == node->src[0]->src[0]->src[0]; + } else { + update = src->op == GGML_OP_VIEW && src->src[0] == node; + for (int port : {1, 2, 3, 4}) { + update |= src->op == GGML_OP_VIEW && src->src[0] == node->src[port]; + } + } + if (!extra && !update) { + continue; + } + if (update) { + ++writes[t->view_src]; + } + group.consumed.insert(t); + collect(t->src[1]); + group.consumed.insert(src); + if (extra) { + collect(src); + } + } + } + bool complete = true; + for (const auto bank : group.banks) { + complete &= resets[bank] == 1 && writes[bank] == (bank == group.banks.back() && !group.conv ? 2 : 1); + } + group.consumed.insert(node); + // A bank reader or writer outside this group would race with the implicit stores. + for (int j = 0; j < m_graph->n_nodes && complete; ++j) { + const auto t = m_graph->nodes[j]; + if (group.consumed.count(t)) { + continue; + } + if (is_bank(t->view_src) && t->op != GGML_OP_VIEW && t->op != GGML_OP_RESHAPE) { + complete = false; + } + for (int port = 0; port < GGML_MAX_SRC; ++port) { + const auto src = t->src[port]; + if (!src || is_bank(src) == false) { + continue; + } + if (t->op != GGML_OP_VIEW && t->op != GGML_OP_RESHAPE) { + complete = false; + } + } + } + if (!complete) { + continue; + } + const auto id = m_groups.size(); + for (int j = 0; j < m_graph->n_nodes; ++j) { + if (group.consumed.count(m_graph->nodes[j])) { + m_nodes[j] = id; + } + } + m_groups.push_back(std::move(group)); + } + if (ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_CGRAPH")) { + const auto conv = + std::count_if(m_groups.begin(), m_groups.end(), [](const Group & group) { return group.conv; }); + GGML_LOG_INFO("ggml-openvino: replay fusion: %zu convolution, %zu GDN groups\n", size_t(conv), + m_groups.size() - conv); + } +} + +OutputVector RecurrentReplayFusion::translate(int index, const NodeContext & context) { + const auto found = m_nodes.find(index); + if (found == m_nodes.end()) { + return {}; + } + const auto & group = m_groups[found->second]; + using namespace ov::op; + auto bank_input = [&](const ggml_tensor * t) -> Output { + const auto name = GgmlOvDecoder::get_tensor_name(m_graph, t); + const auto found = m_tensors->find(name); + FRONT_END_OP_CONVERSION_CHECK(found != m_tensors->end(), "Replay input missing: ", name, " while translating ", + context.get_name()); + return found->second; + }; + if (index != group.compute) { + const auto node = m_graph->nodes[index]; + auto root = cache_root(node); + if (!root && node->view_src && + std::find(group.banks.begin(), group.banks.end(), node->view_src) != group.banks.end()) { + root = node->view_src; + } + return OutputVector(context.get_output_names().size(), bank_input(root ? root : group.banks[0])); + } + OutputVector banks; + for (const auto bank : group.banks) { + auto input = bank_input(bank); + auto source = input.get_node_shared_ptr(); + while (ov::is_type(source)) { + source = source->input_value(0).get_node_shared_ptr(); + } + FRONT_END_OP_CONVERSION_CHECK(ov::is_type(source), + "Replay banks require writable Parameter storage"); + banks.push_back(input); + } + auto rows = context.get_input("rs_replay_rows"), control = context.get_input("rs_replay_control"), + reset = context.get_input("rs_replay_reset"); + if (group.conv) { + auto x = bank_input(group.current); + const auto history = m_graph->nodes[index]->src[1]->ne[0] - 1; + auto pattern = + v0::Constant::create(element::i64, Shape{4}, std::vector{1, 1, group.current->ne[0], history + 1}); + auto weights = std::make_shared(context.get_input(1), pattern, false); + auto replay = ov::recurrent_replay::build({banks[0], rows, x, weights, control, reset}, true); + m_updated_banks[GgmlOvDecoder::get_tensor_name(m_graph, group.banks[0])] = replay[1]; + return {replay[0]}; + } + auto outputs = op::translate_recurrent_gated_delta_net_replay( + context, {banks[0], banks[1], banks[2], banks[3], rows, control, reset}); + for (size_t i = 0; i < group.banks.size(); ++i) { + m_updated_banks[GgmlOvDecoder::get_tensor_name(m_graph, group.banks[i])] = outputs[i + 1]; + } + return {outputs[0], outputs[1]}; +} +} // namespace ov::frontend::ggml diff --git a/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h new file mode 100644 index 000000000000..d02e9049c098 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h @@ -0,0 +1,34 @@ +#pragma once +#include "../ggml-decoder.h" +#include "node_context.h" + +#include +#include + +namespace ov::frontend::ggml { +// Assign variables with this prefix opt a caller-owned remote bank into writable-input fusion. +inline constexpr std::string_view replay_cache_state_prefix = "__ggml_replay_cache_"; + +class RecurrentReplayFusion { +public: + RecurrentReplayFusion(const std::shared_ptr &, const std::shared_ptr &); + OutputVector translate(int index, const NodeContext & context); + + const std::map> & updated_banks() const { return m_updated_banks; } +private: + struct Group { + int compute = -1; + bool conv = false; + const ggml_tensor * current = nullptr; + std::vector banks; + std::set consumed; + }; + + std::shared_ptr m_decoder; + std::shared_ptr m_tensors; + const ggml_cgraph * m_graph = nullptr; + std::vector m_groups; + std::map m_nodes; + std::map> m_updated_banks; +}; +} // 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 1c43c8ae0df5..5c5a6a8bd99e 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -5,9 +5,7 @@ #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 "recurrent_replay_fusion.h" #include "pass/mark_decompression_convert_constant_folding.h" #include "pass/mark_dequantization_subgraph.h" #include "pass_registry/pipeline.h" @@ -24,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -74,11 +73,8 @@ std::shared_ptr create_parameter(const std::string & name std::shared_ptr create_extra_input(const std::string & name, const ModelExtraInputInfo & input_info) { if (input_info.is_parameter) { - ov::PartialShape shape(input_info.shape); - // One SET_ROWS emits min(tokens, snapshot capacity) windows on each batch. - if (name.compare(0, 11, "rs_windows_") == 0) { - shape[2] = ov::Dimension::dynamic(); - } + const auto shape = input_info.parameter_shape.rank().is_static() ? input_info.parameter_shape : + ov::PartialShape(input_info.shape); auto param_node = std::make_shared(input_info.type, shape); param_node->set_friendly_name(name); param_node->output(0).get_tensor().set_names({name}); @@ -302,9 +298,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo } } -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map); -#endif + RecurrentReplayFusion replay_fusion(ggml_model_decoder, tensor_map); 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") { @@ -325,10 +319,7 @@ 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); - ov::OutputVector converted_outputs; -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - converted_outputs = recurrent_fusion.translate(node_idx, node_context); -#endif + auto converted_outputs = replay_fusion.translate(node_idx, node_context); if (converted_outputs.empty()) { converted_outputs = it->second(node_context); } @@ -390,15 +381,24 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo } ggml_model_decoder->visit_subgraph(node_visitor); + ov::SinkVector sinks; + const auto actual_decoder = std::dynamic_pointer_cast(ggml_model_decoder); + for (const auto & updated : replay_fusion.updated_banks()) (*tensor_map)[updated.first] = updated.second; for (const auto & name : ggml_model_decoder->get_model_output_names()) { -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - if (recurrent_fusion.is_inplace_output(name)) { - // The fused kernel updates the bound cache input; no cache Result is needed. - continue; - } -#endif FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(), "Output name not found in tensor map: ", name); + if (const auto bank = replay_fusion.updated_banks().find(name); + bank != replay_fusion.updated_banks().end() && actual_decoder && + ggml_openvino_buffer_is_remote(actual_decoder->get_model_outputs().at(name))) { + const auto & update = bank->second; + // Let the Assign input determine the state type. GPU precision conversion can rewrite + // declared variable types even when the precision-sensitive input stays in FP32. + auto variable = std::make_shared(ov::op::util::VariableInfo{ + update.get_partial_shape(), element::dynamic, std::string(replay_cache_state_prefix) + name}); + auto assign = std::make_shared(update, variable); + sinks.push_back(assign); + continue; + } auto result = std::make_shared(tensor_map->at(name)); result->set_friendly_name(name); results.push_back(result); @@ -450,7 +450,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo used_params.push_back(param); } } - resulting_model = std::make_shared(results, used_params); + resulting_model = std::make_shared(results, sinks, used_params); apply_transformations(resulting_model); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 29f7f404155b..9470302a7efa 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -10,6 +10,7 @@ #include "model-cache.h" #include "openvino/frontend.h" #include "openvino/input_model.h" +#include "openvino/recurrent_replay_fusion.h" #include #include @@ -22,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -216,12 +218,8 @@ static size_t get_static_attention_size(const std::shared_ptr & g static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) { const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); - uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results. -#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 + // Preserve the fingerprint for graphs compiled without the old native cache update ops. + uint64_t extra_cfg = 18 * 131; extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0 ? 1u : 0u); @@ -368,9 +366,17 @@ 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); + // Replay control lengths change with the batch. The compiled graph uses the declared Parameter shape. + if (input.is_parameter && input.parameter_shape.rank().is_static() && input.parameter_shape.is_dynamic()) { + append(std::numeric_limits::max()); + append_string(input.parameter_shape.to_string()); + } else { + const auto shape = input.is_parameter && input.parameter_shape.is_static() ? + input.parameter_shape.to_shape() : input.shape; + append(shape.size()); + for (const auto dim : shape) { + append(dim); + } } append(input.is_parameter); if (!input.is_parameter) { @@ -766,19 +772,10 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod 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) { + } else if (param_name.compare(0, 10, "rs_replay_") == 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 { if (extra_input->second.type == ov::element::i64) { *input_tensor.data() = extra_input->second.value; @@ -1487,8 +1484,12 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share uint64_t exact_fp = 0; std::string blob_path, manifest_path; if (!model_cache_dir.empty() && !model_is_splitted) { - const uint64_t extra_cfg = + uint64_t extra_cfg = ggml_openvino_model_cache_extra_cfg(r_ctx->stateful, stateful_recurrent); + if (ggml_decoder->get_model_extra_inputs().count("rs_replay_rows")) { + // The writable-input replay interface replaces bank Results with Assign sinks. + extra_cfg = extra_cfg * 131 + 1; + } model_fp = ggml_openvino_model_fingerprint(cgraph, device, /*fa=*/true, m_params.rope_params, 16, extra_cfg, dynamic_graph_signature(cgraph, *ggml_decoder, m_params)); @@ -1729,6 +1730,16 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share shared_model = compiled_model; } // end non-imported (compile) path + entry->replay_writebacks.clear(); + if (ggml_decoder->get_model_extra_inputs().count("rs_replay_rows")) { + constexpr auto prefix = ov::frontend::ggml::replay_cache_state_prefix; + for (auto state : infer_request->query_state()) { + const auto name = state.get_name(); + if (name.compare(0, prefix.size(), prefix) == 0) { + entry->replay_writebacks.emplace_back(name.substr(prefix.size()), std::move(state)); + } + } + } entry->ptr = ggml_decoder; if (!shared_key.empty() && shared_it == shared_cache->graphs.end()) { ov_compiled_graph graph; @@ -1904,6 +1915,14 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share } throw; } + for (const auto & [name, state] : entry->replay_writebacks) { + const auto bank = ggml_decoder->get_model_outputs().at(name); + const auto updated = state.get_state(); + OPENVINO_ASSERT(updated.get_element_type() == GgmlOvDecoder::get_ov_type(bank) && + updated.get_shape() == GgmlOvDecoder::get_shape(bank), + "Invalid replay cache writeback for ", name); + ggml_backend_tensor_set(bank, updated.data(), 0, ggml_nbytes(bank)); + } infer_end_time = ggml_time_us(); for (const auto & out : staged_outputs) { std::memcpy(out.dst, out.src, out.bytes); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index ee170a2666f1..3db84a2541a7 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -125,6 +125,7 @@ struct decoder_runtime_ctx { std::shared_ptr mutex; std::shared_ptr ptr; + std::vector> replay_writebacks; // Static path: the compiled models of this graph with their requests (ov_graph_compute_static). std::map variants;