Skip to content

ggml-openvino: correct the RESHAPE dynamic-dim comment for size-1 dims - #382

Merged
ravi9 merged 1 commit into
ravi9:dev_backend_openvinofrom
osabnis:ov-reshape-size1-dim
Nov 5, 2026
Merged

ravi9 merged 1 commit into
ravi9:dev_backend_openvinofrom
osabnis:ov-reshape-size1-dim

Conversation

@osabnis

@osabnis osabnis commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Update: the fix itself is now in dev_backend_openvino through #384, which has the same logic. This PR is rebased onto dev and now carries only the comment correction: the old comment said the RESHAPE stride match is unambiguous, which a size-1 dim breaks. The testing below also covers the merged logic.

The original description follows.


Problem

Models with a single KV head fail on the current dev_backend_openvino tip in all configurations:

Check 'backward_compatible_check || in_out_elements_equal' failed
While validating node 'opset1::Reshape reshape:Kcur-0 (view)'
Shape inference input shapes {[1,512,1,256],[4]}
Requested output shape [1,1,2,256] is incompatible with input shape

Affected models (all 6 configurations: GGML_OPENVINO_STATEFUL_EXECUTION=0/1 × -fa on/off/auto):

  • Gemma-3 1B IT (ggml-org Q4_K_M)
  • Gemma-3 270M (QuantFactory Q4_K_M)
  • Gemma-4-E2B IT (Q4_K_M)

