Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
825de80
ggml-openvino: write back consumed in-place nodes of op-test graphs
ravi9 Nov 24, 2026
1e5d24b
ggml-openvino: keep the rest of the buffer in a partial in-place FILL
ravi9 Nov 24, 2026
21ae03f
ggml-openvino: fix softplus precision for large negative inputs
ravi9 Nov 24, 2026
3d0ae55
ggml-openvino: finer GPU KV rounding for decode batches
ravi9 Nov 24, 2026
5ec6354
ggml-openvino : keep the head axis of the 4-D KV cache static
cavusmustafa Nov 24, 2026
0f76941
ggml-openvino: split two one-line lambdas per clang-format
ravi9 Nov 25, 2026
3042519
ggml-openvino: KV-only prefill on the static path, with one decode st…
anikulk Nov 2, 2026
82f18e5
ggml-openvino: NPU host gather for large embedding tables
anikulk Nov 3, 2026
a95ce67
ggml-openvino: NPU host gather and KV-only prefill with the weightles…
anikulk Nov 3, 2026
f8d3e4e
ggml-openvino: let GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT apply to Q4_K/Q…
anikulk Nov 6, 2026
5cae3e1
ggml-openvino: export prefill model of every KV window for weightless…
zhaixuejun1993 Nov 23, 2026
e767f19
ggml-openvino: integer KV_SLICE, KV-only with decode windows, gemma-4…
zhaixuejun1993 Nov 25, 2026
1550ef2
ggml-openvino: keep the compiled model alive while reading its inputs…
zhaixuejun1993 Nov 25, 2026
35b416e
Merge pull request #456 from zhaixuejun1993/xuejun/gemma4-e2b-v1
zhaixuejun1993 Nov 25, 2026
29f8c67
ggml-openvino: translate recurrent cache replay graphs
wine99 Nov 25, 2026
575db27
ggml-openvino: use host USM for 4-D KV on integrated GPUs
wine99 Nov 25, 2026
b549240
Revert "ggml-openvino: use host USM for 4-D KV on integrated GPUs"
wine99 Nov 25, 2026
7956c26
ggml-openvino: key compiled replay graphs by declared control shapes
wine99 Nov 25, 2026
fed6548
ggml-openvino: represent replay writes with Assign sinks
wine99 Nov 26, 2026
b0fd84a
ggml-openvino: document writable replay graph contract
wine99 Nov 26, 2026
7b50277
ggml-openvino: remove legacy native recurrent cache ops
wine99 Nov 26, 2026
36636a9
Merge remote-tracking branch 'origin/dev_backend_openvino' into gpu-r…
wine99 Nov 27, 2026
690606b
ggml-openvino: document replay graph selection during prefill
wine99 Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 0 additions & 18 deletions ggml/src/ggml-openvino/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <recurrent_cache_update.hpp>
int main() {
auto conv = std::make_shared<ov::op::internal::RecurrentConvCacheUpdate>(ov::OutputVector{}, 3);
auto gdn = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(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()
19 changes: 4 additions & 15 deletions ggml/src/ggml-openvino/README.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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

Expand Down
44 changes: 26 additions & 18 deletions ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
Original file line number Diff line number Diff line change
@@ -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_<Parameter friendly name>`.

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.
Loading
Loading