All three models run on e602f31e9 (the commit before #370), so #370 exposed the issue. The underlying dynamic-dim
rule predates #370.

Cause

For ggml_reshape_3d(Kcur, head_dim, 1, n_tokens), the size-1 head dimension and the token dimension have the same
stride.

The RESHAPE rule in compute_node_dynamic_dims() selected the first dimension with the source stride. This marked the
head dimension as dynamic and left the token dimension static at the warm-up size of 2.

Fix

When several dimensions match the source stride, prefer the one that also matches the source dimension's size. If none
does, fall back to the first stride match, as before.

This only changes RESHAPEs where the previous match had a different size from the source dimension. #375 (open) applies
the same approach to VIEW nodes.

Testing

Environment: B70 (GPU.0), OpenVINO 2026.4.1, dev_backend_openvino at 9c238a1e5 (the two later merges, #379 and
#381, do not touch ggml-decoder.cpp).

Command: llama-completion -f <1024-token prompt> -c 1382 -n 128 -st -ngl -1 -no-cnv --ignore-eos --temp 0

Each model was run in all 6 configurations (GGML_OPENVINO_STATEFUL_EXECUTION=0/1 × -fa on/off/auto).

Affected models

Model Before After
Gemma-3 1B IT Fails 6/6 Passes 6/6; same output in all 6
Gemma-3 270M Fails 6/6 Passes 6/6
Gemma-4-E2B IT Fails 6/6 Passes 6/6

With the fix, Gemma-3 1B IT and Gemma-4-E2B IT give the same output as e602f31e9 (before #370), stateless with
-fa on.

Regression testing

Tip vs tip + this PR, same 6 configurations:

  • Llama-3.2-1B
  • SmolLM2-1.7B
  • Phi-3.5-mini
  • Phi-4-mini
  • Qwen3.5-4B
  • Gemma-2-2B
  • SmolLM3-3B
  • Qwen1.5-MoE

All give the same output, except for run-to-run GPU variation in Phi-3.5-mini and Gemma-2-2B, which shows on both
trees. A debug build that logs every RESHAPE whose dynamic dimension changes found none in those two models.

Among the tested models, the fix changes the dynamic dimension only for RESHAPEs in Gemma-3/4 and Qwen1.5-MoE. In
Qwen1.5-MoE, the ffn_norm RESHAPE now selects the token dimension; its output is unchanged.

Panther Lake (Arc B390 iGPU), OpenVINO 2026.4.1: same command and configurations, tip vs tip + this PR.

  • Gemma-3 1B IT, Gemma-3 270M, Gemma-4-E2B IT: fail 6/6 on the tip, pass 6/6 with this PR.
  • Gemma-3 4B IT (4 KV heads), Llama-3.2-1B, SmolLM2-1.7B, Phi-3.5-mini, Phi-4-mini, Qwen3.5-4B, Gemma-2-2B,
    SmolLM3-3B, Qwen1.5-MoE: same output on both trees in all 6 configurations.
  • No ops fall back to CPU in any run.

The comment above the RESHAPE stride match in compute_node_dynamic_dims()
still said the match is unambiguous because result strides are strictly
monotone. A size-1 dim has the same stride as the dim after it
([head_dim, T] -> [head_dim, 1, T] with one KV head), so it is not.

Explain the size-1 case in the block comment, drop the duplicate comment
inside the loop, and name the source dim's size once.
@ravi9
ravi9 force-pushed the ov-reshape-size1-dim branch from 2d8ffb6 to 5b0149d Compare November 5, 2026 00:55
@ravi9 ravi9 changed the title ggml-openvino: fix dynamic token dim detection for single-KV-head models ggml-openvino: correct the RESHAPE dynamic-dim comment for size-1 dims Nov 5, 2026
@ZackyLake

Copy link
Copy Markdown

actually, why not simply enforce ne and nb both matching with dynamic_dim?

@ravi9
ravi9 merged commit 8b96e9f into ravi9:dev_backend_openvino Nov 5, 2026
3 checks passed
allnes pushed a commit to allnes/openvino that referenced this pull request Nov 20, 2026
…y rows (openvinotoolkit#38996)

### Details:

With GQA, llama.cpp stacks the query heads of each KV head into rows, so
decode reaches SDPA with 3–4 query rows on common models. `sdpa_opt`
sent every query length above one to the multi-token kernels, which do
not split the keys, so long contexts ran with too few work-groups. This
PR uses the key-partitioned single-token kernel for up to 4 query rows
and fixes the bugs that multiple rows exposed in it.

#### Performance

Decode, Q4_K_M, `llama-bench tg64`, Arc B390 (Panther Lake), tokens/s
before / after / llama.cpp Vulkan:

| Model | Depth 0 | Depth 1024 | Depth 4096 | Depth 8192 |
|---|---:|---:|---:|---:|
| Llama-3.2 1B | 96.76 / 97.33 / 121.72 | 86.26 / 89.02 / 115.01 | 61.38
/ 67.49 / 102.43 | 46.49 / 52.46 / 88.72 |
| Phi-4 mini | 31.58 / 32.50 / 41.34 | 27.06 / 28.29 / 39.02 | 19.98 /
20.89 / 33.74 | 14.05 / 14.69 / 28.18 |
| Qwen3.5 4B | 21.06 / 20.89 / 32.91 | 20.28 / 20.31 / 32.21 | 18.77 /
19.08 / 31.18 | 17.02 / 17.57 / 29.89 |

- Depth 8192: +12.8% (Llama-3.2 1B), +4.5% (Phi-4 mini), +3.2% (Qwen3.5
4B); the share of Vulkan's speed goes from 52% to 59%, 50% to 52% and
57% to 59%. Depth 0 is within run-to-run noise (up to 3.5% between
rounds).
- Arc B580 (`tg128`, 4 alternating rounds), depth 4096: +25.5% Llama-3.2
1B (126.2 → 158.4), +9.6% Phi-4 mini, +5.3% Qwen3.5 4B, +3.7% Gemma-4
E2B; depth 0 within noise.
- On the B390, models that do not stack query rows (Gemma-4 E2B, SmolLM2
1.7B, Phi-3.5 mini) are unchanged.
- KL divergence against the CPU backend is unchanged: 0.041104 →
0.041087 (Llama-3.2 1B), 0.035677 → 0.035695 (Phi-4 mini), 0.024973 →
0.024896 (Qwen3.5 4B).

#### Implementation

- **`sdpa_opt.cpp`:** up to `max_single_token_rows = 4` query rows use
the key-partitioned single-token kernel. A limit of 16 slowed prompt
chunks at depth 4096 (+0.3% at 6 rows, −9% at 8, −11% at 9–12, −20% to
−26% at 15–16; depth 0 within ±2%), because this kernel reads the keys
once per query row. The micro single-token kernel stays at one row; it
was slower than `sdpa_opt` for several rows.
- Rows stay on the multi-token kernels where the single-token stages are
not exact for them (`single_token_supports_query_rows()`): per-channel
compressed KV (needs the micro kernel), a sink input (each key partition
adds the sink to its softmax sum), more than `get_max_partitions_num()`
(128) key partitions (the finalization limit, now passed to the kernel
as `MAX_PARTITIONS_NUM` instead of a kernel-local define), and a V head
wider than Q/K (the query is kept in local memory at the Q/K width, but
its loads and the output reduction use the V width). `exp_sums` and
`max_logits` are sized by the V head size.
- **`sdpa_utils.hpp`:** `is_prefill_stage()` had no other users and
becomes `get_target_seq_len()` (query rows, −1 if dynamic).

#### Fixes in `sdpa_opt.cl` exposed by several rows

- **Mask index:** `INPUT3_GET_INDEX_SAFE` does not parenthesize its
arguments, so the modulo for a mask broadcast over query rows applied
only to `seq_idx`, read out of bounds and caused GPU page faults
(`CL_OUT_OF_RESOURCES`). The arguments are parenthesized at this call
site, the only one in the GPU plugin that passes unparenthesized
expressions; fixing the macro in `fetch_data.cl` could follow up for
other kernels. Single-row decode was not affected.
- **`load_attn_mask`:** for a mask broadcast over the keys (one element
along X, e.g. a scalar mask) the `_SAFE` index wraps the first key, but
the following keys read past it. The keys now step through the mask only
when it has more than one element along X.
- **Masked keys:** a masked key is excluded in the f32 score range: the
mask is added in f32 and the combined score is clamped to the lowest
finite f32 (`SOFTMAX_ACCUMULATOR_VAL_MIN`), and causal masking assigns
that value. Clamping an f16 mask to −65504 left a masked key with a
large score above unmasked keys, and an unclamped f32 `-Inf` mask turned
a fully masked partition into NaN, which finalization kept. A fully
masked partition now has a finite maximum and zero weight in
finalization.
- **Finalization output index:** the flat output offset was wrong for a
padded output when several partitions are merged; it now uses
`SDPA_OUTPUT_GET_INDEX`, like the other output writes.

#### Tests

New in `sdpa_gpu_test.cpp`: 3, 4 and 5 query rows (static and dynamic,
batch 1 and 2), and the cases that stay on the multi-token kernels
(per-channel compressed KV, sink, more than 128 partitions).
`sdpa_few_rows_grid` checks the few-row route and the kernel that ran
against a host reference: fully masked partitions and rows (f16 and f32
masks), causal and sliding-window masks, partition edges, head sizes,
asymmetric and unaligned widths, output transpose and padding, batch
broadcast, bf16 and f32, shapes changing between calls of one dynamic
network, and scores beyond the f16 range with f16, f32 and causal masks
(on the previous kernel a masked key wins).

- **Arc B390 and B580:** `ov_gpu_unit_tests
--gtest_filter=*sdpa*:*SDPA*`: 834 passed, 0 failed.

#### Measurement setup

Local console, Windows, master `cd202900e4` (before) and this PR (after)
in one OpenVINO build where only the GPU plugin differs; the same
llama.cpp build (OpenVINO fork `675680b54` plus ravi9/llama.cpp#382,
stateless, `-fa 1`) and Q4_K_M models. Decode: `llama-bench -p 0 -n 64
-d <depth> -r 3`, one depth per call, mean of two rounds with the order
reversed in the second. KL divergence: `llama-perplexity -c 1024 -b 1`
against stored CPU logits. The PR head before the review fixes measured
within ±2% of the final head on all models and depths. The masked-key
fix leaves llama.cpp greedy output byte-identical and decode speed
within run-to-run variation (Arc B580, Llama-3.2 1B and Qwen3 8B, depth
0 and 4096).

### Tickets:

 - CVS-196699

### AI Assistance:

- AI assistance was used for analysis, kernel-fault debugging, test
execution and measurements.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants