OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU]QSA fusion ops indexer/sparse_attention definition and implement (#38902)
River Li3b0ee896233e
diff --git a/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/paged-qsa-indexer.rst b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/paged-qsa-indexer.rstnew file mode 100644index 00000000000..b3aa8a16c0c--- /dev/null+++ b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/paged-qsa-indexer.rst@@ -0,0 +1,653 @@+.. {#openvino_docs_ops_internal_PagedQSAIndexer}++PagedQSAIndexer+===============++.. meta::+ :description: Learn about PagedQSAIndexer - a paged, model-specific plan producer for Qwen Sparse Attention (QSA) under continuous batching / PagedAttention page tables. It consumes per-token RoPE cos/sin, maintains full-history raw-K, incremental summary and block-start RoPE caches over the main page table and emits selections containing only complete blocks.++**Versioned name**: *PagedQSAIndexer*++**Category**: *Internal*++**Short description**:+The *PagedQSAIndexer* is the **model-specific plan producer** for Qwen Sparse Attention (QSA) in its+**paged** form, used under **continuous batching / PagedAttention page tables**. It consumes externally projected+indexer queries and keys, applies query RMSNorm/RoPE, appends raw keys, generates summaries for completed blocks,+and produces block selections. *PagedQSAIndexer* owns its recurrent caches **in place** as explicitly-passed+paged tensors and reads the shared main PagedAttention page table (``block_indices`` / ``block_indices_begins``).+It performs the *K-side compression chain* (pooled key mean-pool, RMSNorm, RoPE with the caller-supplied cos/sin of each completed+block's first logical token), maintains the full-history ``index_key_cache``, ``index_block_rope_cache`` and+incremental ``block_index_keys_cache``, and emits a clean ``(selected_block_indices, selected_block_count)``+block-selection contract for the paired *SparseAttention* consumer, which derives the causal tail itself. It **supports page-aligned prefix caching** (see "Prefix Caching" below): because+``page_size % key_block_size == 0``, cached physical pages already have their ``block_index_keys_cache`` populated, so a+matched prompt prefix skips summary recomputation for the cached pages.++**Data flow and cache organization**++The K-side history is maintained as three in-place paged caches. The raw-K, summary and rope caches use the+main PagedAttention page table and are passed as explicit inputs.++``page_size`` (tokens per physical page) is **not an attribute**: as in *PagedAttentionExtension*, it is derived+from the cache shapes, ``page_size = index_key_cache.shape[2]``. It must equal the block size of the main+PagedAttention ``key_cache`` / ``value_cache`` and satisfy ``block_index_keys_cache.shape[2] * key_block_size == page_size``.++- ``block_index_keys_cache`` ``[num_blocks, H_ik, page_size / key_block_size, D_idx]``: the mean-pooled, RMSNorm'ed,+ first-token-RoPE'ed summary key of each *completed* block. This is the incrementally-updated artifact that+ makes the per-token update :math:`O(1)`. It is addressed by the **same page table** as the main PagedAttention+ KV cache (``block_indices`` / ``block_indices_begins``). For sequence ``s``, block ``b`` (covering logical+ tokens ``[b*r, (b+1)*r - 1]``) is stored at the physical location+ ``block_index_keys_cache[phys, :, slot_in_page, :]`` with+ ``phys = block_indices[block_indices_begins[s] + (b * r) // page_size]`` and+ ``slot_in_page = (b * r % page_size) // r``. The second dimension is the **configurable index-key head count+ ``H_ik``** (never hard-coded to ``1``). This requires+ ``page_size % key_block_size == 0`` so every summary slot maps to a fixed position inside one physical page.++- ``index_key_cache`` ``[num_blocks, H_ik, page_size, D_idx]``: all projected, unnormalized, unrotated+ indexer keys stored at their logical token positions. For sequence ``s`` and logical token ``pos``, the operation writes+ ``index_key_cache[phys, :, pos % page_size, :]`` where+ ``phys = block_indices[block_indices_begins[s] + pos // page_size]``. The second dimension is the configurable+ index-key head count ``H_ik``. This is full-history storage, not a per-sequence ring: it removes ring wraparound,+ capacity sizing, and cross-block slot-alias hazards, at the cost of memory proportional to the full sequence.+- ``index_block_rope_cache`` ``[num_blocks, page_size / key_block_size, 2 * indexer_rotary_dim]``: the RoPE+ coefficients of each QSA block's first logical token, stored as one row that interleaves its ``rope_cos`` and+ ``rope_sin`` rows, ``(cos_0, sin_0, cos_1, sin_1, ...)``, and addressed through the same page table and at the+ same per-page granularity as+ ``block_index_keys_cache``. Written+ once, when that first token is processed (which may be an earlier invocation than the one that completes the+ block), and read back once when the block completes to rotate its summary. Only one row per block is kept, not+ one per raw key.+- ``rope_cos`` / ``rope_sin`` ``[tokens, indexer_rotary_dim]``: per-token rotate-half RoPE coefficients of the+ current tokens in the Hugging Face layout (``cat(freqs, freqs)``, both halves equal), row ``t`` aligned with+ ``index_query`` row ``t``. They are the same per-token+ cos/sin consumed by the main attention RoPE, so the indexer shares its RoPE coordinates (including any mRoPE or+ other multi-axis position scheme, resolved by the producer) and needs neither ``position_ids`` nor a+ position-indexed rotary table. A query is rotated with its own row; the row of a block's first token is copied+ into ``index_block_rope_cache`` for that block's summary.++A block is *completed* once exactly :math:`r` raw keys have been appended. The flush reads the block's contiguous+raw-key slice from the shared paged cache and writes its pooled, normalized, first-token-rotated summary+into ``block_index_keys_cache``. The last, partially-filled block is not summarized and is never included in this+operation's selection. *SparseAttention* independently derives and processes the causal tail for each query from its+logical position.++**Prefix Caching**++Because ``page_size % key_block_size == 0``, a cached physical page always has every ``block_index_keys_cache`` slot for+its completed blocks already populated — the summary layout is page-aligned. Prefix caching is **page-aligned**:+the scheduler only matches prefixes whose length is a whole multiple of ``page_size``.++.. note::+ **Why page-aligned matching is required.** Since ``page_size % key_block_size == 0``, any page-aligned+ ``matched_len`` (a multiple of ``page_size``) also satisfies ``matched_len % key_block_size == 0``, so the new+ sequence starts at a complete-block boundary. Its shared physical pages contain raw-K history, summaries and+ block-start RoPE rows, and are only **read**; the suffix writes into **new** pages, so no copy-on-write is+ needed. Prefix matching remains page-aligned because the page table shares whole physical pages, not partial+ pages. If the matched prefix is not a whole multiple of ``page_size``, it must be **rounded down** to the page+ boundary (``matched_len := matched_len - matched_len % page_size``); otherwise the suffix would need to write+ into a shared physical page.++**Execution flow.** When a new request's prompt shares a page-aligned prefix with a previously-cached one, the+scheduler:++1. Detects the shared prefix length, **rounds it down** to a multiple of ``page_size``, and advances ``past_lens``+ by that length (``past_lens[B] = matched_len``). The shared KV pages — and therefore their ``block_index_keys_cache``+ rows — are reused by the page table; ``block_indices[B]`` points at the shared pages first, then at new pages+ for the suffix.+2. The op processes only the *unmatched suffix* (logical positions ``>= past_lens[B]``), writing raw keys and+ newly completed summaries into the **new** suffix pages. No COW, no overwrite of the shared prefix pages.+3. The op **skips recomputing summaries for the cached prefix pages**: it only scores against the existing summary+ keys of the shared prefix blocks (reading them directly) plus the newly-written suffix summaries. The matching+ raw-K pages are retained as full history and are likewise read-only for the shared prefix.++This is *lossless* with respect to the sparse plan **given deterministic summary computation**: the summary keys+for the prefix blocks are byte-identical to what a fresh prefill would have produced, so the emitted+``(selected_block_indices, selected_block_count)`` for the suffix is exactly what it would be had the prefix been re-computed. The cost+of prefix caching is therefore only the *scoring* over the (already-summarized) prefix blocks, not the+*construction* of those summaries.++**Worked example.** Let ``page_size = 16`` and ``key_block_size = 4``. Request A writes 40 tokens:+page ``P0 = [0..15]`` (blocks 0–3), page ``P1 = [16..31]`` (blocks 4–7), page ``P2 = [32..39]`` (blocks 8–9, the+last page partially filled). Request B shares the first 35 tokens of A. Whole pages shared: ``32 = floor(35 / 16) *+16``, so ``past_lens[B] = 32`` and ``block_indices[B] = [P0, P1, Pnew]``. B's suffix is tokens ``32..`` in ``Pnew``;+it processes logical positions ``32, 33, ...`` (fresh raw-K writes to the suffix pages). At logical position ``pos = 40``+(block ``10``), B scores blocks ``0..7`` from shared pages ``P0/P1`` and blocks ``8, 9`` from its own ``Pnew``+(just flushed).++**Why page-aligned rounding is mandatory.** If one attempted to share ``34`` tokens, the page table could not+represent that prefix as whole shared pages: the page containing tokens ``32, 33`` would also contain positions+that B must write independently. Sharing that page would alias the two sequences' writable raw-K/summary storage;+copying or allocating a private page is required. Therefore the prefix length is rounded down to the page boundary.++**Full-prompt hit.** When the whole prompt is cached, the scheduler must still run at least one prompt token to+produce logits. It MUST back off by a **whole page**, not by one token: with ``matched_len`` already rounded down,+if ``matched_len == prompt_len`` then ``matched_len := prompt_len - page_size`` and the last prompt page is not+shared; B gets a private page for it and recomputes its ``page_size`` tokens (raw K, block-start RoPE rows and+summaries). Setting ``past_lens[B] = prompt_len - 1`` instead is invalid: the replayed token would write raw K+(and, when it completes a block, a summary) into a shared physical page. If ``prompt_len`` is not a multiple of+``page_size``, the rounding above already leaves a non-empty suffix and no extra back-off is needed. In the+worked example, a request B whose 32-token prompt equals A's first 32 tokens gets ``past_lens[B] = 16`` and+``block_indices[B] = [P0, Pnew]``, and recomputes tokens ``16..31``.++.. note::+ **Rollback (e.g. speculative decoding).** There is no ``ring_capacity`` and no raw-K ring window, so rollback+ depth is not limited by the op, only by the pages the scheduler still retains. To roll sequence ``s`` back to+ logical length ``L``, the scheduler sets ``past_lens[s] = L`` and replays from position ``L``. The op keeps no+ separate valid-length state: the visible summaries of every query are derived from its logical position+ (``n_complete = floor((pos + 1) / r)``), so summaries of blocks beyond ``L`` are hidden automatically and are+ overwritten when the replay completes those blocks again. The replay overwrites raw K at the same logical+ positions, rewrites ``index_block_rope_cache`` for every replayed block start, and recomputes the summary of every+ block it completes. A block that started before ``L`` (``L % r != 0``) reuses its retained first ``L % r`` raw+ keys and its retained RoPE row. Rolling back into a page shared through prefix caching is not allowed, because+ the replay would write into that shared page; the scheduler must first give the sequence a private copy of the+ page (the same copy-on-write it applies to the main KV cache).++**Logical positions and RoPE coordinates**++The op separates the *logical KV index* used for block addressing and causal filtering from the *RoPE+coefficients* used for positional rotation. The **logical position** of a token is derived from ``past_lens`` and+the sequence partition (``subsequence_begins``): for sequence ``s`` and token ``t``,+:math:`pos = past\_lens[s] + (t - subsequence\_begins[s])`. This logical position drives (a) which blocks are+causally valid and (b) the raw-K, summary and rope-cache page/offset. It is never used as a RoPE angle: query+``t`` is rotated with ``(rope_cos[t], rope_sin[t])``, and the summary of block ``b`` is rotated with the+coefficients of the token at logical position ``b * r`` (the block's first token), read from+``index_block_rope_cache`` rather than recomputed from ``b * r``. ``index_block_rope_cache`` is written once, in+whichever invocation first appends the block's first token, so by the time the block completes (possibly several+invocations later) the coefficients are already resident. When one invocation both starts and completes a block,+an implementation may use that invocation's own ``rope_cos``/``rope_sin`` row instead of reading back the+just-written cache row; the result is identical.++**Position schemes.** The op never sees position ids or rotary frequencies, so any scheme the producer applies to+the per-token cos/sin (mRoPE sections, non-monotonic or gapped positions, scaled RoPE variants) is reproduced+exactly, without an op change. Block membership (which ``r`` raw keys form one block) still follows the plain+logical-token count; only the coefficients applied to the pooled result come from the block's first token.++**Score computation**++For a query at logical position :math:`p` with normalized and rotated query+:math:`q_h = \mathrm{RoPE}_{\rho(p)}(\mathrm{RMSNorm}(q^{idx}_h)) \in \mathbb{R}^{D_{idx}}` (per index-query+head :math:`h`, stored as *T*) and block :math:`b` whose per-index-key-head summary key is+:math:`\bar{k}_{b,\mathrm{kv}(h)} \in \mathbb{R}^{D_{idx}}`, the per-selection-head score is a **grouped reduction+over index-query heads**:++.. math::++ H_{iq} \bmod H_{ik} = 0, \quad G = H_{iq} / H_{ik}, \quad \mathrm{kv}(h) = \lfloor h / G \rfloor, \quad+ \mathrm{sel}(h) = \lfloor \mathrm{kv}(h) \cdot H_{sel} / H_{ik} \rfloor++ s_{b, sh} = \mathrm{scale} \cdot \sum_{\substack{h \in [0, H_{iq}) \\ \mathrm{sel}(h) = sh}}+ \mathrm{ReLU}\!\left( \langle q_{h},\, \bar{k}_{b,\mathrm{kv}(h)} \rangle \right)++where :math:`\bar{k}_{b,\mathrm{kv}(h)} =+\mathrm{RoPE}_{\rho(b\cdot r)}(\mathrm{RMSNorm}(\tfrac{1}{r}\sum_{j=0}^{r-1} k_{b\cdot r + j,\mathrm{kv}(h)}))`+is the per-index-key-head block summary key and :math:`\rho(p)` is the ``(rope_cos, rope_sin)`` row of the token at+logical position :math:`p`, as recorded in ``index_block_rope_cache``. Queries use :math:`\rho` of their own token.+The rotation is the split-half (rotate-half) RoPE of Hugging Face Transformers over the first+:math:`R = \mathrm{indexer\_rotary\_dim}` channels, computed in ``fp32``; the channels after :math:`R` are not+rotated:++.. math::++ x' = x \odot \cos + \mathrm{rotate\_half}(x) \odot \sin, \quad+ \mathrm{rotate\_half}(x) = (-x_{R/2}, \ldots, -x_{R-1}, x_0, \ldots, x_{R/2-1})++with ``cos`` and ``sin`` the ``R``-wide ``rope_cos``/``rope_sin`` row. In Hugging Face RoPE both halves of a row are+equal, so this is :math:`x'_j = x_j \cos_j - x_{j + R/2} \sin_j`,+:math:`x'_{j + R/2} = x_{j + R/2} \cos_j + x_j \sin_j` for :math:`0 \le j < R/2`.++The ReLU is applied *per index-query head before reduction over+heads*, matching the QSA scoring semantics. Under QSA (:math:`H_{iq} = 4`, :math:`H_{ik} = 1`,+:math:`H_{sel} = 1`) all four index-query heads map to the single selection head.++**Selection heads vs. index-key heads**++- ``H_ik`` (index-key heads): the heads of the indexer *key* projection, taken from the ``raw_index_keys`` shape. Each+ produces an independent per-block summary key.+- ``H_iq`` (index-query heads): the heads of the indexer *query* projection, taken from the ``index_query`` shape, with+ ``H_iq % H_ik == 0``.+- ``num_selection_heads`` (:math:`H_{sel}`): the heads of the emitted *selection*, in ``{1, H_ik}``. Under QSA,+ :math:`H_{sel} = 1` — a single shared selection drives every query/KV head of the main attention.++The grouping is fully determined by ``H_iq % H_ik == 0`` and ``H_sel`` (see the formula above); there is no+additional partition constraint.++The RMSNorm used for the pooled block key is defined as++.. math::++ \mathrm{rms\_norm}(x, w, \mathrm{epsilon}) = x \cdot \mathrm{rsqrt}\!\left( \mathrm{mean}(x^2) + \mathrm{epsilon} \right) \cdot w++computed in ``fp32`` regardless of the input precision. Qwen's Gemma-style scale :math:`(1 + w)` is folded by the+model converter into the stored weight :math:`w' = 1 + w`, so the op consumes the already-shifted weight.++**Numerics of the block summary.** The pooled key is accumulated in ``fp32`` and rounded to *T* before RMSNorm,+matching the reference model (``mean(k.float()).to(k.dtype)``); RMSNorm and RoPE are then evaluated in ``fp32``+and the result is stored to ``block_index_keys_cache`` as *T*. An implementation MAY keep the pooled mean in ``fp32``+instead of rounding it to *T*; the summaries then differ by at most one rounding of *T*, which can change the+selection only among blocks whose scores are equal within that error.++**Numerics of the query.** ``index_query`` is RMSNorm'ed and rotated in ``fp32`` and the result is rounded once to *T*+(``f16`` on GPU) before scoring. The dot products, ReLU, head reduction and ``scale`` are evaluated in ``fp32``+on the *T* query and *T* summary values. The reference model rounds the query to *T* after RMSNorm and again+after RoPE; an implementation MAY do so, which differs by at most one rounding of *T*.++**Score scale.** ``scale`` multiplies every score of a query by the same positive constant, so it never changes+the ranking: in exact arithmetic ``selected_block_indices`` and ``selected_block_count`` do not depend on its value. It is kept for+parity with the reference scoring (``1 / sqrt(indexer_head_dim)``); an implementation MAY omit the+multiplication.++**Selection, tie-breaking, and top-k**++- A block is *causally valid* for a query at logical position :math:`p` iff its last token is at most :math:`p`,+ i.e. :math:`N_{complete}(p) = \lfloor (p + 1) / r \rfloor`. Only these causally-valid complete blocks participate+ in the top-k.+- The number of selected *complete* blocks per selection head is capped at ``block_topk``; the output width is+ ``K_max = block_topk``. ``selected_block_count`` counts complete-block IDs only and is exactly+ ``min(block_topk, n_complete)``; no tail ID or tail token indices are emitted.+- **Tie-breaking and ordering**: among equal scores the *smaller block index* (earlier block) wins; the op+ computes the selection as ``argsort(-scores, kind='stable')``, takes the first ``k`` entries, and emits them in+ **strictly ascending** block order (``sort(order[:k])``), yielding a deterministic, implementation-independent,+ monotone result. The valid output prefix ``selected_block_indices[t, sh, :selected_block_count[t, sh]]`` is sorted ascending.+- **Causal tail**: it is not part of the selection output. *SparseAttention* derives+ ``tail_start = floor((p+1)/r) * r`` for each query and attends token positions ``tail_start..p`` inclusive;+ this span is empty at a complete-block boundary.++**Pseudo-code (numpy)**++.. code-block:: py+ :force:++ import numpy as np++ def relu(x):+ return np.maximum(x, 0)++ def rms_norm(x, w, epsilon):+ # fp32 over the last axis; w is the already-shifted (1 + w) weight+ x = x.astype(np.float32)+ return x / np.sqrt(np.mean(x * x, axis=-1, keepdims=True) + epsilon) * w.astype(np.float32)++ def apply_partial_rope(x, cos, sin, rotary_dim):+ # Hugging Face rotate-half over the first rotary_dim channels, in fp32; cos/sin: [..., rotary_dim]+ half = rotary_dim // 2+ x = x.astype(np.float32)+ r = x[..., :rotary_dim].copy()+ rotated = np.concatenate([-r[..., half:], r[..., :half]], axis=-1)+ x[..., :rotary_dim] = r * cos + rotated * sin+ return x++ def seq_of_token(t, subsequence_begins):+ # the unique s with subsequence_begins[s] <= t < subsequence_begins[s + 1]+ return int(np.searchsorted(subsequence_begins, t, side='right')) - 1++ def paged_qsa_indexer(index_query, raw_index_keys, rope_cos, rope_sin,+ q_norm_weight, k_norm_weight,+ past_lens, subsequence_begins,+ block_indices, block_indices_begins,+ index_key_cache, index_block_rope_cache, block_index_keys_cache,+ *, key_block_size, block_topk, num_selection_heads,+ indexer_rotary_dim, indexer_head_dim,+ epsilon, scale):+ # index_query: [tokens, H_iq * D_idx] (raw external projection; norm/RoPE applied here)+ # raw_index_keys: [tokens, H_ik * D_idx] (raw external projection)+ # rope_cos, rope_sin: [tokens, indexer_rotary_dim] (per-token rotate-half coefficients)+ # q_norm_weight, k_norm_weight: [D_idx]+ # past_lens: [num_sequences] (logical length of each sequence before this step)+ # subsequence_begins: [num_sequences + 1] split pointers into the token stream (len == tokens)+ # block_indices: [total_logical_blocks] logical -> physical block map (shared with main PA)+ # block_indices_begins: [num_sequences + 1] split pointers into block_indices (len == total_logical_blocks)+ # index_key_cache: [num_blocks, H_ik, page_size, D_idx] (full history, shared page table)+ # index_block_rope_cache: [num_blocks, page_size // r, 2 * indexer_rotary_dim], interleaved (cos_j, sin_j)+ # block_index_keys_cache: [num_blocks, H_ik, page_size // r, D_idx]+ # returns: selected_block_indices [tokens, H_sel, K_max] (int32; -1 = pad), K_max = block_topk+ # selected_block_count [tokens, H_sel] (int32)+ tokens = index_query.shape[0]+ num_sequences = past_lens.shape[0]+ Hiq = index_query.shape[1] // indexer_head_dim # index-query heads, derived from the shape+ Hik = raw_index_keys.shape[1] // indexer_head_dim # index-key heads, derived from the shape+ Hsel = num_selection_heads+ r = key_block_size+ page_size = index_key_cache.shape[2] # derived from the cache, not an attribute+ Dr = indexer_rotary_dim+ Kmax = block_topk+ G = Hiq // Hik # index-query heads per index-key head+ spp = page_size // r # block slots per physical page+ assert page_size % r == 0 and Hiq % Hik == 0 and Hsel in (1, Hik)++ k = np.reshape(raw_index_keys, (tokens, Hik, indexer_head_dim))+ q = np.reshape(index_query, (tokens, Hiq, indexer_head_dim))+ q = rms_norm(q, q_norm_weight, epsilon)+ q = apply_partial_rope(q, rope_cos[:, None, :], rope_sin[:, None, :], indexer_rotary_dim)+ q = q.astype(index_query.dtype) # rounded once to T before scoring+ # 1. Per-token K-side update, addressed by logical page and offset. Full-history raw K+ # means no ring wraparound or ring-capacity constraint.+ for s in range(num_sequences):+ base = past_lens[s] # logical position of the first token of this chunk+ for t in range(subsequence_begins[s], subsequence_begins[s + 1]):+ pos = base + (t - subsequence_begins[s]) # global logical position+ # page_size % r == 0, so a block's raw keys, summary and rope row share one physical page.+ phys = block_indices[block_indices_begins[s] + pos // page_size]+ slot = (pos // r) % spp+ index_key_cache[phys, :, pos % page_size, :] = k[t] # [Hik, Di] (H_ik configurable)+ if pos % r == 0:+ # First token of block `pos // r`: record its RoPE coefficients once.+ index_block_rope_cache[phys, slot, 0::2] = rope_cos[t]+ index_block_rope_cache[phys, slot, 1::2] = rope_sin[t]+ if pos % r == r - 1:+ # Block `pos // r` is now complete: read its page-local raw-K slice, mean-pool (fp32),+ # RMSNorm, then rotate with its first token's recorded coefficients.+ raw_start = (pos - (r - 1)) % page_size+ pooled = np.mean(index_key_cache[phys, :, raw_start:raw_start + r, :]+ .astype(np.float32), axis=1).astype(raw_index_keys.dtype) # [Hik, Di]+ nb = rms_norm(pooled, k_norm_weight, epsilon) # [Hik, Di]+ row = index_block_rope_cache[phys, slot, :]+ bar = apply_partial_rope(nb, row[0::2], row[1::2], Dr)+ block_index_keys_cache[phys, :, slot, :] = bar # [Hik, Di]++ # 2. Score the causally-valid complete blocks per selection head (grouped per-query-head reduction).+ scores = {}+ for t in range(tokens):+ s = seq_of_token(t, subsequence_begins)+ pos = past_lens[s] + (t - subsequence_begins[s])+ n_complete = (pos + 1) // r+ for sh in range(Hsel):+ for b in range(n_complete):+ phys = block_indices[block_indices_begins[s] + (b * r) // page_size]+ slot_in_page = (b * r % page_size) // r+ score = 0.0+ for kv in range(Hik):+ if (kv * Hsel) // Hik != sh:+ continue+ bar = block_index_keys_cache[phys, kv, slot_in_page, :].astype(np.float32) # [Di]+ q_h = q[t, kv * G:(kv + 1) * G, :].astype(np.float32) # [G, Di]+ # ReLU per index-query head on the dot product, then sum over heads (reference: relu(q·k).sum(heads))+ score += np.sum(relu(np.sum(q_h * bar[None, :], axis=-1)))+ scores[(t, sh, b)] = score * scale++ # 3. Top-k over causally-valid complete blocks per selection head; stable tie-break, ascending order.+ selected_block_indices = np.full((tokens, Hsel, Kmax), -1, dtype=np.int32)+ selected_block_count = np.zeros((tokens, Hsel), dtype=np.int32)+ for t in range(tokens):+ s = seq_of_token(t, subsequence_begins)+ pos = past_lens[s] + (t - subsequence_begins[s])+ n_complete = (pos + 1) // r+ for sh in range(Hsel):+ n_sel = min(block_topk, n_complete)+ scores_arr = np.array([scores[(t, sh, b)] for b in range(n_complete)], dtype=np.float32)+ order = np.argsort(-scores_arr, kind='stable')+ picked = np.sort(order[:n_sel]) # strictly ascending block indices+ selected_block_indices[t, sh, :n_sel] = picked+ selected_block_count[t, sh] = n_sel+ return selected_block_indices, selected_block_count+++**Attributes**++* *key_block_size*++ * **Description**: :math:`r`, the number of raw token keys pooled into one block key (``4`` for Qwen QSA).+ * **Type**: ``int``+ * **Required**: *yes*+ * **Constraints**: ``key_block_size >= 1``. The derived ``page_size`` must be a multiple of ``key_block_size``+ (this is what makes Prefix Caching page-aligned and lossless).++* *block_topk*++ * **Description**: Maximum number of *complete* blocks selected per selection head and the output width+ ``K_max``. The causal tail is not part of this output and does not consume a selection slot. For Qwen QSA it is+ ``indexer_budget / key_block_size``.+ * **Type**: ``int``+ * **Required**: *yes*+ * **Constraints**: ``block_topk >= 1``.++* *num_selection_heads*++ * **Description**: Number of selection heads :math:`H_{sel}` in the emitted contract. Must be ``1`` or+ ``H_ik`` (the index-key head count taken from ``raw_index_keys``). Each index-query head :math:`h` is mapped to a+ selection head via :math:`\mathrm{sel}(h) = \lfloor \mathrm{kv}(h) \cdot H_{sel} / H_{ik} \rfloor`, where+ :math:`\mathrm{kv}(h) = \lfloor h / G \rfloor` and :math:`G = H_{iq} / H_{ik}`.+ * **Type**: ``int``+ * **Default value**: ``1``+ * **Required**: *no*+ * **Constraints**: ``num_selection_heads == 1`` (QSA default) or ``num_selection_heads == H_ik``.++* *indexer_rotary_dim*++ * **Description**: RoPE dimension used by the indexer (partial rotary). Only the first+ ``indexer_rotary_dim`` channels of each query head and block summary are rotated; the trailing+ ``indexer_head_dim - indexer_rotary_dim`` channels are passed through unrotated. ``rope_cos`` / ``rope_sin``+ carry ``indexer_rotary_dim`` coefficients per token; an ``index_block_rope_cache`` row carries+ ``2 * indexer_rotary_dim`` interleaved values ``(cos_0, sin_0, cos_1, sin_1, ...)``. Because ``rope_cos`` / ``rope_sin`` are shared with the main+ attention RoPE, this equals the main attention rotary dimension.+ * **Type**: ``int``+ * **Required**: *yes*+ * **Constraints**: even, ``0 <= indexer_rotary_dim <= indexer_head_dim``.++* *indexer_head_dim*++ * **Description**: Head dimension :math:`D_{idx}` of the indexer.+ * **Type**: ``int``+ * **Required**: *yes*+ * **Constraints**: ``indexer_head_dim >= 1``.++* *epsilon*++ * **Description**: Epsilon for both RMSNorms (query and pooled block key).+ * **Type**: ``float``+ * **Default value**: ``1e-6``+ * **Required**: *no*+ * **Constraints**: ``epsilon > 0``.++* *scale*++ * **Description**: Positive multiplier applied to every block score (see "Score scale"). It does not affect+ the selection outputs. When omitted, the default is resolved at op construction, so a serialized IR always+ carries the actual value.+ * **Type**: ``float``+ * **Default value**: ``1.0 / sqrt(indexer_head_dim)``+ * **Required**: *no*+ * **Constraints**: ``scale > 0``.+++**Inputs**++* **0**: ``index_query``+ A 2D tensor of type *T* with shape ``[tokens, H_iq * D_idx]``.+ Raw projected indexer queries before indexer RMSNorm and RoPE. The operation applies both internally. **Required.**++* **1**: ``raw_index_keys``+ A 2D tensor of type *T* with shape ``[tokens, H_ik * D_idx]``.+ Current-step projected indexer keys. The index-key head count ``H_ik`` is derived from this shape and may be+ greater than one. Keys are written to the full-history+ raw-K cache at the logical token position. **Required.**++* **2**: ``rope_cos``+ A 2D tensor of type *T* with shape ``[tokens, indexer_rotary_dim]``. ``rope_cos[t, :]`` is the rotate-half RoPE+ cosine of token ``t`` for the first ``indexer_rotary_dim`` channels, in the Hugging Face layout+ (``cat(freqs, freqs)``, both halves equal).+ Intended to be the same per-token cosine tensor consumed by the main attention RoPE; the operation does not+ recompute angles, so producers should evaluate them in ``fp32`` before any cast to *T*. **Required.**++* **3**: ``rope_sin``+ A 2D tensor of type *T* with shape ``[tokens, indexer_rotary_dim]``; the sine counterpart of ``rope_cos``+ with the same layout. **Required.**++* **4**: ``q_norm_weight``+ A 1D tensor of type *T* with shape ``[D_idx]``. RMSNorm weight for raw projected indexer queries. **Required.**++* **5**: ``k_norm_weight``+ A 1D tensor of type *T* with shape ``[D_idx]``.+ RMSNorm weight for pooled block keys. **Required.**++* **6**: ``past_lens``+ A 1D tensor of type *T_IND* with shape ``[num_sequences]``.+ Logical KV length of each sequence before this step. When Prefix Caching matches a prompt prefix, this is+ advanced by the matched prefix length, so the op skips the cached prefix pages. The global logical position of a+ token is ``past_lens[s] + (t - subsequence_begins[s])``. **Required.**++* **7**: ``subsequence_begins``+ A 1D tensor of type *T_IND* with shape ``[num_sequences + 1]``.+ Splits the token stream among sequences: sequence ``s`` uses tokens+ ``[subsequence_begins[s] : subsequence_begins[s + 1]]``. **Required.**++* **8**: ``block_indices``+ A 1D tensor of type *T_IND* with shape ``[total_logical_blocks]``.+ The main PagedAttention logical-to-physical block map; also addresses ``index_key_cache``,+ ``block_index_keys_cache`` and ``index_block_rope_cache``. **Required.**++* **9**: ``block_indices_begins``+ A 1D tensor of type *T_IND* with shape ``[num_sequences + 1]``.+ Splits ``block_indices`` among sequences: sequence ``s`` owns blocks+ ``block_indices[block_indices_begins[s] : block_indices_begins[s+1]]``. **Required.**++* **10**: ``index_key_cache``+ A 4D tensor of type *T* with shape ``[num_blocks, H_ik, page_size, D_idx]``; ``page_size`` is read from+ ``shape[2]``. Full-history cache of projected, unnormalized, unrotated keys, addressed through the same ``block_indices`` /+ ``block_indices_begins`` page table as the main KV cache. For logical position ``pos``, the operation writes to physical+ page ``block_indices[block_indices_begins[s] + pos // page_size]`` and offset ``pos % page_size``. The ``H_ik``+ head count is configurable, never hard-coded to ``1``. Updated in place. **Required.**++* **11**: ``index_block_rope_cache``+ A 3D tensor of type *T* with shape ``[num_blocks, page_size // key_block_size, 2 * indexer_rotary_dim]``.+ One row per QSA block holding the RoPE coefficients of that block's first logical token, interleaved as+ ``(cos_0, sin_0, cos_1, sin_1, ...)``, i.e. ``row[2j] = rope_cos[t, j]`` and ``row[2j + 1] = rope_sin[t, j]``+ for ``0 <= j < indexer_rotary_dim``.+ Addressed through the same page table as ``block_index_keys_cache``: physical page+ ``block_indices[block_indices_begins[s] + pos // page_size]``, slot+ ``(pos // key_block_size) % (page_size // key_block_size)``. Written once, in whichever invocation appends the+ token with ``pos % key_block_size == 0``, and read back once the block completes to rotate that block's summary.+ Updated in place. **Required.**++* **12**: ``block_index_keys_cache``+ A 4D tensor of type *T* with shape ``[num_blocks, H_ik, page_size // key_block_size, D_idx]``.+ Mean-pooled + RMSNorm'ed + first-token-RoPE'ed summary keys of each completed block, addressed through the+ shared main PA page table (``block_indices`` / ``block_indices_begins``). The ``H_ik`` head count is+ configurable, never hard-coded to ``1``. Updated in place. **Required.**++Inputs 10, 11 and 12 are mutated in place. When they are model inputs, the bound tensors MUST be device-visible+storage of the exact port element type (e.g. a GPU RemoteTensor or USM host tensor); a runtime that would stage+them through a host copy or precision conversion MUST reject the binding instead of silently dropping the update.+A scheduler that copies, swaps or forks physical pages of the main KV cache (copy-on-write, beam search) MUST+apply the same page operation to inputs 10, 11 and 12.+++**Outputs**++* **0**: ``selected_block_indices``+ A 3D tensor of type *T_IND* with shape ``[tokens, H_sel, K_max]``, where ``K_max = block_topk``.+ Contains only selected complete-block IDs. For query ``t`` and selection head ``sh``, the valid prefix+ ``selected_block_indices[t, sh, :selected_block_count[t, sh]]`` is **strictly ascending and duplicate-free**; ``-1`` is padded only+ after the prefix (no interior holes). *SparseAttention* derives the causal tail per query; it is not represented+ in this output. **Required.**++* **1**: ``selected_block_count``+ A 2D tensor of type *T_IND* with shape ``[tokens, H_sel]``.+ Number of selected complete-block IDs per selection head per query, equal to+ ``min(block_topk, n_complete)``. Tail tokens are not counted. **Required.**++For the QSA configuration ``H_sel = 1``, the logical selection ABI is ``selected_block_indices[T, K]`` and+``selected_block_count[T]``, with ``T = tokens`` and ``K = block_topk``. The explicit ``H_sel`` axis above is retained for+the generalized multi-selection-head form.+++**Shape inference and type rules**++* ``T`` is a floating-point type (``float32``, ``float16``, ``bfloat16``) shared by all floating-point inputs.+* ``T_IND`` is ``int32`` (the page-table inputs and both outputs).+* ``tokens``, ``num_sequences`` and ``subsequence_begins`` must be consistent:+ ``subsequence_begins[0] == 0`` and ``subsequence_begins[-1] == tokens``.+* ``block_indices_begins[0] == 0`` and ``block_indices_begins[-1] == len(block_indices)`` (block splits).+* ``index_query`` last dimension equals ``H_iq * indexer_head_dim``; ``raw_index_keys`` last dimension equals+ ``H_ik * indexer_head_dim``, with both head counts derived from the shapes and ``H_iq % H_ik == 0`` and+ ``H_sel`` in ``{1, H_ik}``.+* ``page_size`` is derived as ``index_key_cache.shape[2]`` and must satisfy ``page_size % key_block_size == 0``+ and equal the main KV cache block size; ``block_index_keys_cache`` dim 2 equals ``page_size // key_block_size``, dim 1+ equals ``H_ik``, and dim 0 equals ``num_blocks`` (shared with the main KV ``key_cache`` dim 0).+* ``index_key_cache`` dim 0 equals ``num_blocks`` (shared with main KV cache), dim 1 equals ``H_ik``, and dim 2+ equals ``page_size``; it stores raw K for the full logical history, with no ring-capacity attribute.+* ``rope_cos`` and ``rope_sin`` both have shape ``[tokens, indexer_rotary_dim]``, with dim 0 equal to the+ ``index_query`` dim 0.+* ``index_block_rope_cache`` dim 0 equals ``num_blocks`` (shared with the main KV cache and ``index_key_cache``),+ dim 1 equals ``page_size // key_block_size`` (shared with ``block_index_keys_cache``) and dim 2 equals+ ``2 * indexer_rotary_dim``; it must be writable and stores one row per completed-or-pending block, not a per-token+ or ring-capacity tensor.+* ``selected_block_indices`` last dimension ``K_max`` equals ``block_topk``; ``selected_block_count[t, sh] == min(block_topk, n_complete)``+ per query, hence ``<= K_max``. The valid+ prefix ``selected_block_indices[t, sh, :selected_block_count[t, sh]]`` is **strictly ascending** and contains no ``-1`` entries.+* ``selected_block_count == 0`` only when ``n_complete == 0`` (``pos < key_block_size - 1``). A causal *SparseAttention*+ consumer still attends the automatically-derived tail ``0..pos`` in that case, so its result is nonzero.++**Types**++* *T*: ``float32``, ``float16`` or ``bfloat16``.+* *T_IND*: ``int32``.+++**Example**++The example below shows a single query token at logical position ``9`` (``past_lens[0] = 9``, one token in the+step) with ``key_block_size = 4``, ``block_topk = 2`` (so ``K_max = block_topk = 2``), ``num_selection_heads = 1``,+``H_iq = 4``, ``H_ik = 1``, and ``page_size = 16`` (taken from ``index_key_cache.shape[2]``). The history written before this step covers+blocks ``{0:[0..3], 1:[4..7]}`` (complete) and block ``2:[8]`` (incomplete). Causally-valid complete blocks for+``pos = 9`` are ``{0, 1}``. After a stable top-2 by score, the selection head emits ``selected_block_indices = [[[0, 1]]]``+and ``selected_block_count = [[2]]`` in strictly ascending order. *SparseAttention* independently derives the tail positions+``[8, 9]`` for this query; the tail is absent from the selection output/count. With ``H_iq = 4`` and ``H_ik = 1``,+all four index-query heads participate in the single selection head's score.++.. code-block:: xml+ :force:++ <layer ... type="PagedQSAIndexer">+ <data key_block_size="4" block_topk="2" num_selection_heads="1" indexer_head_dim="128"+ indexer_rotary_dim="64" epsilon="1e-6"+ scale="0.088388"/>+ <input>+ <port id="0"> <!-- index_query: [tokens, H_iq*D_idx] -->+ <dim>1</dim><dim>512</dim>+ </port>+ <port id="1"> <!-- raw_index_keys: [tokens, H_ik*D_idx] -->+ <dim>1</dim><dim>128</dim>+ </port>+ <port id="2"> <!-- rope_cos: [tokens, rotary_dim] -->+ <dim>1</dim><dim>64</dim>+ </port>+ <port id="3"> <!-- rope_sin: [tokens, rotary_dim] -->+ <dim>1</dim><dim>64</dim>+ </port>+ <port id="4"> <!-- q_norm_weight: [D_idx] -->+ <dim>128</dim>+ </port>+ <port id="5"> <!-- k_norm_weight: [D_idx] -->+ <dim>128</dim>+ </port>+ <port id="6"> <!-- past_lens: [num_sequences] -->+ <dim>1</dim>+ </port>+ <port id="7"> <!-- subsequence_begins: [num_sequences+1] -->+ <dim>2</dim>+ </port>+ <port id="8"> <!-- block_indices: [total_logical_blocks] -->+ <dim>1</dim>+ </port>+ <port id="9"> <!-- block_indices_begins: [num_sequences+1] -->+ <dim>2</dim>+ </port>+ <port id="10"> <!-- index_key_cache: [num_blocks, H_ik, page_size, D_idx] -->+ <dim>1</dim><dim>1</dim><dim>16</dim><dim>128</dim>+ </port>+ <port id="11"> <!-- index_block_rope_cache: [num_blocks, page_size//r, 2*rotary_dim], writable -->+ <dim>1</dim><dim>4</dim><dim>128</dim>+ </port>+ <port id="12"> <!-- block_index_keys_cache: [num_blocks, H_ik, page_size//r, D_idx] -->+ <dim>1</dim><dim>1</dim><dim>4</dim><dim>128</dim>+ </port>+ </input>+ <output>+ <port id="13" precision="I32"> <!-- selected_block_indices: [tokens, H_sel, K_max=block_topk] -->+ <dim>1</dim><dim>1</dim><dim>2</dim>+ </port>+ <port id="14" precision="I32"> <!-- selected_block_count: [tokens, H_sel] -->+ <dim>1</dim><dim>1</dim>+ </port>+ </output>+ </layer>\ No newline at end of filediff --git a/src/core/dev_api/dev_headers.cmake b/src/core/dev_api/dev_headers.cmakeindex bf703ae2e66..65ff67416f6 100644--- a/src/core/dev_api/dev_headers.cmake+++ b/src/core/dev_api/dev_headers.cmake@@ -30,7 +30,9 @@ set(DEV_HEADERS${CMAKE_CURRENT_LIST_DIR}/openvino/op/paged_sparse_attention.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/paged_causal_conv1d.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/paged_gated_delta_net.hpp+ ${CMAKE_CURRENT_LIST_DIR}/openvino/op/paged_qsa_indexer.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/paged_selective_ssm.hpp+ ${CMAKE_CURRENT_LIST_DIR}/openvino/op/paged_sparse_attention.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/rms_norm.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/selective_ssm.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/util/node_util.hppdiff --git a/src/core/dev_api/openvino/op/paged_qsa_indexer.hpp b/src/core/dev_api/openvino/op/paged_qsa_indexer.hppnew file mode 100644index 00000000000..c06e4460db2--- /dev/null+++ b/src/core/dev_api/openvino/op/paged_qsa_indexer.hpp@@ -0,0 +1,87 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#pragma once++#include <cstddef>+#include <string>++#include "openvino/core/node.hpp"+#include "openvino/op/op.hpp"++namespace ov::op::internal {++/// \brief Paged-cache complete-block plan producer for Qwen Sparse Attention (QSA).+///+/// Consumes externally projected indexer queries/keys (`index_query`/`raw_index_keys`) and the per-token+/// RoPE coefficients of the main attention (`rope_cos`/`rope_sin`), applies query RMSNorm ++/// partial RoPE, appends raw keys, completed-block summaries and block-start RoPE rows into+/// caller-owned paged caches addressed through the shared main-KV page table, and emits+/// per-query selections containing ONLY complete blocks (`selected_block_indices`/`selected_block_count`,+/// width `block_topk`). The causal tail is not represented here; the paired+/// `SparsePA` consumer derives it from each query's logical position. See+/// `paged-qsa-indexer.rst` for the normative contract.+///+/// \ingroup ov_ops_cpp_api+class OPENVINO_API PagedQSAIndexer : public ov::op::Op {+public:+ OPENVINO_OP("PagedQSAIndexer");++ /// @brief Fixed input order of the PagedQSAIndexer op.+ struct InputIdx {+ static constexpr size_t INDEX_QUERY = 0; ///< [tokens, H_iq*D_idx]+ static constexpr size_t RAW_INDEX_KEYS = 1; ///< [tokens, H_ik*D_idx]+ static constexpr size_t ROPE_COS = 2; ///< [tokens, indexer_rotary_dim]+ static constexpr size_t ROPE_SIN = 3; ///< [tokens, indexer_rotary_dim]+ static constexpr size_t Q_NORM_WEIGHT = 4; ///< [D_idx]+ static constexpr size_t K_NORM_WEIGHT = 5; ///< [D_idx]+ static constexpr size_t PAST_LENS = 6; ///< [num_sequences]+ static constexpr size_t SUBSEQUENCE_BEGINS = 7; ///< [num_sequences+1]+ static constexpr size_t BLOCK_INDICES = 8; ///< [total_logical_blocks]+ static constexpr size_t BLOCK_INDICES_BEGINS = 9; ///< [num_sequences+1]+ static constexpr size_t INDEX_KEY_CACHE =+ 10; ///< [N_phys, H_ik, page_size, D_idx], writable in place; page_size = shape[2]+ static constexpr size_t INDEX_BLOCK_ROPE_CACHE =+ 11; ///< [N_phys, page_size/r, 2*indexer_rotary_dim], (cos_j, sin_j) interleaved, writable in place+ static constexpr size_t BLOCK_INDEX_KEYS_CACHE = 12; ///< [N_phys, H_ik, page_size/r, D_idx], writable in place++ static constexpr size_t COUNT = 13;+ };++ struct Config {+ size_t key_block_size = 4; ///< r+ size_t block_topk = 0; ///< K_max, required+ size_t num_selection_heads = 1; ///< 1 or H_ik+ size_t indexer_rotary_dim = 0; ///< <= indexer_head_dim, even+ size_t indexer_head_dim = 0; ///< D_idx+ float epsilon = 1e-6f; ///< RMSNorm epsilon+ float scale = 0.0f; ///< positive score multiplier; 0 is resolved to 1 / sqrt(indexer_head_dim) by the op+ };++ PagedQSAIndexer() = default;+ PagedQSAIndexer(const ov::OutputVector& args, const Config& config);++ bool visit_attributes(ov::AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ const Config& get_config() const {+ return m_config;+ }++ /// @brief Attribute constraints that must hold before a lowering may be created.+ static bool validate_config(const Config& config, std::string& reason);++ /// `scale`, or its 1 / sqrt(indexer_head_dim) default when unset (0).+ static float effective_scale(const Config& config);++ /// H_iq, derived from index_query's static shape (last dim / indexer_head_dim). Never cached.+ size_t get_index_query_heads() const;+ /// H_ik, derived from raw_index_keys's static shape (last dim / indexer_head_dim). Never cached.+ size_t get_index_key_heads() const;++private:+ Config m_config{};+};++} // namespace ov::op::internaldiff --git a/src/core/shape_inference/CMakeLists.txt b/src/core/shape_inference/CMakeLists.txtindex 6c83c1b9f4b..b907b879e37 100644--- a/src/core/shape_inference/CMakeLists.txt+++ b/src/core/shape_inference/CMakeLists.txt@@ -103,6 +103,7 @@ target_sources(${TARGET_NAME}${SHAPE_INFER_INCLUDE_DIR}/paged_causal_conv1d_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/paged_gated_delta_net_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/paged_selective_ssm_shape_inference.hpp+ ${SHAPE_INFER_INCLUDE_DIR}/paged_sparse_attention_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/pooling_shape_inference_util.hpp${SHAPE_INFER_INCLUDE_DIR}/prior_box_clustered_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/prior_box_shape_inference.hppdiff --git a/src/core/src/op/paged_qsa_indexer.cpp b/src/core/src/op/paged_qsa_indexer.cppnew file mode 100644index 00000000000..226cd3829e6--- /dev/null+++ b/src/core/src/op/paged_qsa_indexer.cpp@@ -0,0 +1,277 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/paged_qsa_indexer.hpp"++#include <cmath>+#include <initializer_list>+#include <string>++#include "itt.hpp"++namespace ov::op::internal {++PagedQSAIndexer::PagedQSAIndexer(const ov::OutputVector& args, const Config& config) : Op(args), m_config(config) {+ constructor_validate_and_infer_types();+}++bool PagedQSAIndexer::validate_config(const Config& c, std::string& reason) {+ if (c.key_block_size == 0) {+ reason = "key_block_size must be positive";+ return false;+ }+ if (c.block_topk == 0) {+ reason = "block_topk must be positive";+ return false;+ }+ if (c.num_selection_heads == 0) {+ reason = "num_selection_heads must be positive";+ return false;+ }+ if (c.indexer_head_dim == 0) {+ reason = "indexer_head_dim must be positive";+ return false;+ }+ if (c.indexer_rotary_dim % 2 != 0 || c.indexer_rotary_dim > c.indexer_head_dim) {+ reason = "indexer_rotary_dim must be even and not exceed indexer_head_dim";+ return false;+ }+ if (!std::isfinite(c.scale) || c.scale < 0.0f) {+ reason = "scale must be positive (0 selects the default 1 / sqrt(indexer_head_dim))";+ return false;+ }+ return true;+}++float PagedQSAIndexer::effective_scale(const Config& c) {+ return c.scale > 0.0f ? c.scale : 1.0f / std::sqrt(static_cast<float>(c.indexer_head_dim));+}++size_t PagedQSAIndexer::get_index_query_heads() const {+ const auto& ps = get_input_partial_shape(InputIdx::INDEX_QUERY);+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() == 2 && ps[1].is_static(),+ "PagedQSAIndexer: index_query shape is not static");+ OPENVINO_ASSERT(m_config.indexer_head_dim != 0, "PagedQSAIndexer: indexer_head_dim is 0");+ return static_cast<size_t>(ps[1].get_length()) / m_config.indexer_head_dim;+}++size_t PagedQSAIndexer::get_index_key_heads() const {+ const auto& ps = get_input_partial_shape(InputIdx::RAW_INDEX_KEYS);+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() == 2 && ps[1].is_static(),+ "PagedQSAIndexer: raw_index_keys shape is not static");+ OPENVINO_ASSERT(m_config.indexer_head_dim != 0, "PagedQSAIndexer: indexer_head_dim is 0");+ return static_cast<size_t>(ps[1].get_length()) / m_config.indexer_head_dim;+}++bool PagedQSAIndexer::visit_attributes(ov::AttributeVisitor& visitor) {+ OV_OP_SCOPE(internal_PagedQSAIndexer_visit_attributes);+ visitor.on_attribute("key_block_size", m_config.key_block_size);+ visitor.on_attribute("block_topk", m_config.block_topk);+ visitor.on_attribute("num_selection_heads", m_config.num_selection_heads);+ visitor.on_attribute("indexer_rotary_dim", m_config.indexer_rotary_dim);+ visitor.on_attribute("indexer_head_dim", m_config.indexer_head_dim);+ visitor.on_attribute("epsilon", m_config.epsilon);+ visitor.on_attribute("scale", m_config.scale);+ return true;+}++void PagedQSAIndexer::validate_and_infer_types() {+ OV_OP_SCOPE(internal_PagedQSAIndexer_validate_and_infer_types);+ NODE_VALIDATION_CHECK(this,+ get_input_size() == InputIdx::COUNT,+ "PagedQSAIndexer expects ",+ InputIdx::COUNT,+ " inputs, got ",+ get_input_size());++ std::string reason;+ NODE_VALIDATION_CHECK(this,+ validate_config(m_config, reason),+ "PagedQSAIndexer configuration is invalid: ",+ reason);++ const auto& index_query_ps = get_input_partial_shape(InputIdx::INDEX_QUERY);+ const auto& raw_index_keys_ps = get_input_partial_shape(InputIdx::RAW_INDEX_KEYS);+ NODE_VALIDATION_CHECK(this,+ index_query_ps.rank().is_dynamic() || index_query_ps.size() == 2,+ "PagedQSAIndexer expects a rank-2 [tokens, H_iq*D_idx] index_query input, got ",+ index_query_ps);+ NODE_VALIDATION_CHECK(this,+ raw_index_keys_ps.rank().is_dynamic() || raw_index_keys_ps.size() == 2,+ "PagedQSAIndexer expects a rank-2 [tokens, H_ik*D_idx] raw_index_keys input, got ",+ raw_index_keys_ps);+ // All floating-point inputs must share one element type.+ element::Type float_et = element::dynamic;+ for (const auto idx : {InputIdx::INDEX_QUERY,+ InputIdx::RAW_INDEX_KEYS,+ InputIdx::ROPE_COS,+ InputIdx::ROPE_SIN,+ InputIdx::BLOCK_INDEX_KEYS_CACHE,+ InputIdx::INDEX_KEY_CACHE,+ InputIdx::Q_NORM_WEIGHT,+ InputIdx::K_NORM_WEIGHT,+ InputIdx::INDEX_BLOCK_ROPE_CACHE}) {+ const auto& in_et = get_input_element_type(idx);+ NODE_VALIDATION_CHECK(this,+ element::Type::merge(float_et, float_et, in_et),+ "PagedQSAIndexer expects all floating-point inputs to share one element type; input ",+ idx,+ " is ",+ in_et);+ }+ NODE_VALIDATION_CHECK(this,+ float_et.is_dynamic() || float_et.is_real(),+ "PagedQSAIndexer expects floating-point inputs, got ",+ float_et);++ // The kernels read every integer input as int32_t.+ for (const auto idx :+ {InputIdx::PAST_LENS, InputIdx::SUBSEQUENCE_BEGINS, InputIdx::BLOCK_INDICES, InputIdx::BLOCK_INDICES_BEGINS}) {+ const auto& in_et = get_input_element_type(idx);+ const auto& in_ps = get_input_partial_shape(idx);+ NODE_VALIDATION_CHECK(this,+ in_et.is_dynamic() || in_et == element::i32,+ "PagedQSAIndexer expects an i32 index input; input ",+ idx,+ " is ",+ in_et);+ NODE_VALIDATION_CHECK(this,+ in_ps.rank().is_dynamic() || in_ps.size() == 1,+ "PagedQSAIndexer expects a rank-1 index input; input ",+ idx,+ " is ",+ in_ps);+ }++ // Local helper: the extent of one axis, or dynamic when the rank or the axis is unknown.+ const auto dim_at = [](const ov::PartialShape& ps, size_t axis) -> ov::Dimension {+ return ps.rank().is_static() && ps.size() > axis ? ps[axis] : ov::Dimension::dynamic();+ };++ const ov::Dimension tokens = dim_at(index_query_ps, 0);+ const ov::Dimension di(static_cast<int64_t>(m_config.indexer_head_dim));+ const ov::Dimension rot(static_cast<int64_t>(m_config.indexer_rotary_dim));+ const ov::Dimension rope_row(static_cast<int64_t>(2 * m_config.indexer_rotary_dim));+ // page_size is not an attribute: it is the block size of the raw-K cache (dim 2).+ const ov::Dimension page = dim_at(get_input_partial_shape(InputIdx::INDEX_KEY_CACHE), 2);+ ov::Dimension spp = ov::Dimension::dynamic();+ if (page.is_static()) {+ const auto page_size = static_cast<size_t>(page.get_length());+ NODE_VALIDATION_CHECK(+ this,+ page_size > 0 && page_size % m_config.key_block_size == 0,+ "PagedQSAIndexer: index_key_cache dim 2 (page_size) must be a positive multiple of key_block_size, got ",+ page_size);+ spp = ov::Dimension(static_cast<int64_t>(page_size / m_config.key_block_size));+ }+ // H_iq / H_ik come from the flattened [tokens, H * D_idx] inputs; dynamic unless the last axis is static.+ const auto flat_heads = [this, &dim_at](const ov::PartialShape& ps, const char* name) -> ov::Dimension {+ const auto last = dim_at(ps, 1);+ if (last.is_dynamic()) {+ return ov::Dimension::dynamic();+ }+ NODE_VALIDATION_CHECK(+ this,+ last.get_length() > 0 && last.get_length() % static_cast<int64_t>(m_config.indexer_head_dim) == 0,+ "PagedQSAIndexer expects the ",+ name,+ " last dimension to be a positive multiple of indexer_head_dim=",+ m_config.indexer_head_dim,+ ", got ",+ ps);+ return ov::Dimension(last.get_length() / static_cast<int64_t>(m_config.indexer_head_dim));+ };+ const auto h_iq = flat_heads(index_query_ps, "index_query");+ const auto h_ik = flat_heads(raw_index_keys_ps, "raw_index_keys");++ NODE_VALIDATION_CHECK(this,+ raw_index_keys_ps.compatible(ov::PartialShape{tokens, -1}),+ "PagedQSAIndexer expects raw_index_keys shaped [tokens, H_ik*D_idx], got ",+ raw_index_keys_ps);+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::ROPE_COS).compatible(ov::PartialShape{tokens, rot}),+ "PagedQSAIndexer expects rope_cos shaped [tokens, indexer_rotary_dim], got ",+ get_input_partial_shape(InputIdx::ROPE_COS));+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::ROPE_SIN).compatible(ov::PartialShape{tokens, rot}),+ "PagedQSAIndexer expects rope_sin shaped [tokens, indexer_rotary_dim], got ",+ get_input_partial_shape(InputIdx::ROPE_SIN));+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::Q_NORM_WEIGHT).compatible(ov::PartialShape{di}),+ "PagedQSAIndexer expects q_norm_weight shaped [indexer_head_dim], got ",+ get_input_partial_shape(InputIdx::Q_NORM_WEIGHT));+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::K_NORM_WEIGHT).compatible(ov::PartialShape{di}),+ "PagedQSAIndexer expects k_norm_weight shaped [indexer_head_dim], got ",+ get_input_partial_shape(InputIdx::K_NORM_WEIGHT));++ // The three paged caches share the main KV page pool (dim 0).+ ov::Dimension num_blocks = ov::Dimension::dynamic();+ for (auto idx : {InputIdx::BLOCK_INDEX_KEYS_CACHE, InputIdx::INDEX_KEY_CACHE, InputIdx::INDEX_BLOCK_ROPE_CACHE}) {+ NODE_VALIDATION_CHECK(this,+ ov::Dimension::merge(num_blocks, num_blocks, dim_at(get_input_partial_shape(idx), 0)),+ "PagedQSAIndexer expects block_index_keys_cache, index_key_cache and "+ "index_block_rope_cache to share dim 0 (num_blocks)");+ }+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::BLOCK_INDEX_KEYS_CACHE)+ .compatible(ov::PartialShape{num_blocks, h_ik, spp, di}),+ "PagedQSAIndexer expects block_index_keys_cache shaped "+ "[num_blocks, H_ik, page_size/r, indexer_head_dim], got ",+ get_input_partial_shape(InputIdx::BLOCK_INDEX_KEYS_CACHE));+ NODE_VALIDATION_CHECK(+ this,+ get_input_partial_shape(InputIdx::INDEX_KEY_CACHE).compatible(ov::PartialShape{num_blocks, h_ik, page, di}),+ "PagedQSAIndexer expects index_key_cache shaped [num_blocks, H_ik, page_size, indexer_head_dim], "+ "got ",+ get_input_partial_shape(InputIdx::INDEX_KEY_CACHE));+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::INDEX_BLOCK_ROPE_CACHE)+ .compatible(ov::PartialShape{num_blocks, spp, rope_row}),+ "PagedQSAIndexer expects index_block_rope_cache shaped "+ "[num_blocks, page_size/r, 2*indexer_rotary_dim], got ",+ get_input_partial_shape(InputIdx::INDEX_BLOCK_ROPE_CACHE));++ const auto num_seqs = dim_at(get_input_partial_shape(InputIdx::PAST_LENS), 0);+ const auto num_seqs_plus_one =+ num_seqs.is_static() ? ov::Dimension(num_seqs.get_length() + 1) : ov::Dimension::dynamic();+ NODE_VALIDATION_CHECK(+ this,+ get_input_partial_shape(InputIdx::SUBSEQUENCE_BEGINS).compatible(ov::PartialShape{num_seqs_plus_one}),+ "PagedQSAIndexer expects subsequence_begins shaped [num_sequences+1], got ",+ get_input_partial_shape(InputIdx::SUBSEQUENCE_BEGINS));+ NODE_VALIDATION_CHECK(+ this,+ get_input_partial_shape(InputIdx::BLOCK_INDICES_BEGINS).compatible(ov::PartialShape{num_seqs_plus_one}),+ "PagedQSAIndexer expects block_indices_begins shaped [num_sequences+1], got ",+ get_input_partial_shape(InputIdx::BLOCK_INDICES_BEGINS));++ if (h_iq.is_static() && h_ik.is_static()) {+ const auto h_iq_value = static_cast<size_t>(h_iq.get_length());+ const auto h_ik_value = static_cast<size_t>(h_ik.get_length());+ NODE_VALIDATION_CHECK(this,+ h_iq_value % h_ik_value == 0,+ "PagedQSAIndexer: H_iq must be a positive multiple of H_ik.");+ NODE_VALIDATION_CHECK(this,+ m_config.num_selection_heads == 1 || m_config.num_selection_heads == h_ik_value,+ "PagedQSAIndexer: num_selection_heads must be 1 or H_ik.");+ }++ const ov::PartialShape selected_block_indices_ps{tokens,+ ov::Dimension(static_cast<int64_t>(m_config.num_selection_heads)),+ ov::Dimension(static_cast<int64_t>(m_config.block_topk))};+ const ov::PartialShape selected_block_count_ps{tokens,+ ov::Dimension(static_cast<int64_t>(m_config.num_selection_heads))};++ set_output_size(2);+ set_output_type(0, element::i32, selected_block_indices_ps);+ set_output_type(1, element::i32, selected_block_count_ps);+}++std::shared_ptr<Node> PagedQSAIndexer::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<PagedQSAIndexer>(new_args, m_config);+}++} // namespace ov::op::internaldiff --git a/src/core/src/sources.cmake b/src/core/src/sources.cmakeindex 57db353d253..ed6837da0ee 100644--- a/src/core/src/sources.cmake+++ b/src/core/src/sources.cmake@@ -191,7 +191,9 @@ set(LIBRARY_SRC${CMAKE_CURRENT_LIST_DIR}/op/paged_sparse_attention.cpp${CMAKE_CURRENT_LIST_DIR}/op/paged_causal_conv1d.cpp${CMAKE_CURRENT_LIST_DIR}/op/paged_gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/op/paged_qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/op/paged_selective_ssm.cpp+ ${CMAKE_CURRENT_LIST_DIR}/op/paged_sparse_attention.cpp${CMAKE_CURRENT_LIST_DIR}/op/parameter.cpp${CMAKE_CURRENT_LIST_DIR}/op/power.cpp${CMAKE_CURRENT_LIST_DIR}/op/prelu.cppdiff --git a/src/core/tests/type_prop/paged_qsa_indexer.cpp b/src/core/tests/type_prop/paged_qsa_indexer.cppnew file mode 100644index 00000000000..bda541620c8--- /dev/null+++ b/src/core/tests/type_prop/paged_qsa_indexer.cpp@@ -0,0 +1,196 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/paged_qsa_indexer.hpp"++#include <gtest/gtest.h>++#include <memory>+#include <tuple>++#include "common_test_utils/type_prop.hpp"+#include "openvino/op/parameter.hpp"++namespace ov::testing {+namespace {++using op::internal::PagedQSAIndexer;+using op::v0::Parameter;++// Consistent configuration: key block size r = 4, K = 3, one selection head, D_idx = 4 with 2 rotary dims.+PagedQSAIndexer::Config make_paged_qsa_indexer_config() {+ PagedQSAIndexer::Config config;+ config.key_block_size = 4;+ config.block_topk = 3;+ config.num_selection_heads = 1;+ config.indexer_rotary_dim = 2;+ config.indexer_head_dim = 4;+ return config;+}++// Six tokens, eight physical pages of page_size slots, query/key heads of width D_idx = 4.+OutputVector make_paged_qsa_indexer_inputs(int64_t query_heads = 2, int64_t key_heads = 1, int64_t page_size = 8) {+ constexpr int64_t head_dim = 4;+ constexpr int64_t rotary_dim = 2;+ constexpr int64_t num_pages = 8;+ const int64_t summaries_per_page = page_size / 4; // page_size / key_block_size+ return {+ std::make_shared<Parameter>(element::f32, PartialShape{6, query_heads * head_dim}),+ std::make_shared<Parameter>(element::f32, PartialShape{6, key_heads * head_dim}),+ std::make_shared<Parameter>(element::f32, PartialShape{6, rotary_dim}),+ std::make_shared<Parameter>(element::f32, PartialShape{6, rotary_dim}),+ std::make_shared<Parameter>(element::f32, PartialShape{head_dim}),+ std::make_shared<Parameter>(element::f32, PartialShape{head_dim}),+ std::make_shared<Parameter>(element::i32, PartialShape{2}),+ std::make_shared<Parameter>(element::i32, PartialShape{3}),+ std::make_shared<Parameter>(element::i32, PartialShape{4}),+ std::make_shared<Parameter>(element::i32, PartialShape{3}),+ std::make_shared<Parameter>(element::f32, PartialShape{num_pages, key_heads, page_size, head_dim}),+ std::make_shared<Parameter>(element::f32, PartialShape{num_pages, summaries_per_page, 2 * rotary_dim}),+ std::make_shared<Parameter>(element::f32, PartialShape{num_pages, key_heads, summaries_per_page, head_dim})};+}++} // namespace++TEST(type_prop, paged_qsa_indexer_output_shape_and_type) {+ const auto op = std::make_shared<PagedQSAIndexer>(make_paged_qsa_indexer_inputs(), make_paged_qsa_indexer_config());++ // Both outputs are i32 selections; the paged caches are updated in place and are not outputs.+ ASSERT_EQ(op->get_output_size(), 2);+ EXPECT_EQ(op->get_output_element_type(0), element::i32);+ // Six tokens, one selection head, block_topk = 3.+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{6, 1, 3}));+ EXPECT_EQ(op->get_output_element_type(1), element::i32);+ EXPECT_EQ(op->get_output_partial_shape(1), (PartialShape{6, 1}));+ EXPECT_EQ(op->get_index_query_heads(), 2u);+ EXPECT_EQ(op->get_index_key_heads(), 1u);+}++TEST(type_prop, paged_qsa_indexer_per_key_head_selection) {+ auto config = make_paged_qsa_indexer_config();+ // num_selection_heads may equal H_ik, giving one selection row per key head.+ config.num_selection_heads = 2;+ const auto op = std::make_shared<PagedQSAIndexer>(make_paged_qsa_indexer_inputs(2, 2), config);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{6, 2, 3}));+ EXPECT_EQ(op->get_output_partial_shape(1), (PartialShape{6, 2}));+ EXPECT_EQ(op->get_index_key_heads(), 2u);+}++TEST(type_prop, paged_qsa_indexer_dynamic_tokens_and_pages) {+ auto inputs = make_paged_qsa_indexer_inputs();+ const auto dyn = Dimension::dynamic();+ inputs[0] = std::make_shared<Parameter>(element::f32, PartialShape{dyn, dyn});+ inputs[1] = std::make_shared<Parameter>(element::f32, PartialShape{dyn, dyn});+ inputs[2] = std::make_shared<Parameter>(element::f32, PartialShape{dyn, 2});+ inputs[3] = std::make_shared<Parameter>(element::f32, PartialShape{dyn, 2});+ inputs[10] = std::make_shared<Parameter>(element::f32, PartialShape{dyn, dyn, dyn, dyn});+ inputs[11] = std::make_shared<Parameter>(element::f32, PartialShape{dyn, dyn, dyn});+ inputs[12] = std::make_shared<Parameter>(element::f32, PartialShape{dyn, dyn, dyn, dyn});+ const auto op = std::make_shared<PagedQSAIndexer>(inputs, make_paged_qsa_indexer_config());++ // The token count is unknown, while the selection width and the selection head count stay static.+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{dyn, 1, 3}));+ EXPECT_EQ(op->get_output_partial_shape(1), (PartialShape{dyn, 1}));+}++TEST(type_prop, paged_qsa_indexer_rejects_invalid_config) {+ const auto expect_invalid = [](const PagedQSAIndexer::Config& config) {+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(make_paged_qsa_indexer_inputs(), config),+ NodeValidationFailure);+ };++ // Each attribute constraint enforced by validate_config must fail at construction time.+ auto config = make_paged_qsa_indexer_config();+ config.key_block_size = 0;+ expect_invalid(config);++ config = make_paged_qsa_indexer_config();+ config.block_topk = 0;+ expect_invalid(config);++ config = make_paged_qsa_indexer_config();+ config.num_selection_heads = 0;+ expect_invalid(config);++ config = make_paged_qsa_indexer_config();+ config.indexer_rotary_dim = 3; // must be even+ expect_invalid(config);++ config = make_paged_qsa_indexer_config();+ config.indexer_rotary_dim = 6; // must not exceed indexer_head_dim+ expect_invalid(config);++ config = make_paged_qsa_indexer_config();+ config.scale = -1.0f;+ expect_invalid(config);+}++TEST(type_prop, paged_qsa_indexer_rejects_incompatible_shapes) {+ const auto config = make_paged_qsa_indexer_config();+ auto inputs = make_paged_qsa_indexer_inputs();++ // The query width must be a whole number of indexer_head_dim heads.+ inputs[0] = std::make_shared<Parameter>(element::f32, PartialShape{6, 6});+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(inputs, config), NodeValidationFailure);++ inputs = make_paged_qsa_indexer_inputs();+ // Raw keys must describe the same token stream as the index queries.+ inputs[1] = std::make_shared<Parameter>(element::f32, PartialShape{5, 4});+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(inputs, config), NodeValidationFailure);++ inputs = make_paged_qsa_indexer_inputs();+ // RoPE rows carry indexer_rotary_dim coefficients per token.+ inputs[2] = std::make_shared<Parameter>(element::f32, PartialShape{6, 3});+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(inputs, config), NodeValidationFailure);++ // page_size 6 is not a multiple of key_block_size 4.+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(make_paged_qsa_indexer_inputs(2, 1, 6), config),+ NodeValidationFailure);++ // H_iq = 3 is not a multiple of H_ik = 2.+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(make_paged_qsa_indexer_inputs(3, 2), config),+ NodeValidationFailure);++ inputs = make_paged_qsa_indexer_inputs();+ // The three paged caches must share the physical page axis.+ inputs[12] = std::make_shared<Parameter>(element::f32, PartialShape{7, 1, 2, 4});+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(inputs, config), NodeValidationFailure);++ // num_selection_heads must be 1 or H_ik; here H_ik = 1.+ auto bad_selection = make_paged_qsa_indexer_config();+ bad_selection.num_selection_heads = 2;+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(make_paged_qsa_indexer_inputs(), bad_selection),+ NodeValidationFailure);+}++TEST(type_prop, paged_qsa_indexer_rejects_invalid_types_and_arity) {+ auto inputs = make_paged_qsa_indexer_inputs();+ inputs.pop_back();+ // All 13 inputs are required.+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(inputs, make_paged_qsa_indexer_config()),+ NodeValidationFailure);++ inputs = make_paged_qsa_indexer_inputs();+ inputs[6] = std::make_shared<Parameter>(element::i64, PartialShape{2});+ // The kernels read every integer input as i32, so i64 index tables are rejected.+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(inputs, make_paged_qsa_indexer_config()),+ NodeValidationFailure);++ inputs = make_paged_qsa_indexer_inputs();+ inputs[4] = std::make_shared<Parameter>(element::f16, PartialShape{4});+ // Floating-point inputs must share one element type.+ EXPECT_THROW(std::ignore = std::make_shared<PagedQSAIndexer>(inputs, make_paged_qsa_indexer_config()),+ NodeValidationFailure);+}++TEST(type_prop, paged_qsa_indexer_effective_scale_defaults_to_inverse_sqrt_head_dim) {+ auto config = make_paged_qsa_indexer_config();+ // scale = 0 selects 1 / sqrt(indexer_head_dim) = 1 / 2 for D_idx = 4.+ EXPECT_FLOAT_EQ(PagedQSAIndexer::effective_scale(config), 0.5f);+ config.scale = 0.25f;+ EXPECT_FLOAT_EQ(PagedQSAIndexer::effective_scale(config), 0.25f);+}++} // namespace ov::testingdiff --git a/src/core/tests/type_prop/sources.cmake b/src/core/tests/type_prop/sources.cmakeindex a6e0f677527..dc2f17f0e65 100644--- a/src/core/tests/type_prop/sources.cmake+++ b/src/core/tests/type_prop/sources.cmake@@ -142,7 +142,9 @@ set(OV_CORE_TESTS_TYPE_PROP_SRCS${CMAKE_CURRENT_LIST_DIR}/paged_sparse_attention.cpp${CMAKE_CURRENT_LIST_DIR}/paged_causal_conv1d.cpp${CMAKE_CURRENT_LIST_DIR}/paged_gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/paged_qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/paged_selective_ssm.cpp+ ${CMAKE_CURRENT_LIST_DIR}/paged_sparse_attention.cpp${CMAKE_CURRENT_LIST_DIR}/parameter.cpp${CMAKE_CURRENT_LIST_DIR}/power.cpp${CMAKE_CURRENT_LIST_DIR}/prelu.cppdiff --git a/src/core/tests/visitors/op/paged_qsa_indexer.cpp b/src/core/tests/visitors/op/paged_qsa_indexer.cppnew file mode 100644index 00000000000..3202360bece--- /dev/null+++ b/src/core/tests/visitors/op/paged_qsa_indexer.cpp@@ -0,0 +1,59 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/paged_qsa_indexer.hpp"++#include <gtest/gtest.h>++#include "openvino/op/parameter.hpp"+#include "visitors/visitors.hpp"++using ov::PartialShape;+using ov::op::v0::Parameter;+using ov::test::NodeBuilder;++TEST(attributes, paged_qsa_indexer) {+ using ov::op::internal::PagedQSAIndexer;+ NodeBuilder::opset().insert<PagedQSAIndexer>();++ const auto f32 = ov::element::f32;+ const auto i32 = ov::element::i32;+ // Six tokens, H_iq = 2, H_ik = 1, D_idx = 4, two rotary dims, eight physical pages of eight slots (r = 4).+ const ov::OutputVector args{std::make_shared<Parameter>(f32, PartialShape{6, 8}),+ std::make_shared<Parameter>(f32, PartialShape{6, 4}),+ std::make_shared<Parameter>(f32, PartialShape{6, 2}),+ std::make_shared<Parameter>(f32, PartialShape{6, 2}),+ std::make_shared<Parameter>(f32, PartialShape{4}),+ std::make_shared<Parameter>(f32, PartialShape{4}),+ std::make_shared<Parameter>(i32, PartialShape{2}),+ std::make_shared<Parameter>(i32, PartialShape{3}),+ std::make_shared<Parameter>(i32, PartialShape{4}),+ std::make_shared<Parameter>(i32, PartialShape{3}),+ std::make_shared<Parameter>(f32, PartialShape{8, 1, 8, 4}),+ std::make_shared<Parameter>(f32, PartialShape{8, 2, 4}),+ std::make_shared<Parameter>(f32, PartialShape{8, 1, 2, 4})};++ PagedQSAIndexer::Config config;+ config.key_block_size = 4;+ config.block_topk = 3;+ config.num_selection_heads = 1;+ config.indexer_rotary_dim = 2;+ config.indexer_head_dim = 4;+ config.epsilon = 1e-5f;+ config.scale = 0.5f;+ const auto op = std::make_shared<PagedQSAIndexer>(args, config);++ NodeBuilder builder(op, args);+ const auto restored = ov::as_type_ptr<PagedQSAIndexer>(builder.create());+ ASSERT_NE(restored, nullptr);+ const auto& restored_config = restored->get_config();+ EXPECT_EQ(restored_config.key_block_size, config.key_block_size);+ EXPECT_EQ(restored_config.block_topk, config.block_topk);+ EXPECT_EQ(restored_config.num_selection_heads, config.num_selection_heads);+ EXPECT_EQ(restored_config.indexer_rotary_dim, config.indexer_rotary_dim);+ EXPECT_EQ(restored_config.indexer_head_dim, config.indexer_head_dim);+ EXPECT_EQ(restored_config.epsilon, config.epsilon);+ EXPECT_EQ(restored_config.scale, config.scale);+ EXPECT_EQ(restored->get_output_size(), 2);+}diff --git a/src/core/tests/visitors/sources.cmake b/src/core/tests/visitors/sources.cmakeindex 52d94ed6f55..5aae4be3204 100644--- a/src/core/tests/visitors/sources.cmake+++ b/src/core/tests/visitors/sources.cmake@@ -142,7 +142,9 @@ set(OV_CORE_TESTS_VISITORS_SRCS${CMAKE_CURRENT_LIST_DIR}/op/pad.cpp${CMAKE_CURRENT_LIST_DIR}/op/paged_causal_conv1d.cpp${CMAKE_CURRENT_LIST_DIR}/op/paged_gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/op/paged_qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/op/paged_selective_ssm.cpp+ ${CMAKE_CURRENT_LIST_DIR}/op/paged_sparse_attention.cpp${CMAKE_CURRENT_LIST_DIR}/op/parameter.cpp${CMAKE_CURRENT_LIST_DIR}/op/power.cpp${CMAKE_CURRENT_LIST_DIR}/op/prelu.cppdiff --git a/src/plugins/intel_gpu/include/intel_gpu/op/paged_qsa_indexer.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/paged_qsa_indexer.hppnew file mode 100644index 00000000000..9f8ea88f6d8--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/op/paged_qsa_indexer.hpp@@ -0,0 +1,31 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/paged_qsa_indexer.hpp"++namespace ov::intel_gpu::op {++/// @brief GPU-internal paged-cache QSA Indexer. Reuses ov::op::internal::PagedQSAIndexer's+/// Config/InputIdx/shape-inference/attribute-visiting logic wholesale; the only+/// GPU-specific bit is the "gpu_opset" RTTI tag used by ProgramBuilder dispatch and by+/// the cldnn::paged_qsa_indexer primitive lowering.+class PagedQSAIndexer : public ov::op::internal::PagedQSAIndexer {+public:+ OPENVINO_OP("PagedQSAIndexer", "gpu_opset", ov::op::internal::PagedQSAIndexer);++ using Base = ov::op::internal::PagedQSAIndexer;+ using Config = Base::Config;+ using InputIdx = Base::InputIdx;+ using Base::validate_config;++ PagedQSAIndexer() = default;++ PagedQSAIndexer(const ov::OutputVector& args, const Config& config) : Base(args, config) {}++ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;+};++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/include/intel_gpu/op/qsa_indexer.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/qsa_indexer.hppnew file mode 100644index 00000000000..bb6e1903f9c--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/op/qsa_indexer.hpp@@ -0,0 +1,88 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <string>++#include "openvino/core/node.hpp"+#include "openvino/op/op.hpp"++namespace ov::intel_gpu::op {++/// \brief GPU-internal non-paged, stateful complete-block plan producer for Qwen Sparse Attention (QSA).+///+/// Reads no page table and owns no opaque runtime state. The state (`block_index_keys_cache`, and the+/// raw keys and first-token RoPE row of the incomplete block) is passed as inputs and+/// returned, updated, as outputs (functional state interface). `key_length` is the number of+/// valid tokens of each row after the call; rows shorter than `L` are left-padded.+/// RoPE uses the caller-supplied per-token rotate-half `rope_cos`/`rope_sin`.+class QSAIndexer : public ov::op::Op {+public:+ OPENVINO_OP("QSAIndexer", "gpu_opset");++ /// @brief Fixed input order of the QSAIndexer op.+ struct InputIdx {+ static constexpr size_t INDEX_QUERY = 0; ///< [B, L, H_iq, D_idx]+ static constexpr size_t RAW_INDEX_KEYS = 1; ///< [B, L, H_ik, D_idx]+ static constexpr size_t ROPE_COS = 2; ///< [B, L, indexer_rotary_dim]+ static constexpr size_t ROPE_SIN = 3; ///< [B, L, indexer_rotary_dim]+ static constexpr size_t KEY_LENGTH = 4; ///< [B], valid tokens after the call+ static constexpr size_t Q_NORM_WEIGHT = 5; ///< [D_idx]+ static constexpr size_t K_NORM_WEIGHT = 6; ///< [D_idx]+ static constexpr size_t BLOCK_INDEX_KEYS_CACHE = 7; ///< [B, H_ik, floor(S_cap/r), D_idx]+ static constexpr size_t PAST_INCOMPLETE_RAW_K = 8; ///< [B, H_ik, r-1, D_idx], slot p % r+ static constexpr size_t PAST_INCOMPLETE_ROPE = 9; ///< [B, 2*indexer_rotary_dim], (cos_j, sin_j) interleaved++ static constexpr size_t COUNT = 10;+ };++ /// @brief Fixed output order of the QSAIndexer op.+ struct OutputIdx {+ static constexpr size_t SELECTED_BLOCK_INDICES = 0; ///< [B, num_selection_heads, L, block_topk]+ static constexpr size_t SELECTED_BLOCK_COUNT = 1; ///< [B, num_selection_heads, L]+ static constexpr size_t BLOCK_INDEX_KEYS_CACHE = 2; ///< same shape as input BLOCK_INDEX_KEYS_CACHE+ static constexpr size_t PAST_INCOMPLETE_RAW_K = 3; ///< same shape as input PAST_INCOMPLETE_RAW_K+ static constexpr size_t PAST_INCOMPLETE_ROPE = 4; ///< same shape as input PAST_INCOMPLETE_ROPE++ static constexpr size_t COUNT = 5;+ };++ struct Config {+ size_t key_block_size = 4; ///< r+ size_t block_topk = 0; ///< K_max, required+ size_t num_selection_heads = 1; ///< 1 or H_ik+ size_t indexer_rotary_dim = 0; ///< <= indexer_head_dim, even+ size_t indexer_head_dim = 0; ///< D_idx+ float epsilon = 1e-6f; ///< RMSNorm epsilon+ float scale = 0.0f; ///< positive score multiplier; 0 selects the default 1 / sqrt(indexer_head_dim)+ };++ QSAIndexer() = default;+ QSAIndexer(const ov::OutputVector& args, const Config& config);++ bool visit_attributes(ov::AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ const Config& get_config() const {+ return m_config;+ }++ static bool validate_config(const Config& config, std::string& reason);++ /// `scale`, or its 1 / sqrt(indexer_head_dim) default when unset (0).+ static float effective_scale(const Config& config);++ /// H_iq, derived from index_query's static shape (last dim / indexer_head_dim). Never cached.+ size_t get_index_query_heads() const;+ /// H_ik, derived from raw_index_keys's static shape (last dim / indexer_head_dim). Never cached.+ size_t get_index_key_heads() const;++private:+ Config m_config{};+};++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/include/intel_gpu/op/sparse_kv_quant.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/sparse_kv_quant.hppnew file mode 100644index 00000000000..e8e0541d460--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/op/sparse_kv_quant.hpp@@ -0,0 +1,157 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <cstdint>+#include <string>++namespace ov::intel_gpu::op {++/// \brief Quantization of one paged QSA main-KV cache (K or V).+///+/// A quantized cache is a u8 tensor [blocks, Hkv, total_rows, row_bytes]. Per (block, head) page the+/// first `page_size` rows hold the token-major data (4-bit values are packed two per byte, the low nibble+/// holds the even channel); the scale/zero-point parameters follow in the remaining rows:+/// BY_TOKEN : per token `[scale f16][zp f16]` (the zp half is unused when symmetric)+/// BY_CHANNEL : per group of `group_size` tokens `[scale f16 x head_size][zp f16 x head_size]`+/// Dequantization: x = (q - zp) * scale. A symmetric cache stores biased codes (zp = 128 / 8).+struct KVQuant {+ enum class Mode : uint8_t { NONE = 0, BY_TOKEN = 1, BY_CHANNEL = 2 };++ Mode mode = Mode::NONE;+ uint8_t bits = 16; ///< 8 or 4 when quantized+ bool symmetric = false; ///< no zero point stored, biased code+ uint16_t group_size = 0; ///< tokens per parameter group (BY_CHANNEL only)++ bool enabled() const {+ return mode != Mode::NONE;+ }+ bool operator==(const KVQuant& rhs) const {+ return mode == rhs.mode && bits == rhs.bits && symmetric == rhs.symmetric && group_size == rhs.group_size;+ }+ bool operator!=(const KVQuant& rhs) const {+ return !(*this == rhs);+ }+};++/// Byte geometry of one (block, head) page of a cache.+struct KVPageLayout {+ size_t row_bytes = 0; ///< bytes of one token row (last dim of the cache tensor)+ size_t param_bytes = 0; ///< bytes of scale/zp parameters per page+ size_t extra_rows = 0; ///< rows appended to the page to hold the parameters+ size_t total_rows = 0; ///< page_size + extra_rows (third dim of the cache tensor)+ size_t page_bytes = 0; ///< total_rows * row_bytes+ size_t param_offset = 0; ///< byte offset of the parameters inside the page (== page_size * row_bytes)+};++inline KVPageLayout kv_page_layout(const KVQuant& q, size_t page_size, size_t head_size) {+ KVPageLayout l;+ if (!q.enabled()) {+ l.row_bytes = head_size * 2; // f16+ l.total_rows = page_size;+ l.page_bytes = page_size * l.row_bytes;+ l.param_offset = l.page_bytes;+ return l;+ }+ l.row_bytes = head_size * q.bits / 8;+ const size_t values_per_param = q.symmetric ? 1 : 2;+ if (q.mode == KVQuant::Mode::BY_TOKEN) {+ l.param_bytes = page_size * 4; // [scale f16][zp f16], the zp slot is unused when symmetric+ } else {+ l.param_bytes = (page_size / q.group_size) * head_size * values_per_param * 2;+ }+ l.extra_rows = (l.param_bytes + l.row_bytes - 1) / l.row_bytes;+ l.total_rows = page_size + l.extra_rows;+ l.page_bytes = l.total_rows * l.row_bytes;+ l.param_offset = page_size * l.row_bytes;+ return l;+}++/// Checks a cache quantization against the geometry it is applied to. `is_key` enables BY_CHANNEL.+inline bool validate_kv_quant(const KVQuant& q, bool is_key, size_t page_size, size_t head_size, size_t key_block_size, std::string& reason) {+ if (!q.enabled()) {+ return true;+ }+ if (q.bits != 8 && q.bits != 4) {+ reason = "quantized cache must use 8 or 4 bits";+ return false;+ }+ if (page_size == 0) {+ reason = "a quantized cache needs an explicit page_size";+ return false;+ }+ if (head_size < 32 || (head_size & (head_size - 1)) != 0) {+ reason = "a quantized cache needs a power-of-two head size of at least 32";+ return false;+ }+ if (q.mode == KVQuant::Mode::BY_CHANNEL) {+ if (!is_key) {+ reason = "BY_CHANNEL quantization is only supported for the key cache";+ return false;+ }+ if (q.group_size != 16 && q.group_size != 32) {+ reason = "BY_CHANNEL group_size must be 16 or 32";+ return false;+ }+ if (page_size % q.group_size != 0 || (key_block_size != 0 && q.group_size % key_block_size != 0)) {+ reason = "BY_CHANNEL group_size must be a multiple of key_block_size and divide the page size";+ return false;+ }+ } else if (q.group_size != 0) {+ reason = "group_size only applies to BY_CHANNEL quantization";+ return false;+ }+ return true;+}++// ---------------------------------------------------------------------------+// Dense (stateful KVCacheCompressed) K / V histories [B, Hkv, S, D] of SparseSDPA, quantized per token like the+// stateful SDPA's:+//+// data : i8 tensor, D * bits / 8 bytes per token (4-bit: two codes per byte, low nibble = even channel)+// scale (f16), zero point : [B, Hkv, S, 1]+// An 8-bit cache holds signed codes and an i8 zero point (none when symmetric): x = (q - zp) * scale.+// A 4-bit cache holds unsigned codes and an f16 zero point; a symmetric one has biased codes (zp = 8) and no zero point+// tensor.+// ---------------------------------------------------------------------------+inline bool dense_signed_codes(const KVQuant& q) {+ return q.bits == 8;+}++/// The zero point type of the generic stateful SDPA's compressed cache (immad devices): i8, f16 for 4-bit.+inline bool dense_zp_is_f16(const KVQuant& q) {+ return !dense_signed_codes(q);+}++inline size_t dense_row_bytes(const KVQuant& q, size_t head_size) {+ return q.enabled() ? head_size * q.bits / 8 : head_size * 2;+}++/// Checks the quantization of one dense K / V history.+inline bool validate_dense_kv_quant(const KVQuant& q, size_t head_size, std::string& reason) {+ if (!q.enabled()) {+ return true;+ }+ if (q.mode != KVQuant::Mode::BY_TOKEN) {+ reason = "a dense cache is quantized per token";+ return false;+ }+ if (q.bits != 8 && q.bits != 4) {+ reason = "quantized cache must use 8 or 4 bits";+ return false;+ }+ if (head_size < 16 || head_size % 16 != 0) {+ reason = "a quantized cache needs a head size that is a multiple of 16";+ return false;+ }+ if (q.group_size != 0) {+ reason = "a dense cache has no token groups";+ return false;+ }+ return true;+}++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/include/intel_gpu/op/sparse_pa.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/sparse_pa.hppnew file mode 100644index 00000000000..e2827f93051--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/op/sparse_pa.hpp@@ -0,0 +1,81 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <string>++#include "intel_gpu/op/sparse_kv_quant.hpp"+#include "openvino/op/paged_sparse_attention.hpp"++namespace ov::intel_gpu::op {++/// \brief GPU-internal paged sparse attention consumer: the public ov::op::internal::PagedSparseAttention+/// plus the head geometry the kernels are specialized for (derived from the input shapes by the+/// conversion pass). Lowered to cldnn::sparse_pa.+class SparsePA : public ov::op::internal::PagedSparseAttention {+public:+ OPENVINO_OP("SparsePA", "gpu_opset", ov::op::internal::PagedSparseAttention);++ using Base = ov::op::internal::PagedSparseAttention;++ /// @brief Positional inputs, identical to PagedSparseAttention.+ struct InputIdx {+ static constexpr size_t QUERY = 0; ///< [tokens, num_heads*k_head_size]+ static constexpr size_t KEY = 1; ///< [tokens, num_kv_heads*k_head_size], current step+ static constexpr size_t VALUE = 2; ///< [tokens, num_kv_heads*v_head_size], current step+ static constexpr size_t KEY_CACHE = 3; ///< [num_blocks, num_kv_heads, page_size, k_head_size], writable (u8 pages when quantized)+ static constexpr size_t VALUE_CACHE = 4; ///< [num_blocks, num_kv_heads, page_size, v_head_size], writable (u8 pages when quantized)+ static constexpr size_t PAST_LENS = 5; ///< [num_sequences]+ static constexpr size_t SUBSEQUENCE_BEGINS = 6; ///< [num_sequences+1]+ static constexpr size_t BLOCK_INDICES = 7; ///< [total_logical_blocks]+ static constexpr size_t BLOCK_INDICES_BEGINS = 8; ///< [num_sequences+1]+ static constexpr size_t SELECTED_BLOCK_INDICES = 9; ///< [tokens, num_selection_heads, K_max]+ static constexpr size_t SELECTED_BLOCK_COUNT = 10; ///< [tokens, num_selection_heads]+ static constexpr size_t SCALE = 11; ///< scalar+ static constexpr size_t SINKS = 12; ///< [num_heads], or an empty tensor (no sinks)++ static constexpr size_t COUNT = 13;+ };++ struct Config {+ size_t num_heads = 0;+ size_t num_kv_heads = 0;+ size_t num_selection_heads = 1; ///< 1, num_kv_heads, or num_heads+ size_t k_head_size = 0;+ size_t v_head_size = 0;+ size_t key_block_size = 0; ///< must divide the page size+ size_t query_block_size = 1; ///< only 1 is implemented+ bool causal = true;+ size_t page_size = 0; ///< tokens per page; 0 = taken from key_cache dim 2 (f16 caches only)+ KVQuant key_quant{}; ///< quantization of the key cache+ KVQuant value_quant{}; ///< quantization of the value cache++ bool kv_quantized() const {+ return key_quant.enabled() || value_quant.enabled();+ }+ };++ SparsePA() = default;+ SparsePA(const ov::OutputVector& args, const Config& config);++ bool visit_attributes(ov::AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ const Config& get_config() const {+ return m_config;+ }++ /// True unless the sinks input is a statically empty tensor.+ bool has_sinks() const;++ static bool validate_config(const Config& config, std::string& reason);++private:+ Config m_config{};+};++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/include/intel_gpu/op/sparse_sdpa.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/sparse_sdpa.hppnew file mode 100644index 00000000000..eb663d9226d--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/op/sparse_sdpa.hpp@@ -0,0 +1,103 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <string>++#include "intel_gpu/op/sparse_kv_quant.hpp"+#include "openvino/core/node.hpp"+#include "openvino/op/op.hpp"++namespace ov::intel_gpu::op {++/// \brief GPU-internal non-paged (dense) sparse-attention consumer for Qwen Sparse Attention (QSA).+///+/// Reads dense K/V history already materialized by an upstream `KVCache`-style producer+/// (read-only; does not write main K/V or own Indexer state), consumes an upstream+/// Indexer's complete-block selection, derives each query's causal tail from its logical+/// position `q_abs = key_length[b] - L + l`, and performs sparse attention over the union.+/// `key_length` describes left padding: logical key `j` of batch `b` is stored at index+/// `S - key_length[b] + j`.+class SparseSDPA : public ov::op::Op {+public:+ OPENVINO_OP("SparseSDPA", "gpu_opset");++ /// @brief Fixed input order: the six core inputs, then the parameters of a quantized cache, then the optional SCALE and+ /// SINKS (see Config::scale_input_idx() / sinks_input_idx() for their positions).+ struct InputIdx {+ static constexpr size_t QUERY = 0; ///< [B, Hq, L, Dh]+ static constexpr size_t KEY = 1; ///< [B, Hkv, S, Dh], dense history+ static constexpr size_t VALUE = 2; ///< [B, Hkv, S, Dv], dense history+ static constexpr size_t SELECTED_BLOCK_INDICES = 3; ///< [B, num_selection_heads, ceil(L/query_block_size), K_max]+ static constexpr size_t SELECTED_BLOCK_COUNT = 4; ///< [B, num_selection_heads, ceil(L/query_block_size)]+ static constexpr size_t KEY_LENGTH = 5; ///< [B] i32, valid keys per batch row+ static constexpr size_t COUNT_CORE = 6;+ /// Only with a quantized cache (`Config::kv_compressed()`): KEY/VALUE are i8 and the parameters follow in the+ /// KVCacheCompressed planar layout (see sparse_kv_quant.hpp). The zero points are absent when symmetric.+ static constexpr size_t KEY_SCALE = 6; ///< [B, Hkv, S, 1] f16+ static constexpr size_t VALUE_SCALE = 7; ///< [B, Hkv, S, 1] f16+ static constexpr size_t KEY_ZP = 8; ///< same shape as KEY_SCALE, i8 (8-bit BY_TOKEN) or f16+ static constexpr size_t VALUE_ZP = 9; ///< same shape as VALUE_SCALE+ };++ struct Config {+ size_t num_heads = 0;+ size_t num_kv_heads = 0;+ size_t num_selection_heads = 1; ///< 1, num_kv_heads, or num_heads+ size_t k_head_size = 0;+ size_t v_head_size = 0;+ size_t key_block_size = 0; ///< matches producer's key_block_size+ size_t query_block_size = 1; ///< v1 fixed at 1+ bool causal = true;+ KVQuant key_quant{}; ///< quantization of the key history (the K and V histories share bits and symmetry)+ KVQuant value_quant{}; ///< quantization of the value history++ bool kv_compressed() const {+ return key_quant.enabled() || value_quant.enabled();+ }+ /// Inputs between the core ones and the optional SCALE: scales, plus zero points unless symmetric.+ size_t param_input_count() const {+ return !kv_compressed() ? 0 : key_quant.symmetric ? 2 : 4;+ }+ /// Optional scalar or 1-element tensor.+ size_t scale_input_idx() const {+ return InputIdx::COUNT_CORE + param_input_count();+ }+ /// Optional [num_heads] input after SCALE; not supported with a quantized cache.+ size_t sinks_input_idx() const {+ return scale_input_idx() + 1;+ }+ };++ SparseSDPA() = default;+ SparseSDPA(const ov::OutputVector& args, const Config& config, const ov::element::Type output_type = ov::element::dynamic);++ bool visit_attributes(ov::AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ const Config& get_config() const {+ return m_config;+ }+ ov::element::Type get_output_type() const {+ return m_output_type;+ }++ bool has_scale_input() const {+ return get_input_size() > m_config.scale_input_idx();+ }+ bool has_sinks() const {+ return !m_config.kv_compressed() && get_input_size() > m_config.sinks_input_idx();+ }++ static bool validate_config(const Config& config, std::string& reason);++private:+ Config m_config{};+ ov::element::Type m_output_type = ov::element::dynamic;+};++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hppindex 83cb978f7e3..b7fa9d9f8ae 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp@@ -337,3 +337,7 @@ REGISTER_FACTORY(internal, Swoosh);#ifdef ENABLE_MLIR_FOR_GPUREGISTER_FACTORY(internal, MLIR);#endif+REGISTER_FACTORY(internal, PagedQSAIndexerGPU);+REGISTER_FACTORY(internal, QSAIndexer);+REGISTER_FACTORY(internal, SparsePA);+REGISTER_FACTORY(internal, SparseSDPA);diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_qsa_indexer.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_qsa_indexer.hppnew file mode 100644index 00000000000..0a13b14fdd2--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_qsa_indexer.hpp@@ -0,0 +1,85 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <vector>++#include "intel_gpu/op/paged_qsa_indexer.hpp"+#include "primitive.hpp"++namespace cldnn {++/// @brief Paged-cache QSA Indexer primitive: Q1 (prepare) + Q2 (score/top-k).+/// @details See ov::intel_gpu::op::PagedQSAIndexer. Always declares 2 outputs+/// (selected_block_indices, selected_block_count); the raw-K/summary cache inputs are mutated in place.+struct paged_qsa_indexer : public primitive_base<paged_qsa_indexer> {+ CLDNN_DECLARE_PRIMITIVE(paged_qsa_indexer)++ using InputIdx = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;++ paged_qsa_indexer() : primitive_base("", {}) {}++ paged_qsa_indexer(const primitive_id& id, const std::vector<input_info>& inputs, const ov::intel_gpu::op::PagedQSAIndexer::Config& config)+ : primitive_base(id, inputs, 2, {optional_data_type{ov::element::i32}, optional_data_type{ov::element::i32}}),+ key_block_size(config.key_block_size),+ block_topk(config.block_topk),+ num_selection_heads(config.num_selection_heads),+ indexer_rotary_dim(config.indexer_rotary_dim),+ indexer_head_dim(config.indexer_head_dim),+ epsilon(config.epsilon),+ scale(config.scale) {}++ size_t key_block_size = 0;+ size_t block_topk = 0;+ size_t num_selection_heads = 1;+ size_t indexer_rotary_dim = 0;+ size_t indexer_head_dim = 0;+ float epsilon = 1e-6f;+ float scale = 0.0f;++ ov::intel_gpu::op::PagedQSAIndexer::Config get_config() const {+ ov::intel_gpu::op::PagedQSAIndexer::Config config;+ config.key_block_size = key_block_size;+ config.block_topk = block_topk;+ config.num_selection_heads = num_selection_heads;+ config.indexer_rotary_dim = indexer_rotary_dim;+ config.indexer_head_dim = indexer_head_dim;+ config.epsilon = epsilon;+ config.scale = scale;+ return config;+ }++ size_t hash() const override {+ size_t seed = primitive::hash();+ seed = hash_combine(seed, key_block_size);+ seed = hash_combine(seed, block_topk);+ seed = hash_combine(seed, num_selection_heads);+ seed = hash_combine(seed, indexer_rotary_dim);+ seed = hash_combine(seed, indexer_head_dim);+ seed = hash_combine(seed, epsilon);+ seed = hash_combine(seed, scale);+ return seed;+ }++ bool operator==(const primitive& rhs) const override {+ if (!compare_common_params(rhs))+ return false;+ auto r = downcast<const paged_qsa_indexer>(rhs);+ return key_block_size == r.key_block_size && block_topk == r.block_topk && num_selection_heads == r.num_selection_heads &&+ indexer_rotary_dim == r.indexer_rotary_dim && indexer_head_dim == r.indexer_head_dim && epsilon == r.epsilon && scale == r.scale;+ }++ void save(BinaryOutputBuffer& ob) const override {+ primitive_base<paged_qsa_indexer>::save(ob);+ ob << key_block_size << block_topk << num_selection_heads << indexer_rotary_dim << indexer_head_dim << epsilon << scale;+ }++ void load(BinaryInputBuffer& ib) override {+ primitive_base<paged_qsa_indexer>::load(ib);+ ib >> key_block_size >> block_topk >> num_selection_heads >> indexer_rotary_dim >> indexer_head_dim >> epsilon >> scale;+ }+};++} // namespace cldnndiff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/qsa_indexer.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/qsa_indexer.hppnew file mode 100644index 00000000000..b0ccf474804--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/qsa_indexer.hpp@@ -0,0 +1,90 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <vector>++#include "intel_gpu/op/qsa_indexer.hpp"+#include "primitive.hpp"++namespace cldnn {++/// @brief Non-paged (dense, functional-state) QSA Indexer primitive: Q1 (prepare) ++/// Q2 (score/top-k). Outputs: selected_block_indices, selected_block_count, and the updated block_index_keys_cache,+/// past_incomplete_raw_k and past_incomplete_rope state. See ov::intel_gpu::op::QSAIndexer.+struct qsa_indexer : public primitive_base<qsa_indexer> {+ CLDNN_DECLARE_PRIMITIVE(qsa_indexer)++ using InputIdx = ov::intel_gpu::op::QSAIndexer::InputIdx;+ using OutputIdx = ov::intel_gpu::op::QSAIndexer::OutputIdx;++ qsa_indexer() : primitive_base("", {}) {}++ qsa_indexer(const primitive_id& id, const std::vector<input_info>& inputs, const ov::intel_gpu::op::QSAIndexer::Config& config)+ : primitive_base(+ id,+ inputs,+ OutputIdx::COUNT,+ {optional_data_type{ov::element::i32}, optional_data_type{ov::element::i32}, optional_data_type{}, optional_data_type{}, optional_data_type{}}),+ key_block_size(config.key_block_size),+ block_topk(config.block_topk),+ num_selection_heads(config.num_selection_heads),+ indexer_rotary_dim(config.indexer_rotary_dim),+ indexer_head_dim(config.indexer_head_dim),+ epsilon(config.epsilon),+ scale(config.scale) {}++ size_t key_block_size = 0;+ size_t block_topk = 0;+ size_t num_selection_heads = 1;+ size_t indexer_rotary_dim = 0;+ size_t indexer_head_dim = 0;+ float epsilon = 1e-6f;+ float scale = 0.0f;++ ov::intel_gpu::op::QSAIndexer::Config get_config() const {+ ov::intel_gpu::op::QSAIndexer::Config config;+ config.key_block_size = key_block_size;+ config.block_topk = block_topk;+ config.num_selection_heads = num_selection_heads;+ config.indexer_rotary_dim = indexer_rotary_dim;+ config.indexer_head_dim = indexer_head_dim;+ config.epsilon = epsilon;+ config.scale = scale;+ return config;+ }++ size_t hash() const override {+ size_t seed = primitive::hash();+ seed = hash_combine(seed, key_block_size);+ seed = hash_combine(seed, block_topk);+ seed = hash_combine(seed, num_selection_heads);+ seed = hash_combine(seed, indexer_rotary_dim);+ seed = hash_combine(seed, indexer_head_dim);+ seed = hash_combine(seed, epsilon);+ seed = hash_combine(seed, scale);+ return seed;+ }++ bool operator==(const primitive& rhs) const override {+ if (!compare_common_params(rhs))+ return false;+ auto r = downcast<const qsa_indexer>(rhs);+ return key_block_size == r.key_block_size && block_topk == r.block_topk && num_selection_heads == r.num_selection_heads &&+ indexer_rotary_dim == r.indexer_rotary_dim && indexer_head_dim == r.indexer_head_dim && epsilon == r.epsilon && scale == r.scale;+ }++ void save(BinaryOutputBuffer& ob) const override {+ primitive_base<qsa_indexer>::save(ob);+ ob << key_block_size << block_topk << num_selection_heads << indexer_rotary_dim << indexer_head_dim << epsilon << scale;+ }++ void load(BinaryInputBuffer& ib) override {+ primitive_base<qsa_indexer>::load(ib);+ ib >> key_block_size >> block_topk >> num_selection_heads >> indexer_rotary_dim >> indexer_head_dim >> epsilon >> scale;+ }+};++} // namespace cldnndiff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/sparse_pa.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/sparse_pa.hppnew file mode 100644index 00000000000..0f0898d7496--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/sparse_pa.hpp@@ -0,0 +1,142 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <string>+#include <vector>++#include "intel_gpu/op/sparse_pa.hpp"+#include "primitive.hpp"++namespace cldnn {++/// @brief Paged-cache sparse attention consumer primitive: Q0 (K/V cache write) + Q3+/// (selected-block attention with automatically-derived causal tail). Lowered from+/// ov::intel_gpu::op::SparsePA.+struct sparse_pa : public primitive_base<sparse_pa> {+ CLDNN_DECLARE_PRIMITIVE(sparse_pa)++ /// @brief Primitive input order: the leading PagedSparseAttention inputs; scale and sinks are not primitive inputs.+ struct InputIdx {+ static constexpr size_t QUERY = 0; ///< [tokens, num_heads*k_head_size]+ static constexpr size_t KEY = 1; ///< [tokens, num_kv_heads*k_head_size], current step+ static constexpr size_t VALUE = 2; ///< [tokens, num_kv_heads*v_head_size], current step+ static constexpr size_t KEY_CACHE = 3; ///< [num_blocks, num_kv_heads, page_size, k_head_size], writable+ static constexpr size_t VALUE_CACHE = 4; ///< [num_blocks, num_kv_heads, page_size, v_head_size], writable+ static constexpr size_t PAST_LENS = 5; ///< [num_sequences]+ static constexpr size_t SUBSEQUENCE_BEGINS = 6; ///< [num_sequences+1]+ static constexpr size_t BLOCK_INDICES = 7; ///< [total_logical_blocks]+ static constexpr size_t BLOCK_INDICES_BEGINS = 8; ///< [num_sequences+1]+ static constexpr size_t SELECTED_BLOCK_INDICES = 9; ///< [tokens, num_selection_heads, K_max]+ static constexpr size_t SELECTED_BLOCK_COUNT = 10; ///< [tokens, num_selection_heads]+ static constexpr size_t COUNT = 11;+ };++ using Config = ov::intel_gpu::op::SparsePA::Config;++ static bool validate_config(const Config& c, std::string& reason) {+ return ov::intel_gpu::op::SparsePA::validate_config(c, reason);+ }++ sparse_pa() : primitive_base("", {}) {}++ /// @param inputs QUERY..SELECTED_BLOCK_COUNT of InputIdx only; scale (a lowered Constant input) is passed resolved.+ sparse_pa(const primitive_id& id, const std::vector<input_info>& inputs, const Config& config, float scale)+ : primitive_base(id, inputs),+ num_heads(config.num_heads),+ num_kv_heads(config.num_kv_heads),+ num_selection_heads(config.num_selection_heads),+ k_head_size(config.k_head_size),+ v_head_size(config.v_head_size),+ key_block_size(config.key_block_size),+ query_block_size(config.query_block_size),+ scale(scale),+ causal(config.causal),+ page_size(config.page_size),+ key_quant(config.key_quant),+ value_quant(config.value_quant) {}++ size_t num_heads = 0;+ size_t num_kv_heads = 0;+ size_t num_selection_heads = 1;+ size_t k_head_size = 0;+ size_t v_head_size = 0;+ size_t key_block_size = 0;+ size_t query_block_size = 1;+ float scale = 0.0f;+ bool causal = true;+ size_t page_size = 0; ///< 0 = key_cache dim 2 (f16 caches)+ ov::intel_gpu::op::KVQuant key_quant{};+ ov::intel_gpu::op::KVQuant value_quant{};++ Config get_config() const {+ Config config;+ config.num_heads = num_heads;+ config.num_kv_heads = num_kv_heads;+ config.num_selection_heads = num_selection_heads;+ config.k_head_size = k_head_size;+ config.v_head_size = v_head_size;+ config.key_block_size = key_block_size;+ config.query_block_size = query_block_size;+ config.causal = causal;+ config.page_size = page_size;+ config.key_quant = key_quant;+ config.value_quant = value_quant;+ return config;+ }++ size_t hash() const override {+ size_t seed = primitive::hash();+ seed = hash_combine(seed, num_heads);+ seed = hash_combine(seed, num_kv_heads);+ seed = hash_combine(seed, num_selection_heads);+ seed = hash_combine(seed, k_head_size);+ seed = hash_combine(seed, v_head_size);+ seed = hash_combine(seed, key_block_size);+ seed = hash_combine(seed, query_block_size);+ seed = hash_combine(seed, scale);+ seed = hash_combine(seed, causal);+ seed = hash_combine(seed, page_size);+ for (const auto* q : {&key_quant, &value_quant}) {+ seed = hash_combine(seed, static_cast<size_t>(q->mode));+ seed = hash_combine(seed, static_cast<size_t>(q->bits));+ seed = hash_combine(seed, q->symmetric);+ seed = hash_combine(seed, static_cast<size_t>(q->group_size));+ }+ return seed;+ }++ bool operator==(const primitive& rhs) const override {+ if (!compare_common_params(rhs))+ return false;+ auto r = downcast<const sparse_pa>(rhs);+ return num_heads == r.num_heads && num_kv_heads == r.num_kv_heads && num_selection_heads == r.num_selection_heads && k_head_size == r.k_head_size &&+ v_head_size == r.v_head_size && key_block_size == r.key_block_size && query_block_size == r.query_block_size && scale == r.scale &&+ causal == r.causal && page_size == r.page_size && key_quant == r.key_quant && value_quant == r.value_quant;+ }++ void save(BinaryOutputBuffer& ob) const override {+ primitive_base<sparse_pa>::save(ob);+ ob << num_heads << num_kv_heads << num_selection_heads << k_head_size << v_head_size << key_block_size << query_block_size << scale << causal+ << page_size;+ for (const auto* q : {&key_quant, &value_quant}) {+ ob << static_cast<uint8_t>(q->mode) << q->bits << q->symmetric << q->group_size;+ }+ }++ void load(BinaryInputBuffer& ib) override {+ primitive_base<sparse_pa>::load(ib);+ ib >> num_heads >> num_kv_heads >> num_selection_heads >> k_head_size >> v_head_size >> key_block_size >> query_block_size >> scale >> causal >>+ page_size;+ for (auto* q : {&key_quant, &value_quant}) {+ uint8_t mode = 0;+ ib >> mode >> q->bits >> q->symmetric >> q->group_size;+ q->mode = static_cast<ov::intel_gpu::op::KVQuant::Mode>(mode);+ }+ }+};++} // namespace cldnndiff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/sparse_sdpa.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/sparse_sdpa.hppnew file mode 100644index 00000000000..5291bc92a2d--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/sparse_sdpa.hpp@@ -0,0 +1,120 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <vector>++#include "intel_gpu/op/sparse_sdpa.hpp"+#include "primitive.hpp"++namespace cldnn {++/// @brief Non-paged (dense) sparse attention consumer primitive: Q3 only, read-only on+/// main K/V. See ov::intel_gpu::op::SparseSDPA. Inputs: the core inputs and, with a quantized cache, the+/// parameter inputs (same positions as in the op). A constant scale input is folded into `scale`; sinks are not+/// supported, lowering must reject them explicitly rather than construct this primitive.+struct sparse_sdpa : public primitive_base<sparse_sdpa> {+ CLDNN_DECLARE_PRIMITIVE(sparse_sdpa)++ using InputIdx = ov::intel_gpu::op::SparseSDPA::InputIdx;++ sparse_sdpa() : primitive_base("", {}) {}++ sparse_sdpa(const primitive_id& id, const std::vector<input_info>& inputs, const ov::intel_gpu::op::SparseSDPA::Config& config, float resolved_scale)+ : primitive_base(id, inputs),+ num_heads(config.num_heads),+ num_kv_heads(config.num_kv_heads),+ num_selection_heads(config.num_selection_heads),+ k_head_size(config.k_head_size),+ v_head_size(config.v_head_size),+ key_block_size(config.key_block_size),+ query_block_size(config.query_block_size),+ causal(config.causal),+ scale(resolved_scale),+ key_quant(config.key_quant),+ value_quant(config.value_quant) {}++ size_t num_heads = 0;+ size_t num_kv_heads = 0;+ size_t num_selection_heads = 1;+ size_t k_head_size = 0;+ size_t v_head_size = 0;+ size_t key_block_size = 0;+ size_t query_block_size = 1;+ bool causal = true;+ /// Resolved at lowering time: either the op's default (1/sqrt(k_head_size)) or a+ /// constant-folded value of the optional SCALE input.+ float scale = 0.0f;+ ov::intel_gpu::op::KVQuant key_quant{};+ ov::intel_gpu::op::KVQuant value_quant{};++ bool kv_compressed() const {+ return key_quant.enabled() || value_quant.enabled();+ }++ ov::intel_gpu::op::SparseSDPA::Config get_config() const {+ ov::intel_gpu::op::SparseSDPA::Config config;+ config.num_heads = num_heads;+ config.num_kv_heads = num_kv_heads;+ config.num_selection_heads = num_selection_heads;+ config.k_head_size = k_head_size;+ config.v_head_size = v_head_size;+ config.key_block_size = key_block_size;+ config.query_block_size = query_block_size;+ config.causal = causal;+ config.key_quant = key_quant;+ config.value_quant = value_quant;+ return config;+ }++ size_t hash() const override {+ size_t seed = primitive::hash();+ seed = hash_combine(seed, num_heads);+ seed = hash_combine(seed, num_kv_heads);+ seed = hash_combine(seed, num_selection_heads);+ seed = hash_combine(seed, k_head_size);+ seed = hash_combine(seed, v_head_size);+ seed = hash_combine(seed, key_block_size);+ seed = hash_combine(seed, query_block_size);+ seed = hash_combine(seed, causal);+ seed = hash_combine(seed, scale);+ for (const auto* q : {&key_quant, &value_quant}) {+ seed = hash_combine(seed, static_cast<size_t>(q->mode));+ seed = hash_combine(seed, static_cast<size_t>(q->bits));+ seed = hash_combine(seed, q->symmetric);+ seed = hash_combine(seed, static_cast<size_t>(q->group_size));+ }+ return seed;+ }++ bool operator==(const primitive& rhs) const override {+ if (!compare_common_params(rhs))+ return false;+ auto r = downcast<const sparse_sdpa>(rhs);+ return num_heads == r.num_heads && num_kv_heads == r.num_kv_heads && num_selection_heads == r.num_selection_heads && k_head_size == r.k_head_size &&+ v_head_size == r.v_head_size && key_block_size == r.key_block_size && query_block_size == r.query_block_size && causal == r.causal &&+ scale == r.scale && key_quant == r.key_quant && value_quant == r.value_quant;+ }++ void save(BinaryOutputBuffer& ob) const override {+ primitive_base<sparse_sdpa>::save(ob);+ ob << num_heads << num_kv_heads << num_selection_heads << k_head_size << v_head_size << key_block_size << query_block_size << causal << scale;+ for (const auto* q : {&key_quant, &value_quant}) {+ ob << static_cast<uint8_t>(q->mode) << q->bits << q->symmetric << q->group_size;+ }+ }++ void load(BinaryInputBuffer& ib) override {+ primitive_base<sparse_sdpa>::load(ib);+ ib >> num_heads >> num_kv_heads >> num_selection_heads >> k_head_size >> v_head_size >> key_block_size >> query_block_size >> causal >> scale;+ for (auto* q : {&key_quant, &value_quant}) {+ uint8_t mode = 0;+ ib >> mode >> q->bits >> q->symmetric >> q->group_size;+ q->mode = static_cast<ov::intel_gpu::op::KVQuant::Mode>(mode);+ }+ }+};++} // namespace cldnndiff --git a/src/plugins/intel_gpu/sources.cmake b/src/plugins/intel_gpu/sources.cmakeindex 18a84259f67..ea51365eaf7 100644--- a/src/plugins/intel_gpu/sources.cmake+++ b/src/plugins/intel_gpu/sources.cmake@@ -91,12 +91,14 @@ set(GPU_PLUGIN_OPS_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/paged_attention.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/paged_causal_conv1d.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/paged_gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/paged_qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/paged_selective_ssm.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/parameter.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/placeholder.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/pooling.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/prior_box.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/proposal.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/random_uniform.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/range.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/reduce.cpp@@ -129,6 +131,8 @@ set(GPU_PLUGIN_OPS_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/space_to_batch.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/space_to_depth.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/sparse_fill_empty_rows.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/sparse_pa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/sparse_sdpa.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/split.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/stateless_kv.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/stft.cpp@@ -223,9 +227,13 @@ set(GPU_PLUGIN_TRANSFORMATIONS_OP_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/lora_subgraph_fused.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/mlir_op.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/moe_router_fused.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/paged_qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/placeholder.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/read_value.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/sdpa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/sparse_pa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/sparse_sdpa.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/stateless_kv.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/swoosh.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/swiglu_with_clamp.cppdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cppindex bcf058b1e11..24d7979e18e 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cpp@@ -437,6 +437,26 @@ struct kv_cache_impl : multi_stage_primitive<kv_cache> {return params;}+ // The past cache of a 4-bit KV cache is packed (head_size / 2 bytes per row) while the layout compiled for the+ // ReadValue still carries head_size: the shape agnostic concat would bake the unpacked row length into its kernel and+ // copy the old rows with a wrong pitch whenever the cache is reallocated. Follow the (packed) output instead.+ static layout get_past_kv_layout(const kernel_impl_params& impl_param) {+ auto past_layout = impl_param.input_layouts[0];+ if (!impl_param.typed_desc<kv_cache>()->compressed) {+ return past_layout;+ }+ auto shape = past_layout.get_partial_shape();+ const auto& packed_shape = impl_param.output_layouts[0].get_partial_shape();+ const auto last = shape.size() - 1;+ if (shape.size() == packed_shape.size() && shape[last].is_static() && packed_shape[last].is_static() &&+ ov::element::Type(impl_param.get_program().get_config().get_kv_cache_precision()).bitwidth() == 4 &&+ shape[last].get_length() == packed_shape[last].get_length() * 2) {+ shape[last] = packed_shape[last];+ past_layout.set_partial_shape(shape);+ }+ return past_layout;+ }+static kernel_params_t get_concat_kernel_params(const kernel_impl_params& impl_param, bool is_shape_agnostic = false) {const auto& primitive = impl_param.typed_desc<kv_cache>();auto params = get_default_params<kernel_selector::concatenation_params>(impl_param, is_shape_agnostic);@@ -445,7 +465,7 @@ struct kv_cache_impl : multi_stage_primitive<kv_cache> {const auto inputs_count = 2;params.inputs.resize(inputs_count);for (size_t i = 0; i < inputs_count; ++i) {- params.inputs[i] = convert_data_tensor(impl_param.input_layouts[i]);+ params.inputs[i] = convert_data_tensor(i == 0 ? get_past_kv_layout(impl_param) : impl_param.input_layouts[i]);}params.axis = convert_axis(axis, impl_param.get_output_layout().get_rank());@@ -666,7 +686,7 @@ struct kv_cache_impl : multi_stage_primitive<kv_cache> {auto& params = static_cast<kernel_params_t&>(*_kernels_data[concat_stage].params);const auto inputs_count = 2;for (size_t i = 0; i < inputs_count; ++i) {- params.inputs[i] = convert_data_tensor(impl_param.input_layouts[i]);+ params.inputs[i] = convert_data_tensor(i == 0 ? get_past_kv_layout(impl_param) : impl_param.input_layouts[i]);}params.outputs[0] = convert_data_tensor(impl_param.output_layouts[0]);diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hppindex 58689dd2095..aa5df061b68 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp@@ -316,7 +316,15 @@ struct PrimitiveImplOCL : public cldnn::primitive_impl {OPENVINO_ASSERT(kernels.size() == 1, "Only the kernels of the single primitive should be allowed.");auto& kernel_vec = kernels.begin()->second;for (auto& [kernel, sub_kernel_idx] : kernel_vec) {- _stages[sub_kernel_idx]->kernel = kernel;+ // sub_kernel_idx is a LOCAL index (0..get_kernels_source().size()-1), i.e. a position+ // within the source list returned by get_kernels_source(), which iterates `_order` -+ // it is NOT a global `_stages` index. Multi-stage impls (any node whose add_stage()+ // calls registered more than one stage, or a single-stage node whose stage isn't at+ // _stages[0]) need+ // the same local->global translation init_kernels()/init_by_cached_kernels() already do+ // via `_order[i]`, otherwise this silently binds the compiled kernel to the wrong Stage+ // object (or leaves the real stage's kernel null) - a guaranteed crash on execute().+ _stages[_order[sub_kernel_idx]]->kernel = kernel;}}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_common.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_common.clnew file mode 100644index 00000000000..051d2136b3d--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_common.cl@@ -0,0 +1,761 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Shared helpers of the QSA indexer / sparse attention OpenCL kernels.+//+// Vector elements are spread over the subgroup lanes: element `lane + SG * j` of a row lives in slot `j` of lane+// `lane` (the layout produced by intel_sub_group_block_read_us*).+//+// Every helper is decorated with FUNC() so that the kernels batched into one program do not redefine it,+// and the header deliberately has no include guard (each kernel gets its own copy, built against its own JIT).+//+// Opt-in sections (define before including):+// QSA_INDEXER_HELPERS - RMSNorm / partial NEOX RoPE of an index head vector (needs QSA_IDX_HEAD_DIM, ...)+// QSA_ATTENTION_HELPERS - paged / dense input signature, K/V row addressing, scalar attend and, with+// QSA_XMX_WORKERS, the XMX building blocks (needs QSA_K_HEAD_SIZE, ...)++#include "include/batch_headers/common.cl"++#ifdef cl_intel_subgroups_short+# pragma OPENCL EXTENSION cl_intel_subgroups_short : enable+#endif+#ifdef cl_intel_subgroups+# pragma OPENCL EXTENSION cl_intel_subgroups : enable+#endif+#ifdef cl_intel_subgroup_local_block_io+# pragma OPENCL EXTENSION cl_intel_subgroup_local_block_io : enable+#endif+#ifdef cl_intel_subgroups_char+# pragma OPENCL EXTENSION cl_intel_subgroups_char : enable+#endif++#ifndef QSA_MAX_NE+# define QSA_MAX_NE 32+#endif+#define QSA_SG SUBGROUP_SIZE+#define QSA_NEG_INF (-3.0e38f)+#define QSA_LOG2E 1.4426950408889634f++// ---------------------------------------------------------------------------+// Subgroup block IO: out[j] / v[j] is element (lane + SG * j) of the row+// ---------------------------------------------------------------------------+inline void FUNC(qsa_rd)(const __global ushort* p, __private ushort* out, const uint n) {+ uint j = 0;+ for (; j + 8 <= n; j += 8) {+ ushort8 r = intel_sub_group_block_read_us8(p + j * QSA_SG);+ out[j + 0] = r.s0; out[j + 1] = r.s1; out[j + 2] = r.s2; out[j + 3] = r.s3;+ out[j + 4] = r.s4; out[j + 5] = r.s5; out[j + 6] = r.s6; out[j + 7] = r.s7;+ }+ if (n - j >= 4) {+ ushort4 r = intel_sub_group_block_read_us4(p + j * QSA_SG);+ out[j + 0] = r.s0; out[j + 1] = r.s1; out[j + 2] = r.s2; out[j + 3] = r.s3;+ j += 4;+ }+ if (n - j >= 2) {+ ushort2 r = intel_sub_group_block_read_us2(p + j * QSA_SG);+ out[j + 0] = r.s0; out[j + 1] = r.s1;+ j += 2;+ }+ if (n - j >= 1) {+ out[j] = intel_sub_group_block_read_us(p + j * QSA_SG);+ }+}++inline void FUNC(qsa_wr)(__global ushort* p, const __private ushort* v, const uint n) {+ uint j = 0;+ for (; j + 8 <= n; j += 8) {+ intel_sub_group_block_write_us8(p + j * QSA_SG, (ushort8)(v[j + 0], v[j + 1], v[j + 2], v[j + 3], v[j + 4], v[j + 5], v[j + 6], v[j + 7]));+ }+ if (n - j >= 4) {+ intel_sub_group_block_write_us4(p + j * QSA_SG, (ushort4)(v[j + 0], v[j + 1], v[j + 2], v[j + 3]));+ j += 4;+ }+ if (n - j >= 2) {+ intel_sub_group_block_write_us2(p + j * QSA_SG, (ushort2)(v[j + 0], v[j + 1]));+ j += 2;+ }+ if (n - j >= 1) {+ intel_sub_group_block_write_us(p + j * QSA_SG, v[j]);+ }+}++// f16 row -> f32+inline void FUNC(qsa_rd_f32)(const __global half* p, __private float* v, const uint n) {+ ushort t[QSA_MAX_NE];+ FUNC_CALL(qsa_rd)((const __global ushort*)p, t, n);+ unroll_for (uint j = 0; j < n; j++) {+ v[j] = convert_float(as_half(t[j]));+ }+}++// f32 row -> f16 row (RTNE)+inline void FUNC(qsa_wr_f32)(__global half* p, const __private float* v, const uint n) {+ ushort t[QSA_MAX_NE];+ unroll_for (uint j = 0; j < n; j++) {+ t[j] = as_ushort(convert_half_rte(v[j]));+ }+ FUNC_CALL(qsa_wr)((__global ushort*)p, t, n);+}++// ---------------------------------------------------------------------------+// Address arithmetic (element offsets)+// ---------------------------------------------------------------------------+inline uint FUNC(qsa_kv_cache_offset)(uint page, uint kv_head, uint token_in_page, uint kv_heads, uint pa_block_size, uint head_size) {+ return ((page * kv_heads + kv_head) * pa_block_size + token_in_page) * head_size;+}++inline uint FUNC(qsa_num_complete_blocks)(uint abs_pos) {+ return (abs_pos + 1) / (uint)QSA_COMPRESS_RATIO;+}++// Resolves a flattened paged token to its sequence and absolute position; false for rows past the last real token.+inline bool FUNC(qsa_resolve_token_paged)(const __global int* subsequence_begins,+ const __global int* past_lens,+ uint num_seqs,+ uint token_idx,+ __private uint* seq,+ __private uint* abs_pos) {+ *seq = 0;+ *abs_pos = 0;+ for (uint i = 0; i < num_seqs; i++) {+ if (token_idx >= (uint)subsequence_begins[i] && token_idx < (uint)subsequence_begins[i + 1]) {+ *seq = i;+ *abs_pos = (uint)past_lens[i] + token_idx - (uint)subsequence_begins[i];+ return true;+ }+ }+ return false;+}++// Maps query tile `tile` onto its sequence and the global index of its first token.+inline bool FUNC(qsa_resolve_tile_paged)(const __global int* subsequence_begins,+ uint num_seqs,+ uint tile,+ uint tile_tokens,+ __private uint* seq,+ __private uint* token_begin) {+ uint acc = 0;+ for (uint i = 0; i < num_seqs; i++) {+ const uint begin = (uint)subsequence_begins[i];+ const uint q_len = (uint)subsequence_begins[i + 1] - begin;+ const uint n = (q_len + tile_tokens - 1) / tile_tokens;+ if (tile < acc + n) {+ *seq = i;+ *token_begin = begin + (tile - acc) * tile_tokens;+ return true;+ }+ acc += n;+ }+ return false;+}++// Dense token t = b * seq_len + l -> batch and logical position; a left-padding row yields 0xFFFFFFFF.+inline void FUNC(qsa_resolve_token_dense)(const __global int* key_length, uint seq_len, uint token_idx, __private uint* batch, __private uint* abs_pos) {+ *batch = token_idx / seq_len;+ const uint shifted = (uint)key_length[*batch] + (token_idx - *batch * seq_len);+ *abs_pos = shifted >= seq_len ? shifted - seq_len : 0xFFFFFFFFu;+}++// ---------------------------------------------------------------------------+// Math+// ---------------------------------------------------------------------------+// One online-softmax step on a score that is uniform over the subgroup.+inline void FUNC(qsa_softmax_step)(float score, __private float* running_max, __private float* running_sum, __private float* corr, __private float* weight) {+ const float new_max = *running_max > score ? *running_max : score;+ const float e0 = native_exp2((*running_max - new_max) * QSA_LOG2E);+ const float e1 = native_exp2((score - new_max) * QSA_LOG2E);+ *corr = e0;+ *weight = e1;+ *running_sum = *running_sum * e0 + e1;+ *running_max = new_max;+}++// ---------------------------------------------------------------------------+// Quantized main-KV cache helpers (opt-in: QSA_KVQ_HELPERS, implied by QSA_ATTENTION_HELPERS). The page layout is+// documented in intel_gpu/op/sparse_kv_quant.hpp: per (block, kv head) page, `page_size` token-major data rows of+// QSA_X_ROW_BYTES bytes (4-bit codes packed two per byte, low nibble = even channel) followed, at QSA_X_PARAM_OFFSET,+// by the scale / zero-point parameters. Dequantization is x = (q - zp) * scale.+//+// JIT per cache X in {K, V}: QSA_X_MODE (0 = f16, 1 = by token, 2 = by channel), QSA_X_BITS, QSA_X_SYM (biased codes,+// no zero point stored), QSA_X_GROUP (tokens per by-channel group), QSA_X_ROW_BYTES, QSA_X_PAGE_BYTES,+// QSA_X_PARAM_OFFSET.+// ---------------------------------------------------------------------------+#ifndef QSA_K_MODE+# define QSA_K_MODE 0+#endif+#ifndef QSA_V_MODE+# define QSA_V_MODE 0+#endif+#ifndef QSA_DENSE_QUANT+# define QSA_DENSE_QUANT 0+#endif+#define QSA_K_QUANT (QSA_K_MODE != 0 || QSA_DENSE_QUANT)+#define QSA_V_QUANT (QSA_V_MODE != 0 || QSA_DENSE_QUANT)+#define QSA_ANY_QUANT (QSA_K_QUANT || QSA_V_QUANT)++#if defined(QSA_KVQ_HELPERS) || defined(QSA_ATTENTION_HELPERS)+// Smallest scale kept, so that 1 / scale stays finite in f16 / f32.+# define QSA_KVQ_MIN_SCALE (1.0f / 16384.0f)++inline float FUNC(qsa_q_zero_sym)(const uint bits) {+ return bits == 8 ? 128.0f : 8.0f;+}++// (code - zp) * scale in f16 arithmetic: every step is rounded to half, so all kernels see the same dequantized values.+inline float FUNC(qsa_q_dq)(const float code, const float zp, const float scale) {+ return convert_float(convert_half_rte(convert_float(convert_half_rte(code - zp)) * scale));+}++// Byte offsets of token `tok` of `page`: its data row and its parameters (a token dword for by-token caches, the+// group record for by-channel ones).+inline void FUNC(qsa_q_loc)(const uint page,+ const uint kv_head,+ const uint tok,+ const uint mode,+ const uint group,+ const uint page_bytes,+ const uint row_bytes,+ const uint param_off,+ const uint head,+ const uint sym,+ const uint kv_heads,+ __private uint* row_off,+ __private uint* par_off) {+ const uint pb = (page * kv_heads + kv_head) * page_bytes;+ *row_off = pb + tok * row_bytes;+ *par_off = mode == 1 ? pb + param_off + tok * 4 : pb + param_off + (tok / group) * (head * (sym ? 2 : 4));+}++// Byte offsets of token `tok` of `page` of the K / V cache of kv head `kv_head` (a variable of the caller).+# define QSA_K_LOC(page, tok, ro, po) \+ FUNC_CALL(qsa_q_loc)(page, kv_head, tok, QSA_K_MODE, QSA_K_GROUP, QSA_K_PAGE_BYTES, QSA_K_ROW_BYTES, QSA_K_PARAM_OFFSET, QSA_K_HEAD_SIZE, QSA_K_SYM, QSA_KV_HEADS, ro, po)+# define QSA_V_LOC(page, tok, ro, po) \+ FUNC_CALL(qsa_q_loc)(page, kv_head, tok, QSA_V_MODE, 1, QSA_V_PAGE_BYTES, QSA_V_ROW_BYTES, QSA_V_PARAM_OFFSET, QSA_V_HEAD_SIZE, QSA_V_SYM, QSA_KV_HEADS, ro, po)++// Subgroup block read of bytes: out[j] is byte (lane + SG * j) of p.+inline void FUNC(qsa_rd_uc)(const __global uchar* p, __private uchar* out, const uint n) {+ uint j = 0;+ for (; j + 8 <= n; j += 8) {+ uchar8 r = intel_sub_group_block_read_uc8(p + j * QSA_SG);+ out[j + 0] = r.s0; out[j + 1] = r.s1; out[j + 2] = r.s2; out[j + 3] = r.s3;+ out[j + 4] = r.s4; out[j + 5] = r.s5; out[j + 6] = r.s6; out[j + 7] = r.s7;+ }+ if (n - j >= 4) {+ uchar4 r = intel_sub_group_block_read_uc4(p + j * QSA_SG);+ out[j + 0] = r.s0; out[j + 1] = r.s1; out[j + 2] = r.s2; out[j + 3] = r.s3;+ j += 4;+ }+ if (n - j >= 2) {+ uchar2 r = intel_sub_group_block_read_uc2(p + j * QSA_SG);+ out[j + 0] = r.s0; out[j + 1] = r.s1;+ j += 2;+ }+ if (n - j >= 1) {+ out[j] = intel_sub_group_block_read_uc(p + j * QSA_SG);+ }+}++// Codes of channels x0 + SG * j + lane (j < ne) of the packed row `row`. 8-bit rows are read with block reads; 4-bit+// rows with one byte load per lane and channel (a block read plus shuffles is slower).+inline void FUNC(qsa_q_load_codes)(const __global uchar* row, const uint x0, __private float* code, const uint ne, const uint bits, const bool is_signed) {+ if (bits == 8) {+ uchar b[QSA_MAX_NE];+ FUNC_CALL(qsa_rd_uc)(row + x0, b, ne);+ unroll_for (uint j = 0; j < ne; j++) {+ code[j] = is_signed ? convert_float((char)b[j]) : convert_float(b[j]);+ }+ } else {+ const uint lane = get_sub_group_local_id();+ unroll_for (uint j = 0; j < ne; j++) {+ const uchar v = row[(x0 + QSA_SG * j + lane) >> 1];+ code[j] = convert_float((lane & 1) ? (v >> 4) : (v & 0xF));+ }+ }+}++// Dequantized channels x0 + SG * j + lane (j < ne) of a quantized paged row, block-read.+inline void FUNC(qsa_q_load_cols)(const __global uchar* cache,+ const uint row_off,+ const uint par_off,+ const uint x0,+ __private float* out,+ const uint ne,+ const uint mode,+ const uint bits,+ const uint sym,+ const uint head) {+ FUNC_CALL(qsa_q_load_codes)(cache + row_off, x0, out, ne, bits, false);+ if (mode == 1) {+ const uint pd = *(const __global uint*)(cache + par_off);+ const float scale = convert_float(as_half((ushort)(pd & 0xFFFFu)));+ const float zp = sym ? FUNC_CALL(qsa_q_zero_sym)(bits) : convert_float(as_half((ushort)(pd >> 16)));+ unroll_for (uint j = 0; j < ne; j++) {+ out[j] = FUNC_CALL(qsa_q_dq)(out[j], zp, scale);+ }+ } else {+ ushort sc[QSA_MAX_NE], zq[QSA_MAX_NE];+ FUNC_CALL(qsa_rd)((const __global ushort*)(cache + par_off) + x0, sc, ne);+ if (!sym) {+ FUNC_CALL(qsa_rd)((const __global ushort*)(cache + par_off + head * 2) + x0, zq, ne);+ }+ unroll_for (uint j = 0; j < ne; j++) {+ const float zp = sym ? FUNC_CALL(qsa_q_zero_sym)(bits) : convert_float(as_half(zq[j]));+ out[j] = FUNC_CALL(qsa_q_dq)(out[j], zp, convert_float(as_half(sc[j])));+ }+ }+}++// Dequantized channels x0 + SG * j + lane (j < ne) of a dense (KVCacheCompressed) row, see sparse_kv_quant.hpp. `row_off` is+// the byte offset of the row, `po` the token index into the scale / zero point tensors.+// `is_signed` rows hold signed 8-bit codes (symmetric ones have no zero point), the others unsigned codes with an f16 zero+// point (symmetric ones are biased).+inline void FUNC(qsa_q_load_cols_dense)(const __global uchar* data,+ const uint row_off,+ const uint x0,+ __private float* out,+ const uint ne,+ const uint bits,+ const uint sym,+ const uint is_signed,+ const uint zp_f16,+ const __global half* scale,+ const __global uchar* zp,+ const uint po) {+ FUNC_CALL(qsa_q_load_codes)(data + row_off, x0, out, ne, bits, is_signed != 0);+ const float zero_sym = is_signed ? 0.0f : FUNC_CALL(qsa_q_zero_sym)(bits);+ const float sc = convert_float(scale[po]);+ float z = zero_sym;+ if (!sym) {+ z = zp_f16 ? convert_float(((const __global half*)zp)[po]) : convert_float(((const __global char*)zp)[po]);+ }+ unroll_for (uint j = 0; j < ne; j++) {+ out[j] = FUNC_CALL(qsa_q_dq)(out[j], z, sc);+ }+}++// Quantizes a lane-mapped row (x[j] = channel lane + SG * j, j < ne) to per-lane codes. scale / zp are the f16-rounded+// parameters, uniform over the subgroup.+inline void FUNC(qsa_q_quant_row)(const __private float* x,+ __private uint* code,+ const uint ne,+ const uint bits,+ const uint sym,+ __private half* scale_h,+ __private half* zp_h) {+ float mn = x[0];+ float mx = x[0];+ unroll_for (uint j = 1; j < ne; j++) {+ mn = fmin(mn, x[j]);+ mx = fmax(mx, x[j]);+ }+ mn = sub_group_reduce_min(mn);+ mx = sub_group_reduce_max(mx);+ const float qmax = bits == 8 ? 255.0f : 15.0f;+ float scale, zp;+ if (sym) {+ scale = fmax(mx, -mn) / (bits == 8 ? 127.0f : 7.0f);+ scale = fmax(scale, QSA_KVQ_MIN_SCALE);+ zp = FUNC_CALL(qsa_q_zero_sym)(bits);+ } else {+ mn = fmin(mn, 0.0f);+ mx = fmax(mx, 0.0f);+ scale = fmax((mx - mn) / qmax, QSA_KVQ_MIN_SCALE);+ zp = -mn / scale;+ }+ *scale_h = convert_half_rte(scale);+ *zp_h = convert_half_rte(zp);+ const float inv = 1.0f / convert_float(*scale_h);+ const float zpf = convert_float(*zp_h);+ unroll_for (uint j = 0; j < ne; j++) {+ const float y = clamp(x[j] * inv + zpf, 0.0f, qmax) + 0.5f;+ code[j] = (uint)y;+ }+}++// Stores lane-mapped codes as one packed row (4-bit: adjacent channels share a byte, low nibble = even channel).+inline void FUNC(qsa_q_store_codes)(__global uchar* cache, const uint row_off, const __private uint* code, const uint ne, const uint bits) {+ const uint lane = get_sub_group_local_id();+ unroll_for (uint j = 0; j < ne; j++) {+ const uint c = lane + QSA_SG * j;+ if (bits == 8) {+ cache[row_off + c] = (uchar)code[j];+ } else {+ const uint partner = intel_sub_group_shuffle(code[j], lane ^ 1);+ if ((lane & 1) == 0) {+ cache[row_off + (c >> 1)] = (uchar)(code[j] | (partner << 4));+ }+ }+ }+}+#endif // QSA_KVQ_HELPERS || QSA_ATTENTION_HELPERS++// ---------------------------------------------------------------------------+// Indexer-only helpers: RMSNorm and partial NEOX RoPE over a head vector spread over the subgroup lanes.+// ---------------------------------------------------------------------------+#ifdef QSA_INDEXER_HELPERS+# define QSA_NE (QSA_IDX_HEAD_DIM / QSA_SG)++// RMSNorm with f32 accumulation; the gain is applied exactly as stored.+inline void FUNC(qsa_rms_norm)(__private float* v, const __global half* weight) {+ const uint lane = get_sub_group_local_id();+ float sumsq = 0.0f;+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ sumsq += v[j] * v[j];+ }+ sumsq = sub_group_reduce_add(sumsq);+ const float denom = sumsq / (float)QSA_IDX_HEAD_DIM + (float)QSA_IDX_NORM_EPS;+ const float inv = native_rsqrt(denom);+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ v[j] = v[j] * inv * convert_float(weight[lane + QSA_SG * j]);+ }+}++# if QSA_IDX_ROTARY_DIM > 0+// Partial NEOX rope: channel d < H pairs with d + H (H = rotary_dim / 2). `cp[d * cs]` / `sp[d * cs]` are the coefficients.+inline void FUNC(qsa_rope)(__private float* v, const __global half* cp, const __global half* sp, const uint cs) {+ const uint lane = get_sub_group_local_id();+ const uint H = QSA_IDX_ROTARY_DIM / 2;+ float o[QSA_NE];+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ const uint d = lane + QSA_SG * j;+ float res = v[j];+# if ((QSA_IDX_ROTARY_DIM / 2) % SUBGROUP_SIZE) == 0+ const uint hs = H / QSA_SG;+ float pv = 0.0f;+ if (QSA_SG * j < QSA_IDX_ROTARY_DIM) {+ pv = (QSA_SG * j < H) ? v[min(j + hs, (uint)(QSA_NE - 1))] : v[j >= hs ? j - hs : 0];+ }+# else+ const uint dp = d < H ? d + H : (d < QSA_IDX_ROTARY_DIM ? d - H : d);+ const uint lp = dp % QSA_SG;+ const uint jp = dp / QSA_SG;+ float pv = 0.0f;+ unroll_for (uint jj = 0; jj < QSA_NE; jj++) {+ const float t = intel_sub_group_shuffle(v[jj], lp);+ pv = jp == jj ? t : pv;+ }+# endif+ if (d < QSA_IDX_ROTARY_DIM) {+ const float c = convert_float(cp[d * cs]);+ const float s = convert_float(sp[d * cs]);+ res = d < H ? v[j] * c - pv * s : v[j] * c + pv * s;+ }+ o[j] = res;+ }+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ v[j] = o[j];+ }+}+# endif+#endif // QSA_INDEXER_HELPERS++// ---------------------------------------------------------------------------+// Shared pieces of the sparse attention kernels: the paged / dense (QSA_ADDRESS_MODE 0 / 1) input signature, the K/V+// row addressing, the scalar attend helper and (when QSA_XMX_WORKERS is defined before including) the XMX building+// blocks of the systolic kernels.+//+// Kernels using QSA_KROW / QSA_VROW must declare, in paged mode, `block_indices`, `page_begin` and `kv_head`, and in+// dense mode `batch`, `kv_head`, `shift` (history_len - key_length), `k_pitch`, `v_pitch`.+// ---------------------------------------------------------------------------+#ifdef QSA_ATTENTION_HELPERS+# ifndef QSA_ADDRESS_MODE+# define QSA_ADDRESS_MODE 0+# endif++# if QSA_K_QUANT+# define QSA_KC_T uchar+# else+# define QSA_KC_T half+# endif+# if QSA_V_QUANT+# define QSA_VC_T uchar+# else+# define QSA_VC_T half+# endif++// Dense compressed K/V: the f16 scale tensors (and, unless QSA_K_SYM, the zero point tensors: i8 or f16 per+// QSA_{K,V}_ZP_F16) follow key_length, their sequence pitches (independent of the data's) follow v_pitch (declared by the+// kernels). Helper functions take the tensors FIRST, with the trailing comma inside the macro. Note the kernel minifier+// drops the line after an unused empty #define, hence the sentinels.+# if QSA_DENSE_QUANT+# if QSA_K_SYM+// Symmetric caches have no zero points: the scale pointer stands in for the (unused) zero point argument.+# define QSA_QP_DECL const __global half* key_scale, const __global half* value_scale,+# define QSA_QP_ARGS key_scale, value_scale,+# define QSA_KZP_PTR ((const __global uchar*)key_scale)+# define QSA_VZP_PTR ((const __global uchar*)value_scale)+# else+# define QSA_QP_DECL const __global half* key_scale, const __global half* value_scale, const __global uchar* key_zp, const __global uchar* value_zp,+# define QSA_QP_ARGS key_scale, value_scale, key_zp, value_zp,+# define QSA_KZP_PTR key_zp+# define QSA_VZP_PTR value_zp+# endif+# else+# define QSA_QP_DECL+# define QSA_QP_SENTINEL_1 0+# define QSA_QP_ARGS+# define QSA_QP_SENTINEL_2 0+# endif++# if QSA_ADDRESS_MODE == 0+# define QSA_ATT_INPUT_ARGS const __global half* query, const __global QSA_KC_T* key_cache, const __global QSA_VC_T* value_cache, const __global int* past_lens, const __global int* subsequence_begins, const __global int* block_indices, const __global int* block_indices_begins, const __global int* selected_blocks, const __global int* selected_counts+# define QSA_KROW(pos) FUNC_CALL(qsa_kv_cache_offset)((uint)block_indices[page_begin + (pos) / QSA_PAGE_SIZE], kv_head, (pos) % QSA_PAGE_SIZE, QSA_KV_HEADS, QSA_PAGE_SIZE, QSA_K_HEAD_SIZE)+# define QSA_VROW(pos) FUNC_CALL(qsa_kv_cache_offset)((uint)block_indices[page_begin + (pos) / QSA_PAGE_SIZE], kv_head, (pos) % QSA_PAGE_SIZE, QSA_KV_HEADS, QSA_PAGE_SIZE, QSA_V_HEAD_SIZE)+# else+# if QSA_DENSE_QUANT+# if QSA_K_SYM+# define QSA_ATT_INPUT_ARGS const __global half* query, const __global QSA_KC_T* key_cache, const __global QSA_VC_T* value_cache, const __global int* selected_blocks, const __global int* selected_counts, const __global int* key_length, const __global half* key_scale, const __global half* value_scale+# else+# define QSA_ATT_INPUT_ARGS const __global half* query, const __global QSA_KC_T* key_cache, const __global QSA_VC_T* value_cache, const __global int* selected_blocks, const __global int* selected_counts, const __global int* key_length, const __global half* key_scale, const __global half* value_scale, const __global uchar* key_zp, const __global uchar* value_zp+# endif+# else+# define QSA_ATT_INPUT_ARGS const __global half* query, const __global QSA_KC_T* key_cache, const __global QSA_VC_T* value_cache, const __global int* selected_blocks, const __global int* selected_counts, const __global int* key_length+# endif+# define QSA_KROW(pos) (((((batch) * QSA_KV_HEADS) + kv_head) * k_pitch + shift + (pos)) * QSA_K_HEAD_SIZE)+# define QSA_VROW(pos) (((((batch) * QSA_KV_HEADS) + kv_head) * v_pitch + shift + (pos)) * QSA_V_HEAD_SIZE)+// Byte offset of a quantized row (4-bit rows are packed).+# define QSA_KROWB(pos) (((((batch) * QSA_KV_HEADS) + kv_head) * k_pitch + shift + (pos)) * QSA_K_ROW_BYTES)+# define QSA_VROWB(pos) (((((batch) * QSA_KV_HEADS) + kv_head) * v_pitch + shift + (pos)) * QSA_V_ROW_BYTES)+// Flat index of a token in the dense scale / zero-point tensors.+# define QSA_KPAR(pos) (((((batch) * QSA_KV_HEADS) + kv_head) * k_ppitch + shift + (pos)))+# define QSA_VPAR(pos) (((((batch) * QSA_KV_HEADS) + kv_head) * v_ppitch + shift + (pos)))+# endif++# define QSA_NEK (QSA_K_HEAD_SIZE / QSA_SG)+# define QSA_NEV (QSA_V_HEAD_SIZE / QSA_SG)++// Dequantized channels of the K / V row at byte offset `ro` with parameter locator `po` (paged: byte offset, dense: token+// index in the parameter tensors): out[j] is channel x0 + SG * j + lane.+# if QSA_DENSE_QUANT+# define QSA_LOAD_K_COLS(ro, po, x0, out, ne) FUNC_CALL(qsa_q_load_cols_dense)((const __global uchar*)key_cache, ro, x0, out, ne, QSA_K_BITS, QSA_K_SYM, QSA_K_SIGNED, QSA_K_ZP_F16, key_scale, QSA_KZP_PTR, po)+# define QSA_LOAD_V_COLS(ro, po, x0, out, ne) FUNC_CALL(qsa_q_load_cols_dense)((const __global uchar*)value_cache, ro, x0, out, ne, QSA_V_BITS, QSA_V_SYM, QSA_V_SIGNED, QSA_V_ZP_F16, value_scale, QSA_VZP_PTR, po)+# else+# define QSA_LOAD_K_COLS(ro, po, x0, out, ne) FUNC_CALL(qsa_q_load_cols)((const __global uchar*)key_cache, ro, po, x0, out, ne, QSA_K_MODE, QSA_K_BITS, QSA_K_SYM, QSA_K_HEAD_SIZE)+# define QSA_LOAD_V_COLS(ro, po, x0, out, ne) FUNC_CALL(qsa_q_load_cols)((const __global uchar*)value_cache, ro, po, x0, out, ne, QSA_V_MODE, QSA_V_BITS, QSA_V_SYM, QSA_V_HEAD_SIZE)+# endif++// Row locators (row offset, parameter locator) of the K / V row at position `pos` of the sequence.+# if QSA_ADDRESS_MODE == 0+# define QSA_K_ROWLOC(pos, ro, po) \+ { \+ const uint pg_ = (uint)block_indices[page_begin + (pos) / QSA_PAGE_SIZE]; \+ QSA_K_LOC(pg_, (pos) % QSA_PAGE_SIZE, &(ro), &(po)); \+ }+# define QSA_V_ROWLOC(pos, ro, po) \+ { \+ const uint pg_ = (uint)block_indices[page_begin + (pos) / QSA_PAGE_SIZE]; \+ QSA_V_LOC(pg_, (pos) % QSA_PAGE_SIZE, &(ro), &(po)); \+ }+# else+# define QSA_K_ROWLOC(pos, ro, po) \+ { \+ ro = QSA_KROWB(pos); \+ po = QSA_KPAR(pos); \+ }+# define QSA_V_ROWLOC(pos, ro, po) \+ { \+ ro = QSA_VROWB(pos); \+ po = QSA_VPAR(pos); \+ }+# endif++// Lane-mapped float row of the K / V cache at `pos` (x[j] = channel lane + SG * j).+# define QSA_LOAD_K(x, pos) \+ { \+ if (QSA_K_QUANT) { \+ uint ro_, po_; \+ QSA_K_ROWLOC(pos, ro_, po_); \+ QSA_LOAD_K_COLS(ro_, po_, 0, x, QSA_NEK); \+ } else { \+ FUNC_CALL(qsa_rd_f32)((const __global half*)key_cache + QSA_KROW(pos), x, QSA_NEK); \+ } \+ }+# define QSA_LOAD_V(x, pos) \+ { \+ if (QSA_V_QUANT) { \+ uint ro_, po_; \+ QSA_V_ROWLOC(pos, ro_, po_); \+ QSA_LOAD_V_COLS(ro_, po_, 0, x, QSA_NEV); \+ } else { \+ FUNC_CALL(qsa_rd_f32)((const __global half*)value_cache + QSA_VROW(pos), x, QSA_NEV); \+ } \+ }++// Scalar attend over already loaded (dequantized) K / V rows.+inline void FUNC(qsa_scalar_attend_vals)(__private const float* kf,+ __private const float* vf,+ __private const float* q,+ __private float* acc,+ __private float* running_max,+ __private float* running_sum) {+ float dot = 0.0f;+ unroll_for (uint j = 0; j < QSA_NEK; j++) {+ dot += q[j] * kf[j];+ }+ const float score = sub_group_reduce_add(dot);++ float corr = 0.0f, weight = 0.0f;+ FUNC_CALL(qsa_softmax_step)(score, running_max, running_sum, &corr, &weight);+ unroll_for (uint j = 0; j < QSA_NEV; j++) {+ acc[j] = acc[j] * corr + vf[j] * weight;+ }+}++inline void FUNC(qsa_scalar_attend)(const __global half* krow,+ const __global half* vrow,+ __private const float* q,+ __private float* acc,+ __private float* running_max,+ __private float* running_sum) {+ ushort kr[QSA_NEK];+ ushort vr[QSA_NEV];+ FUNC_CALL(qsa_rd)((const __global ushort*)krow, kr, QSA_NEK);+ FUNC_CALL(qsa_rd)((const __global ushort*)vrow, vr, QSA_NEV);++ float dot = 0.0f;+ unroll_for (uint j = 0; j < QSA_NEK; j++) {+ dot += q[j] * convert_float(as_half(kr[j]));+ }+ const float score = sub_group_reduce_add(dot);++ float corr = 0.0f, weight = 0.0f;+ FUNC_CALL(qsa_softmax_step)(score, running_max, running_sum, &corr, &weight);+ unroll_for (uint j = 0; j < QSA_NEV; j++) {+ acc[j] = acc[j] * corr + convert_float(as_half(vr[j])) * weight;+ }+}++# ifdef QSA_XMX_WORKERS+// ---------------------------------------------------------------------------+// XMX building blocks (SIMD16). One KV step = 16 rows, row i of the step is held by lane i; the lane axis of the+// score tile is the query column.+// ---------------------------------------------------------------------------+# define QSA_XW QSA_XMX_WORKERS+# define QSA_XDH (QSA_K_HEAD_SIZE / QSA_XW)+# define QSA_XDV (QSA_V_HEAD_SIZE / QSA_XW)+# define QSA_XKT (QSA_XDH / 16)+# define QSA_XVT (QSA_XDV / 8)+# define QSA_XST_FLOATS (2 * 8 * QSA_SG)++# ifdef cl_intel_subgroup_local_block_io+# define QSA_SLM_WRITE8(p, v) intel_sub_group_block_write8((__local uint*)(p), as_uint8(v))+# define QSA_SLM_READ8(p) as_float8(intel_sub_group_block_read8((__local uint*)(p)))+# else+# define QSA_SLM_WRITE8(p, v) FUNC_CALL(qsa_slm_write8)((__local float*)(p), v)+# define QSA_SLM_READ8(p) FUNC_CALL(qsa_slm_read8)((__local float*)(p))+inline void FUNC(qsa_slm_write8)(__local float* p, float8 v) {+ const uint l = get_sub_group_local_id();+ p[0 * QSA_SG + l] = v.s0; p[1 * QSA_SG + l] = v.s1; p[2 * QSA_SG + l] = v.s2; p[3 * QSA_SG + l] = v.s3;+ p[4 * QSA_SG + l] = v.s4; p[5 * QSA_SG + l] = v.s5; p[6 * QSA_SG + l] = v.s6; p[7 * QSA_SG + l] = v.s7;+}+inline float8 FUNC(qsa_slm_read8)(__local float* p) {+ const uint l = get_sub_group_local_id();+ return (float8)(p[0 * QSA_SG + l], p[1 * QSA_SG + l], p[2 * QSA_SG + l], p[3 * QSA_SG + l],+ p[4 * QSA_SG + l], p[5 * QSA_SG + l], p[6 * QSA_SG + l], p[7 * QSA_SG + l]);+}+# endif++// K rows of one step as the A operand: kr[i][k] = K[row i][worker * XDH + 16 k + lane]. `koff` is this lane's+// (row = lane) element offset into the K cache; rows >= valid_kv are zero.+inline void FUNC(qsa_xmx_k_load)(const __global half* key_cache, const uint koff, const uint valid_kv, const uint worker, __private ushort (*kr)[QSA_XKT]) {+ unroll_for (uint i = 0; i < 16; i++) {+ const uint ko = sub_group_broadcast(koff, i);+ if (i < valid_kv) {+ FUNC_CALL(qsa_rd)((const __global ushort*)(key_cache + ko + worker * QSA_XDH), kr[i], QSA_XKT);+ } else {+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ kr[i][k] = 0;+ }+ }+ }+}++// QK of one step from preloaded K rows: st[i] = sum over the worker slices of K[row i] . q (this lane's column). With+// several workers the partial tiles are summed through SLM in the fixed order w = 0..W-1, so every worker sees+// bit-identical scores.+inline void FUNC(qsa_xmx_qk_regs)(__private ushort (*kr)[QSA_XKT],+ __private const int8* rq,+ const uint worker,+# if QSA_XW > 1+ __local float* slm, // [W][2][8][SG] of the current slot+# endif+ __private float* st) {+ float8 st0 = (float8)(0.0f);+ float8 st1 = (float8)(0.0f);+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ const short8 a0 = (short8)((short)kr[0][k], (short)kr[1][k], (short)kr[2][k], (short)kr[3][k],+ (short)kr[4][k], (short)kr[5][k], (short)kr[6][k], (short)kr[7][k]);+ const short8 a1 = (short8)((short)kr[8][k], (short)kr[9][k], (short)kr[10][k], (short)kr[11][k],+ (short)kr[12][k], (short)kr[13][k], (short)kr[14][k], (short)kr[15][k]);+ st0 = intel_sub_group_f16_f16_matrix_mad_k16(a0, rq[k], st0);+ st1 = intel_sub_group_f16_f16_matrix_mad_k16(a1, rq[k], st1);+ }+# if QSA_XW > 1+ QSA_SLM_WRITE8(slm + worker * QSA_XST_FLOATS, st0);+ QSA_SLM_WRITE8(slm + worker * QSA_XST_FLOATS + 8 * QSA_SG, st1);+ barrier(CLK_LOCAL_MEM_FENCE);+ st0 = QSA_SLM_READ8(slm);+ st1 = QSA_SLM_READ8(slm + 8 * QSA_SG);+ for (uint w = 1; w < QSA_XW; w++) {+ st0 += QSA_SLM_READ8(slm + w * QSA_XST_FLOATS);+ st1 += QSA_SLM_READ8(slm + w * QSA_XST_FLOATS + 8 * QSA_SG);+ }+# endif+ vstore8(st0, 0, st);+ vstore8(st1, 0, st + 8);+}++inline void FUNC(qsa_xmx_qk)(const __global half* key_cache,+ const uint koff,+ const uint valid_kv,+ __private const int8* rq,+ const uint worker,+# if QSA_XW > 1+ __local float* slm,+# endif+ __private float* st) {+ ushort kr[16][QSA_XKT];+ FUNC_CALL(qsa_xmx_k_load)(key_cache, koff, valid_kv, worker, kr);+# if QSA_XW > 1+ FUNC_CALL(qsa_xmx_qk_regs)(kr, rq, worker, slm, st);+# else+ FUNC_CALL(qsa_xmx_qk_regs)(kr, rq, worker, st);+# endif+}++// This lane's (row = lane) slice of V for one step: va[d] = V[row][worker * XDV + d * 8 .. + 8], zero when !lv.+// Rows are DV-aligned, so 32-byte vector loads are legal (scalar half loads would split into dword gathers).+inline void FUNC(qsa_xmx_v_load)(const __global half* value_cache, const uint voff, const bool lv, const uint worker, __private uint4* va) {+ const __global uint8* src = (const __global uint8*)(value_cache + voff + worker * QSA_XDV);+ unroll_for (uint d = 0; d < QSA_XVT; d += 2) {+ const uint8 v = src[d / 2];+ va[d] = lv ? v.lo : (uint4)(0);+ va[d + 1] = lv ? v.hi : (uint4)(0);+ }+}++// PV of one step: ro[d][i] += sum over the 16 rows of V[row][dv0 + i] * p[row] (this lane's column). V^T is the A+// operand (one KV row per lane, preloaded by qsa_xmx_v_load), P^T the B operand packed in-lane.+inline void FUNC(qsa_xmx_pv_regs)(__private const uint4* va, __private const float* p, __private float8* ro) {+ const int8 bp = (int8)(as_int(convert_half2_rte((float2)(p[0], p[1]))), as_int(convert_half2_rte((float2)(p[2], p[3]))),+ as_int(convert_half2_rte((float2)(p[4], p[5]))), as_int(convert_half2_rte((float2)(p[6], p[7]))),+ as_int(convert_half2_rte((float2)(p[8], p[9]))), as_int(convert_half2_rte((float2)(p[10], p[11]))),+ as_int(convert_half2_rte((float2)(p[12], p[13]))), as_int(convert_half2_rte((float2)(p[14], p[15]))));+ unroll_for (uint d = 0; d < QSA_XVT; d++) {+ ro[d] = intel_sub_group_f16_f16_matrix_mad_k16(as_short8(va[d]), bp, ro[d]);+ }+}++inline void FUNC(qsa_xmx_pv)(const __global half* value_cache,+ const uint voff,+ const bool lv,+ __private const float* p,+ const uint worker,+ __private float8* ro) {+ uint4 va[QSA_XVT];+ FUNC_CALL(qsa_xmx_v_load)(value_cache, voff, lv, worker, va);+ FUNC_CALL(qsa_xmx_pv_regs)(va, p, ro);+}+# endif+#endif // QSA_ATTENTION_HELPERSdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_host_common.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_host_common.hppnew file mode 100644index 00000000000..a2abf92465d--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_host_common.hpp@@ -0,0 +1,269 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Host-side helpers shared by the QSA indexer / sparse-attention OpenCL implementations: routing predicates,+// scratch sizing rules, the common kernel generator and the implementation switch.++#pragma once++#include <algorithm>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <limits>+#include <optional>+#include <string>+#include <string_view>++#include "common_utils/jitter.hpp"+#include "intel_gpu/graph/kernel_impl_params.hpp"+#include "intel_gpu/op/sparse_kv_quant.hpp"+#include "intel_gpu/runtime/device_info.hpp"+#include "intel_gpu/runtime/kernel_args.hpp"+#include "openvino/core/except.hpp"+#include "openvino/core/type/float16.hpp"+#include "primitive_ocl_base.hpp"+#include "utils/kernel_generator.hpp"++namespace ov::intel_gpu::ocl::qsa {++/// Marks one stage's dispatch data and kernel arguments (incl. scalars) for recomputation.+inline void force_stage_refresh(Stage& stage) {+ stage.kd.need_dispatch_data_update = true;+ stage.kd.need_args_update = true;+}++/// For impls whose work sizes/scalars depend on runtime input VALUES (e.g. past_lens), which change between+/// same-shape calls without raising SHAPE_CHANGED.+inline void force_stages_refresh(PrimitiveImplOCL& impl) {+ for (auto* stage : impl._stages) {+ force_stage_refresh(*stage);+ }+}++/// OV_GPU_QSA_OCL_DISABLE_XMX=1 routes every stage to the scalar kernels (for testing them on XMX hardware).+inline bool xmx_allowed(const cldnn::device_info& info) {+ const char* v = std::getenv("OV_GPU_QSA_OCL_DISABLE_XMX");+ if (v != nullptr && std::string_view(v) == "1") {+ return false;+ }+ return info.arch >= cldnn::gpu_arch::xe2 && info.supports_immad;+}++inline size_t subgroup_size(const cldnn::device_info& info) {+ return info.arch >= cldnn::gpu_arch::xe2 ? 16 : 8;+}++/// Basic requirement of every OpenCL kernel of this family: subgroup block IO on halves.+inline bool subgroups_available(const cldnn::device_info& info) {+ return info.supports_intel_subgroups && info.supports_intel_subgroups_short;+}++inline void push_u32(KernelData& kd, size_t value) {+ OPENVINO_ASSERT(value <= std::numeric_limits<uint32_t>::max(), "[GPU][OCL] QSA kernel scalar ", value, " does not fit in 32 bits");+ cldnn::scalar_desc s;+ s.t = cldnn::scalar_desc::Types::UINT32;+ s.v.u32 = static_cast<uint32_t>(value);+ kd.params.scalars.push_back(s);+}++/// JIT description of one paged main-KV cache (`cache` is "K" or "V"): QSA_<cache>_{MODE,BITS,SYM,GROUP,ROW_BYTES,+/// PAGE_BYTES,PARAM_OFFSET}. An f16 cache has MODE 0.+inline void add_cache_jit(JitConstants& jit, const std::string& cache, const ov::intel_gpu::op::KVQuant& quant, size_t page_size, size_t head_size) {+ const auto layout = ov::intel_gpu::op::kv_page_layout(quant, page_size, head_size);+ const std::string prefix = "QSA_" + cache + "_";+ jit.make(prefix + "MODE", static_cast<int>(quant.mode));+ jit.make(prefix + "BITS", quant.enabled() ? static_cast<int>(quant.bits) : 16);+ jit.make(prefix + "SYM", quant.symmetric ? 1 : 0);+ jit.make(prefix + "GROUP", std::max<int>(1, static_cast<int>(quant.group_size)));+ jit.make(prefix + "ROW_BYTES", layout.row_bytes);+ jit.make(prefix + "PAGE_BYTES", layout.page_bytes);+ jit.make(prefix + "PARAM_OFFSET", layout.param_offset);+}++/// JIT description of one dense (KVCacheCompressed) K / V history: QSA_<cache>_{BITS,SYM,ROW_BYTES} plus SIGNED (8-bit:+/// signed codes) and ZP_F16 (the zero point tensor is f16, else i8), see sparse_kv_quant.hpp.+inline void add_dense_cache_jit(JitConstants& jit, const std::string& cache, const ov::intel_gpu::op::KVQuant& quant, size_t head_size) {+ const std::string prefix = "QSA_" + cache + "_";+ jit.make(prefix + "BITS", quant.enabled() ? static_cast<int>(quant.bits) : 16);+ jit.make(prefix + "SYM", quant.symmetric ? 1 : 0);+ jit.make(prefix + "ROW_BYTES", ov::intel_gpu::op::dense_row_bytes(quant, head_size));+ jit.make(prefix + "SIGNED", quant.enabled() && ov::intel_gpu::op::dense_signed_codes(quant) ? 1 : 0);+ jit.make(prefix + "ZP_F16", quant.enabled() && ov::intel_gpu::op::dense_zp_is_f16(quant) ? 1 : 0);+}++/// Upper bound on the decode BLOCK_SCORES scratch. Debug builds can shrink it through OV_GPU_QSA_SCORE_BUDGET_BYTES+/// to force the multi-chunk path with small shapes.+inline size_t score_budget_bytes() {+ if (const char* override_str = std::getenv("OV_GPU_QSA_SCORE_BUDGET_BYTES")) {+ const auto value = std::strtoull(override_str, nullptr, 10);+ if (value > 0) {+ return static_cast<size_t>(value);+ }+ }+ return 128 * 1024 * 1024;+}++/// Row pitch (in floats) of BLOCK_SCORES: a multiple of 8 so the 8-wide score stores of the systolic scorer never+/// leave their row.+inline size_t score_pitch(size_t max_blocks) {+ return (std::max<size_t>(1, max_blocks) + 7) / 8 * 8;+}++/// Most subgroups of a top-k work-group (sizes its SLM) and the count used by the longest rows.+constexpr size_t topk_max_subgroups = 16;++/// Subgroups of the top-k work-group for rows of at most max_blocks blocks: ~16 keys per lane on the longest row (fewer+/// barriers and idle lanes on short rows). With topk_reg_keys keys per lane, 16 subgroups keep 16K blocks in registers.+inline size_t topk_wg_subgroups(size_t max_blocks) {+ size_t w = 1;+ while (w < topk_max_subgroups && w * 256 < max_blocks) {+ w *= 2;+ }+ return w;+}++/// Keys of one row each lane of the top-k work-group holds in registers (longer rows rescan global memory per probe).+constexpr size_t topk_reg_keys = 64;++/// Thresholds counted per top-k probe (at most 7): 3 -> 16 probes for 32 key bits; more only adds per-key work.+constexpr size_t topk_thresholds = 3;++inline constexpr size_t dpas_query_tile = 16;+inline constexpr size_t dpas_k_step = 16;+inline constexpr size_t dpas_wide_cols = 32;+inline constexpr size_t gqa_workers = 4;+inline constexpr size_t split_partitions = 16;+inline constexpr size_t gqa_split_partitions = 64;++inline size_t split_reduce_cols(size_t v_head_size) {+ return v_head_size % 32 == 0 ? 32 : 16;+}++template <class Desc>+size_t dpas_heads_per_tile(const Desc& desc) {+ const auto n_rep = desc.num_heads / desc.num_kv_heads;+ for (size_t ht : {size_t{8}, size_t{4}, size_t{2}}) {+ if (n_rep % ht == 0) {+ return ht;+ }+ }+ return 1;+}++template <class Desc>+size_t dpas_attention_workers(const Desc& desc) {+ constexpr size_t reg_budget = 12 * 1024;+ for (size_t w : {size_t{1}, size_t{2}, size_t{4}, size_t{8}}) {+ if (desc.k_head_size % (w * dpas_k_step) != 0 || desc.v_head_size % (w * dpas_query_tile) != 0) {+ continue;+ }+ const auto dh_w = desc.k_head_size / w;+ const auto dv_w = desc.v_head_size / w;+ if (dh_w % dpas_wide_cols != 0 || dv_w % dpas_wide_cols != 0) {+ continue;+ }+ const auto rq = dh_w * dpas_query_tile * sizeof(ov::float16);+ const auto ro = dpas_query_tile * dv_w * sizeof(float);+ const auto kv = dpas_k_step * (dh_w + dv_w) * sizeof(ov::float16);+ if (rq + ro + kv <= reg_budget) {+ return w;+ }+ }+ return 0;+}++template <class Desc>+bool can_use_dpas_attention(const Desc& desc, std::optional<size_t> page_size, const cldnn::device_info& info) {+ if (!xmx_allowed(info)) {+ return false;+ }+ if (desc.k_head_size % dpas_k_step != 0 || desc.v_head_size % dpas_query_tile != 0) {+ return false;+ }+ if (desc.k_head_size * sizeof(ov::float16) < 64 || desc.v_head_size * sizeof(ov::float16) < 64) {+ return false;+ }+ if (desc.key_block_size % 2 != 0 || dpas_k_step % desc.key_block_size != 0) {+ return false;+ }+ if (page_size && *page_size % desc.key_block_size != 0) {+ return false;+ }+ return dpas_attention_workers(desc) != 0;+}++template <class Desc>+bool can_use_gqa_dpas_attention(const Desc& desc, std::optional<size_t> page_size, const cldnn::device_info& info) {+ if (!xmx_allowed(info)) {+ return false;+ }+ if (desc.num_kv_heads == 0 || desc.num_heads % desc.num_kv_heads != 0) {+ return false;+ }+ const auto n_rep = desc.num_heads / desc.num_kv_heads;+ if (n_rep < 1 || n_rep > 16) {+ return false;+ }+ if (desc.k_head_size % (gqa_workers * 32) != 0 || desc.v_head_size % (gqa_workers * 32) != 0) {+ return false;+ }+ if (std::max(desc.k_head_size, desc.v_head_size) > 256) {+ return false;+ }+ if (desc.key_block_size != 2 && desc.key_block_size != 4 && desc.key_block_size != 8 && desc.key_block_size != 16) {+ return false;+ }+ if (page_size && (*page_size == 0 || *page_size % desc.key_block_size != 0)) {+ return false;+ }+ return desc.causal;+}++template <class Desc>+size_t decode_split_partitions(const Desc& desc, std::optional<size_t> page_size, const cldnn::device_info& info) {+ return can_use_gqa_dpas_attention(desc, page_size, info) ? gqa_split_partitions : split_partitions;+}++/// Float as an OpenCL C literal with the full single precision.+inline JitConstant float_constant(const std::string& name, float value) {+ char buf[64];+ std::snprintf(buf, sizeof(buf), "%.9gf", static_cast<double>(value));+ return JitConstant(name, buf);+}++/// Common base of every QSA OpenCL stage: names the entry point `<entry>_ocl_<hash>` (the tests recognise the kernel+/// by that prefix), adds the subgroup size and, for the register hungry stages, the 256 GRF mode.+class QsaGenerator : public KernelGenerator {+public:+ QsaGenerator(std::string_view template_name, std::string entry_name, bool large_grf = false)+ : KernelGenerator(template_name, ""),+ m_entry_name(std::move(entry_name)),+ m_large_grf(large_grf) {}++protected:+ [[nodiscard]] std::string get_entry_point(const RuntimeParams& params) const override {+ return m_entry_name + "_ocl_" + std::to_string(params.hash()) + (params.is_dynamic() ? "__sa" : "");+ }++ [[nodiscard]] std::string get_build_options(const RuntimeParams& params) const override {+ auto options = KernelGenerator::get_build_options(params);+ if (m_large_grf && params.get_device_info().arch >= cldnn::gpu_arch::xe_hpg) {+ options += " -cl-intel-256-GRF-per-thread";+ }+ return options;+ }++ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_base_jit_constants(params);+ jit.make("SUBGROUP_SIZE", subgroup_size(params.get_device_info()));+ return jit;+ }++private:+ std::string m_entry_name;+ bool m_large_grf;+};++} // namespace ov::intel_gpu::ocl::qsadiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/paged_qsa_indexer.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/paged_qsa_indexer.cppnew file mode 100644index 00000000000..678524c14d2--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/paged_qsa_indexer.cpp@@ -0,0 +1,494 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "paged_qsa_indexer.hpp"++#include <algorithm>+#include <cassert>+#include <memory>+#include <string>+#include <vector>++#include "../primitive_ocl_base.hpp"+#include "../qsa_host_common.hpp"+#include "common_utils/jitter.hpp"+#include "intel_gpu/graph/kernel_impl_params.hpp"+#include "intel_gpu/primitives/paged_qsa_indexer.hpp"+#include "primitive_inst.h"++namespace ov::intel_gpu::ocl {++using namespace cldnn;+using QSAIn = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;++namespace {++/// Tokens per physical page: dim 2 of index_key_cache (there is no page_size attribute).+size_t page_size_of(const kernel_impl_params& params) {+ const auto& ps = params.get_input_layout(QSAIn::INDEX_KEY_CACHE).get_partial_shape();+ OPENVINO_ASSERT(ps.size() == 4 && ps[2].is_static(), "[GPU][OCL] paged_qsa_indexer: index_key_cache must have a static page_size dim");+ return static_cast<size_t>(ps[2].get_length());+}++PagedQSAIndexerRuntimeParams* rt_of(ImplRuntimeParams* rt) {+ auto* p = static_cast<PagedQSAIndexerRuntimeParams*>(rt);+ OPENVINO_ASSERT(p != nullptr, "[GPU][OCL] paged_qsa_indexer runtime params are not initialized");+ return p;+}++size_t index_heads(const layout& l, size_t indexer_head_dim) {+ const auto& ps = l.get_partial_shape();+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() >= 2 && ps[1].is_static() && indexer_head_dim != 0,+ "[GPU][OCL] paged_qsa_indexer: cannot derive index head count");+ return static_cast<size_t>(ps[1].get_length()) / indexer_head_dim;+}++JitConstants make_jit(JitConstants jit, const std::shared_ptr<const paged_qsa_indexer>& desc, const RuntimeParams& params) {+ const auto h_iq = index_heads(params.get_input_layout(QSAIn::INDEX_QUERY), desc->indexer_head_dim);+ jit.make("QSA_IDX_QUERY_HEADS", h_iq);+ jit.make("QSA_IDX_HEAD_DIM", desc->indexer_head_dim);+ jit.make("QSA_IDX_ROTARY_DIM", desc->indexer_rotary_dim);+ jit.make("QSA_COMPRESS_RATIO", desc->key_block_size);+ jit.make("QSA_PAGE_SIZE", page_size_of(params));+ jit.make("QSA_BLOCK_TOPK", desc->block_topk);+ jit.make("QSA_ADDRESS_MODE", 0);+ jit.add(qsa::float_constant("QSA_IDX_NORM_EPS", desc->epsilon));+ jit.add(qsa::float_constant("QSA_IDX_SCALE", ov::op::internal::PagedQSAIndexer::effective_scale(desc->get_config())));+ return jit;+}++constexpr size_t max_slm_bytes = 64 * 1024;+constexpr size_t score_wg_size = 16; // subgroups per query tile in the systolic score kernel+constexpr size_t score_partition_blocks = 32;++bool is_decode_shape(const kernel_impl_params& params) {+ const auto& q_layout = params.get_input_layout(QSAIn::INDEX_QUERY);+ const auto& past_lens_layout = params.get_input_layout(QSAIn::PAST_LENS);+ if (q_layout.is_dynamic() || past_lens_layout.is_dynamic()) {+ return false;+ }+ const auto tokens = q_layout.get_shape()[0];+ const auto seqs = past_lens_layout.get_shape()[0];+ return seqs > 0 && tokens == seqs;+}++bool may_decode(const kernel_impl_params& params) {+ return params.is_dynamic() || is_decode_shape(params);+}++bool may_prefill(const kernel_impl_params& params) {+ return params.is_dynamic() || !is_decode_shape(params);+}++/// Whether the systolic qsa_indexer_score_dpas kernel can be used (a property of the descriptor and the device).+bool can_use_dpas_score(const paged_qsa_indexer& desc, size_t page_size, size_t h_iq, const cldnn::device_info& info) {+ if (!qsa::xmx_allowed(info)) {+ return false;+ }+ if (desc.indexer_head_dim % qsa::dpas_k_step != 0 || desc.indexer_head_dim * sizeof(ov::float16) < 64) {+ return false;+ }+ const auto summaries_per_page = page_size / desc.key_block_size;+ if (summaries_per_page == 0 || (summaries_per_page % 8 != 0 && 8 % summaries_per_page != 0)) {+ return false;+ }+ const auto staged_bytes = h_iq * (desc.indexer_head_dim / qsa::dpas_k_step) * qsa::dpas_k_step * qsa::dpas_query_tile * sizeof(ov::float16);+ return staged_bytes <= max_slm_bytes;+}++bool use_dpas_score(const kernel_impl_params& params) {+ const auto desc = params.typed_desc<paged_qsa_indexer>();+ const auto h_iq = index_heads(params.get_input_layout(QSAIn::INDEX_QUERY), desc->indexer_head_dim);+ return can_use_dpas_score(*desc, page_size_of(params), h_iq, params.get_device_info());+}++/// Row pitch the scorer / finalizer agree on when the pool holds the most blocks it can ever list.+size_t pool_pitch(const kernel_impl_params& params, const paged_qsa_indexer& desc) {+ const auto& kcache_shape = params.get_input_layout(QSAIn::INDEX_KEY_CACHE).get_shape();+ return qsa::score_pitch(kcache_shape[0] * page_size_of(params) / desc.key_block_size);+}++/// f32 element capacity of BLOCK_SCORES. Only the systolic prefill scorer writes one row per token; every other path+/// is row-chunked under the score budget. Static shapes only, so allocation and per-call planning agree.+size_t score_scratch_elems(const kernel_impl_params& params, const paged_qsa_indexer& desc) {+ const auto tokens = std::max<size_t>(1, params.get_input_layout(QSAIn::INDEX_QUERY).get_shape()[0]);+ const auto pitch = pool_pitch(params, desc);+ if (!is_decode_shape(params) && use_dpas_score(params)) {+ return tokens * pitch;+ }+ const auto budget_rows = std::max<size_t>(1, qsa::score_budget_bytes() / (pitch * sizeof(float)));+ return std::min(tokens, budget_rows) * pitch;+}++class PagedPrepareGenerator : public qsa::QsaGenerator {+public:+ PagedPrepareGenerator() : QsaGenerator("qsa_indexer_prepare_paged", "qsa_indexer_prepare_paged") {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ return make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<paged_qsa_indexer>(), params);+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ for (auto idx : {QSAIn::INDEX_QUERY,+ QSAIn::RAW_INDEX_KEYS,+ QSAIn::Q_NORM_WEIGHT,+ QSAIn::K_NORM_WEIGHT,+ QSAIn::ROPE_COS,+ QSAIn::ROPE_SIN,+ QSAIn::PAST_LENS,+ QSAIn::SUBSEQUENCE_BEGINS,+ QSAIn::BLOCK_INDICES,+ QSAIn::BLOCK_INDICES_BEGINS,+ QSAIn::INDEX_KEY_CACHE,+ QSAIn::BLOCK_INDEX_KEYS_CACHE,+ QSAIn::INDEX_BLOCK_ROPE_CACHE}) {+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)});+ }+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedQSAIndexerInternalBufIdx::INDEXER_Q});+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0});+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1});+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ const size_t wg_count = std::max<size_t>(1, rtp->prepare_wg_count);+ auto& wgs = kd.params.workGroups;+ wgs.global = {sg, rtp->index_query_heads + 1, wg_count};+ wgs.local = {sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->prepare_wg_count);+ qsa::push_u32(kd, rtp->num_seqs);+ }};+ }+};++class PagedScoreDpasGenerator : public qsa::QsaGenerator {+public:+ PagedScoreDpasGenerator() : QsaGenerator("qsa_indexer_score_dpas", "qsa_indexer_score_dpas", true) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<paged_qsa_indexer>(), params);+ jit.make("QSA_SCORE_WG", score_wg_size);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedQSAIndexerInternalBufIdx::INDEXER_Q});+ for (auto idx : {QSAIn::BLOCK_INDEX_KEYS_CACHE, QSAIn::PAST_LENS, QSAIn::SUBSEQUENCE_BEGINS, QSAIn::BLOCK_INDICES, QSAIn::BLOCK_INDICES_BEGINS}) {+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)});+ }+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedQSAIndexerInternalBufIdx::BLOCK_SCORES});+ for (uint32_t i = 0; i < 3; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ auto& wgs = kd.params.workGroups;+ // One work-group owns one 16-query tile.+ wgs.global = {std::max<size_t>(1, rtp->score_tile_count) * score_wg_size * sg, 1, 1};+ wgs.local = {score_wg_size * sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->score_tile_count);+ qsa::push_u32(kd, rtp->num_seqs);+ qsa::push_u32(kd, rtp->pitch);+ }};+ }+};++class PagedTopkGenerator : public qsa::QsaGenerator {+public:+ explicit PagedTopkGenerator(bool decode = false)+ : QsaGenerator("qsa_indexer_topk", decode ? "qsa_indexer_topk_decode" : "qsa_indexer_topk"),+ m_decode(decode) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<paged_qsa_indexer>(), params);+ jit.make("QSA_TOPK_WG", qsa::topk_max_subgroups);+ if (m_decode) {+ jit.make("QSA_TOPK_FIXED_WG", 1);+ }+ jit.make("QSA_TOPK_REG_KEYS", qsa::topk_reg_keys);+ jit.make("QSA_TOPK_THRESHOLDS", qsa::topk_thresholds);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedQSAIndexerInternalBufIdx::BLOCK_SCORES});+ args.push_back({ArgumentDescriptor::Types::INPUT, QSAIn::PAST_LENS});+ args.push_back({ArgumentDescriptor::Types::INPUT, QSAIn::SUBSEQUENCE_BEGINS});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 1});+ for (uint32_t i = 0; i < 5; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[decode = m_decode](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ // A decode row is one latency-bound work-group: use all subgroups.+ const auto wg = (decode ? qsa::topk_max_subgroups : qsa::topk_wg_subgroups(rtp->pitch)) * sg;+ auto& wgs = kd.params.workGroups;+ // One work-group cooperatively finalizes one token's row.+ wgs.global = {std::max<size_t>(1, rtp->chunk_row_end - rtp->chunk_row_begin) * wg, 1, 1};+ wgs.local = {wg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->num_tokens);+ qsa::push_u32(kd, rtp->num_seqs);+ qsa::push_u32(kd, rtp->pitch);+ qsa::push_u32(kd, rtp->chunk_row_begin);+ qsa::push_u32(kd, rtp->chunk_row_end);+ }};+ }++private:+ bool m_decode;+};++class PagedScorePartitionGenerator : public qsa::QsaGenerator {+public:+ PagedScorePartitionGenerator() : QsaGenerator("qsa_indexer_score_partition", "qsa_indexer_score_partition") {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<paged_qsa_indexer>(), params);+ jit.make("QSA_SCORE_PARTITION_BLOCKS", score_partition_blocks);+ // Rows whose blocks are all selected are never read by qsa_indexer_topk.+ jit.make("QSA_DENSE_SCORE_BYPASS", 1);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedQSAIndexerInternalBufIdx::INDEXER_Q});+ for (auto idx : {QSAIn::BLOCK_INDEX_KEYS_CACHE, QSAIn::PAST_LENS, QSAIn::SUBSEQUENCE_BEGINS, QSAIn::BLOCK_INDICES, QSAIn::BLOCK_INDICES_BEGINS}) {+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)});+ }+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedQSAIndexerInternalBufIdx::BLOCK_SCORES});+ for (uint32_t i = 0; i < 6; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ auto& wgs = kd.params.workGroups;+ wgs.global = {std::max<size_t>(1, rtp->chunk_row_end - rtp->chunk_row_begin) * sg, 1, rtp->num_partitions};+ wgs.local = {sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->num_tokens);+ qsa::push_u32(kd, rtp->num_seqs);+ qsa::push_u32(kd, rtp->pitch);+ qsa::push_u32(kd, rtp->num_partitions);+ qsa::push_u32(kd, rtp->chunk_row_begin);+ qsa::push_u32(kd, rtp->chunk_row_end);+ }};+ }+};++class PagedQSAIndexerImpl : public PrimitiveImplOCL {+public:+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::PagedQSAIndexerImpl)++ Stage::Ptr prepare = make_stage<PagedPrepareGenerator>();+ Stage::Ptr score_dpas = make_stage<PagedScoreDpasGenerator>();+ Stage::Ptr score_partition = make_stage<PagedScorePartitionGenerator>();+ Stage::Ptr topk = make_stage<PagedTopkGenerator>();+ Stage::Ptr topk_decode = make_stage<PagedTopkGenerator>(true);++ PagedQSAIndexerImpl() : PrimitiveImplOCL(PagedQSAIndexerImplementationManager::get_type_info_static()) {+ m_rt_params = std::make_unique<PagedQSAIndexerRuntimeParams>();+ }++ PagedQSAIndexerRuntimeParams& rt() {+ if (m_rt_params == nullptr) {+ m_rt_params = std::make_unique<PagedQSAIndexerRuntimeParams>();+ }+ return *static_cast<PagedQSAIndexerRuntimeParams*>(m_rt_params.get());+ }++ // Decode: prepare -> [score_partition -> topk_decode] per row chunk. Prefill/mixed: score_dpas -> topk when the+ // systolic scorer is available, otherwise the same row-chunked partition scorer with the prefill top-k.+ explicit PagedQSAIndexerImpl(const RuntimeParams& params) : PagedQSAIndexerImpl() {+ const bool xmx = use_dpas_score(params);+ add_stage(prepare, params);+ if (may_decode(params) || (may_prefill(params) && !xmx)) {+ add_stage(score_partition, params);+ }+ if (may_decode(params)) {+ add_stage(topk_decode, params);+ }+ if (may_prefill(params)) {+ if (xmx) {+ add_stage(score_dpas, params);+ }+ add_stage(topk, params);+ }+ }++ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {+ return make_deep_copy<PagedQSAIndexerImpl>(this);+ }++ [[nodiscard]] bool requires_update(primitive_inst& /*inst*/, const kernel_impl_params& /*impl_params*/) const override {+ return true;+ }++ [[nodiscard]] std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& params) const override {+ if (params.is_dynamic()) {+ return {};+ }+ const auto desc = params.typed_desc<paged_qsa_indexer>();+ const auto tokens = std::max<size_t>(1, params.get_input_layout(QSAIn::INDEX_QUERY).get_shape()[0]);+ const auto h_iq = index_heads(params.get_input_layout(QSAIn::INDEX_QUERY), desc->indexer_head_dim);++ std::vector<BufferDescriptor> bufs;+ bufs.emplace_back(tokens * h_iq * desc->indexer_head_dim, ov::element::f16); // INDEXER_Q+ bufs.emplace_back(score_scratch_elems(params, *desc), ov::element::f32); // BLOCK_SCORES+ return bufs;+ }++ event::ptr execute(const std::vector<event::ptr>& events, primitive_inst& instance) override {+ kernel_dump_info.clear_entries();+ update_rt_params(instance);++ const auto& params = *instance.get_impl_params();+ auto* rtp = &rt();+ auto last = execute_stage(events, instance, prepare);+ const bool decode = is_decode_shape(params);+ if (!decode && use_dpas_score(params)) {+ rtp->chunk_row_begin = 0;+ rtp->chunk_row_end = rtp->num_tokens;+ auto scored = execute_stage({last}, instance, score_dpas);+ return execute_stage({scored}, instance, topk);+ }+ // Chunks reuse one bounded BLOCK_SCORES buffer, so they run strictly in sequence; the stages are+ // re-dispatched per chunk, hence the explicit refresh.+ Stage& finalizer = decode ? *topk_decode : *topk;+ for (size_t begin = 0; begin < rtp->num_tokens; begin += rtp->chunk_rows) {+ rtp->chunk_row_begin = begin;+ rtp->chunk_row_end = std::min(rtp->num_tokens, begin + rtp->chunk_rows);+ qsa::force_stage_refresh(*score_partition);+ qsa::force_stage_refresh(finalizer);+ auto scored = execute_stage({last}, instance, score_partition);+ last = execute_stage({scored}, instance, finalizer);+ }+ return last;+ }++ void update_rt_params(const primitive_inst& instance) override {+ update_stages_flags(instance);+ qsa::force_stages_refresh(*this);+ auto* rtp = &rt();++ const auto& params = *instance.get_impl_params();+ const auto desc = params.typed_desc<paged_qsa_indexer>();++ const auto& q_layout = params.get_input_layout(QSAIn::INDEX_QUERY);+ const size_t num_seqs = params.get_input_layout(QSAIn::PAST_LENS).get_shape()[0];+ rtp->num_seqs = num_seqs;+ rtp->num_tokens = q_layout.get_shape()[0];+ rtp->index_query_heads = index_heads(q_layout, desc->indexer_head_dim);++ // Sequence i touches at most ceil(q_i / r) + 1 blocks, so all sequences together at most+ // tokens / r + 2 * num_seqs; and at most tokens / 16 + num_seqs score tiles.+ const auto r = desc->key_block_size;+ rtp->prepare_wg_count = rtp->num_tokens / r + 2 * num_seqs;+ rtp->score_tile_count = rtp->num_tokens / qsa::dpas_query_tile + num_seqs;++ // No sequence can span more blocks than the page table lists.+ const size_t used_pages = params.get_input_layout(QSAIn::BLOCK_INDICES).get_shape()[0];+ const size_t max_blocks = std::max<size_t>(1, used_pages * page_size_of(params) / r);+ rtp->pitch = qsa::score_pitch(max_blocks);+ rtp->num_partitions = std::max<size_t>(1, (max_blocks + score_partition_blocks - 1) / score_partition_blocks);+ // The runtime pitch never exceeds the pool-wide pitch the buffer was sized for, so a chunk can hold more rows+ // than the static budget alone would allow.+ rtp->chunk_rows = std::max<size_t>(1, std::min(rtp->num_tokens, score_scratch_elems(params, *desc) / rtp->pitch));+ rtp->chunk_row_begin = 0;+ rtp->chunk_row_end = rtp->num_tokens;+ }+};++} // namespace++bool PagedQSAIndexerImplementationManager::validate_impl(const cldnn::program_node& node) const {+ assert(node.is_type<cldnn::paged_qsa_indexer>());++ if (node.has_fused_primitives()) {+ return false;+ }++ const auto& info = node.get_program().get_engine().get_device_info();+ if (!qsa::subgroups_available(info)) {+ return false;+ }++ const auto desc = node.as<cldnn::paged_qsa_indexer>().get_primitive();+ std::string reason;+ if (!ov::intel_gpu::op::PagedQSAIndexer::validate_config(desc->get_config(), reason)) {+ return false;+ }++ // Single selection head; the head dim must tile the subgroup and keep its rows 16-byte aligned.+ if (desc->num_selection_heads != 1 || desc->indexer_head_dim % 16 != 0 || desc->indexer_head_dim % qsa::subgroup_size(info) != 0) {+ return false;+ }+ const auto& index_query_ps = node.get_input_layout(QSAIn::INDEX_QUERY).get_partial_shape();+ const auto& raw_index_keys_ps = node.get_input_layout(QSAIn::RAW_INDEX_KEYS).get_partial_shape();+ if (index_query_ps.rank().is_dynamic() || index_query_ps.size() < 2 || index_query_ps[1].is_dynamic()) {+ return false;+ }+ if (raw_index_keys_ps.rank().is_dynamic() || raw_index_keys_ps.size() < 2 || raw_index_keys_ps[1].is_dynamic() ||+ static_cast<size_t>(raw_index_keys_ps[1].get_length()) != desc->indexer_head_dim) {+ return false;+ }++ return node.get_input_layout(QSAIn::INDEX_QUERY).data_type == ov::element::f16 &&+ node.get_input_layout(QSAIn::RAW_INDEX_KEYS).data_type == ov::element::f16;+}++std::unique_ptr<cldnn::primitive_impl> PagedQSAIndexerImplementationManager::create_impl(const cldnn::program_node& node,+ const cldnn::kernel_impl_params& params) const {+ OPENVINO_ASSERT(node.is_type<cldnn::paged_qsa_indexer>());+ return std::make_unique<PagedQSAIndexerImpl>(params);+}++} // namespace ov::intel_gpu::ocl++BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::PagedQSAIndexerImpl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/paged_qsa_indexer.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/paged_qsa_indexer.hppnew file mode 100644index 00000000000..d3a1d5a0a56--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/paged_qsa_indexer.hpp@@ -0,0 +1,60 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <memory>+#include <utility>+#include <vector>++#include "common_utils/kernel_generator_base.hpp"+#include "intel_gpu/runtime/layout.hpp"+#include "paged_qsa_indexer_inst.h"+#include "program_node.h"+#include "registry/implementation_manager.hpp"++namespace ov::intel_gpu::ocl {++/// Internal (scratch) buffers of the OpenCL PagedQSAIndexer implementation.+struct PagedQSAIndexerInternalBufIdx {+ static constexpr size_t INDEXER_Q = 0; ///< f16 [num_tokens, H_iq, D_idx]+ static constexpr size_t BLOCK_SCORES = 1; ///< f32 [rows, pitch]; rows bounded by the score budget unless the systolic scorer runs++ static constexpr size_t COUNT = 2;+};++/// All sizes are upper bounds derived from shapes: past_lens/subsequence_begins live in GPU memory and are resolved by+/// the kernels, never read by the host.+struct PagedQSAIndexerRuntimeParams : public ImplRuntimeParams {+ size_t num_tokens = 0;+ size_t num_seqs = 0;+ size_t pitch = 8; ///< row pitch of BLOCK_SCORES (multiple of 8)+ size_t prepare_wg_count = 0;+ size_t score_tile_count = 0;+ size_t num_partitions = 1;+ size_t chunk_rows = 1;+ size_t chunk_row_begin = 0;+ size_t chunk_row_end = 0;+ size_t index_query_heads = 0;+};++/// @brief OpenCL implementation of the PagedQSAIndexer primitive (Q1 prepare + Q2 score/top-k).+struct PagedQSAIndexerImplementationManager : public cldnn::ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("ocl::paged_qsa_indexer")+ explicit PagedQSAIndexerImplementationManager(cldnn::shape_types shape_type, cldnn::ValidateFunc vf = nullptr)+ : ImplementationManager(cldnn::impl_types::ocl, shape_type, std::move(vf)) {}++ [[nodiscard]] std::unique_ptr<cldnn::primitive_impl> create_impl(const cldnn::program_node& node, const cldnn::kernel_impl_params& params) const override;++ [[nodiscard]] cldnn::in_out_fmts_t query_formats(const cldnn::program_node& node) const override {+ std::vector<cldnn::format::type> in_fmts(node.get_dependencies().size(), cldnn::format::bfyx);+ std::vector<cldnn::format::type> out_fmts(node.get_outputs_count(), cldnn::format::bfyx);+ return {in_fmts, out_fmts};+ }++ [[nodiscard]] bool validate_impl(const cldnn::program_node& node) const override;+};++} // namespace ov::intel_gpu::ocldiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/qsa_indexer.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/qsa_indexer.cppnew file mode 100644index 00000000000..b43d60ae349--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/qsa_indexer.cpp@@ -0,0 +1,506 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "qsa_indexer.hpp"++#include <algorithm>+#include <array>+#include <cassert>+#include <memory>+#include <string>+#include <utility>+#include <vector>++#include "../primitive_ocl_base.hpp"+#include "../qsa_host_common.hpp"+#include "common_utils/jitter.hpp"+#include "intel_gpu/graph/kernel_impl_params.hpp"+#include "intel_gpu/primitives/qsa_indexer.hpp"+#include "primitive_inst.h"++namespace ov::intel_gpu::ocl {++using namespace cldnn;+using QSAIn = ov::intel_gpu::op::QSAIndexer::InputIdx;+using QSAOut = ov::intel_gpu::op::QSAIndexer::OutputIdx;++namespace {++QSAIndexerRuntimeParams* rt_of(ImplRuntimeParams* rt) {+ auto* p = static_cast<QSAIndexerRuntimeParams*>(rt);+ OPENVINO_ASSERT(p != nullptr, "[GPU][OCL] qsa_indexer runtime params are not initialized");+ return p;+}++/// H_iq / H_ik, derived from the 4D [B, L, H, D_idx] index_query/raw_index_keys layouts (B/L may be dynamic).+size_t index_heads_4d(const layout& l) {+ const auto& ps = l.get_partial_shape();+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() >= 3 && ps[2].is_static(),+ "[GPU][OCL] qsa_indexer: expected a rank-4 [B, L, H, D_idx] input with a static head count");+ return static_cast<size_t>(ps[2].get_length());+}++JitConstants make_jit(JitConstants jit, const std::shared_ptr<const qsa_indexer>& desc, const RuntimeParams& params) {+ const auto h_iq = index_heads_4d(params.get_input_layout(QSAIn::INDEX_QUERY));+ jit.make("QSA_IDX_QUERY_HEADS", h_iq);+ jit.make("QSA_IDX_HEAD_DIM", desc->indexer_head_dim);+ jit.make("QSA_IDX_ROTARY_DIM", desc->indexer_rotary_dim);+ jit.make("QSA_COMPRESS_RATIO", desc->key_block_size);+ jit.make("QSA_BLOCK_TOPK", desc->block_topk);+ jit.make("QSA_ADDRESS_MODE", 1);+ jit.add(qsa::float_constant("QSA_IDX_NORM_EPS", desc->epsilon));+ jit.add(qsa::float_constant("QSA_IDX_SCALE", ov::intel_gpu::op::QSAIndexer::effective_scale(desc->get_config())));+ return jit;+}++constexpr size_t max_slm_bytes = 64 * 1024;+constexpr size_t score_wg_size = 16;+constexpr size_t score_partition_blocks = 32;++bool is_decode_shape(const kernel_impl_params& params) {+ const auto& index_query_layout = params.get_input_layout(QSAIn::INDEX_QUERY);+ if (index_query_layout.is_dynamic()) {+ return false;+ }+ const auto& shape = index_query_layout.get_shape();+ OPENVINO_ASSERT(shape.size() >= 2, "[GPU][OCL] qsa_indexer: expected a rank-4 [B, L, H, D_idx] input");+ return shape[1] == 1;+}++bool may_decode(const kernel_impl_params& params) {+ return params.is_dynamic() || is_decode_shape(params);+}++bool may_prefill(const kernel_impl_params& params) {+ return params.is_dynamic() || !is_decode_shape(params);+}++/// Dense addressing has no page table, so unlike the paged gate there is no page/tile alignment constraint.+bool can_use_dpas_score(const qsa_indexer& desc, size_t h_iq, const cldnn::device_info& info) {+ if (!qsa::xmx_allowed(info)) {+ return false;+ }+ if (desc.indexer_head_dim % qsa::dpas_k_step != 0 || desc.indexer_head_dim * sizeof(ov::float16) < 64) {+ return false;+ }+ const auto staged_bytes = h_iq * (desc.indexer_head_dim / qsa::dpas_k_step) * qsa::dpas_k_step * qsa::dpas_query_tile * sizeof(ov::float16);+ return staged_bytes <= max_slm_bytes;+}++bool use_dpas_score(const kernel_impl_params& params) {+ const auto desc = params.typed_desc<qsa_indexer>();+ const auto h_iq = index_heads_4d(params.get_input_layout(QSAIn::INDEX_QUERY));+ return can_use_dpas_score(*desc, h_iq, params.get_device_info());+}++size_t score_scratch_elems(const kernel_impl_params& params, const qsa_indexer& /*desc*/) {+ const auto& index_query_shape = params.get_input_layout(QSAIn::INDEX_QUERY).get_shape();+ const auto tokens = std::max<size_t>(1, index_query_shape[0] * index_query_shape[1]);+ const auto& summary_shape = params.get_input_layout(QSAIn::BLOCK_INDEX_KEYS_CACHE).get_shape();+ const auto pitch = qsa::score_pitch(summary_shape[2]);+ if (!is_decode_shape(params) && use_dpas_score(params)) {+ return tokens * pitch;+ }+ const auto budget_rows = std::max<size_t>(1, qsa::score_budget_bytes() / (pitch * sizeof(float)));+ return std::min(tokens, budget_rows) * pitch;+}++class DensePrepareGenerator : public qsa::QsaGenerator {+public:+ DensePrepareGenerator() : QsaGenerator("qsa_indexer_prepare_dense", "qsa_indexer_prepare_dense") {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ return make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<qsa_indexer>(), params);+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ for (auto idx : {QSAIn::INDEX_QUERY,+ QSAIn::RAW_INDEX_KEYS,+ QSAIn::Q_NORM_WEIGHT,+ QSAIn::K_NORM_WEIGHT,+ QSAIn::ROPE_COS,+ QSAIn::ROPE_SIN,+ QSAIn::KEY_LENGTH,+ QSAIn::PAST_INCOMPLETE_RAW_K,+ QSAIn::PAST_INCOMPLETE_ROPE}) {+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)});+ }+ args.push_back({ArgumentDescriptor::Types::OUTPUT, QSAOut::BLOCK_INDEX_KEYS_CACHE});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, QSAOut::PAST_INCOMPLETE_RAW_K});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, QSAOut::PAST_INCOMPLETE_ROPE});+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, QSAIndexerInternalBufIdx::INDEXER_Q});+ for (uint32_t i = 0; i < 4; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ const size_t wg_count = std::max<size_t>(1, rtp->prepare_wg_count);+ auto& wgs = kd.params.workGroups;+ wgs.global = {sg, rtp->index_query_heads + 1, wg_count};+ wgs.local = {sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->prepare_wg_count);+ qsa::push_u32(kd, rtp->prepare_blocks_per_row);+ qsa::push_u32(kd, rtp->seq_len);+ qsa::push_u32(kd, rtp->summary_stride);+ }};+ }+};++class DenseScoreDpasGenerator : public qsa::QsaGenerator {+public:+ DenseScoreDpasGenerator() : QsaGenerator("qsa_indexer_score_dpas", "qsa_indexer_score_dpas", true) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<qsa_indexer>(), params);+ jit.make("QSA_SCORE_WG", score_wg_size);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, QSAIndexerInternalBufIdx::INDEXER_Q});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, QSAOut::BLOCK_INDEX_KEYS_CACHE});+ args.push_back({ArgumentDescriptor::Types::INPUT, QSAIn::KEY_LENGTH});+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, QSAIndexerInternalBufIdx::BLOCK_SCORES});+ for (uint32_t i = 0; i < 4; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ auto& wgs = kd.params.workGroups;+ wgs.global = {std::max<size_t>(1, rtp->score_tile_count) * score_wg_size * sg, 1, 1};+ wgs.local = {score_wg_size * sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->score_tile_count);+ qsa::push_u32(kd, rtp->seq_len);+ qsa::push_u32(kd, rtp->summary_stride);+ qsa::push_u32(kd, rtp->pitch);+ }};+ }+};++class DenseTopkGenerator : public qsa::QsaGenerator {+public:+ explicit DenseTopkGenerator(bool decode = false)+ : QsaGenerator("qsa_indexer_topk", decode ? "qsa_indexer_topk_decode" : "qsa_indexer_topk"),+ m_decode(decode) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<qsa_indexer>(), params);+ jit.make("QSA_TOPK_WG", qsa::topk_max_subgroups);+ if (m_decode) {+ jit.make("QSA_TOPK_FIXED_WG", 1);+ }+ jit.make("QSA_TOPK_REG_KEYS", qsa::topk_reg_keys);+ jit.make("QSA_TOPK_THRESHOLDS", qsa::topk_thresholds);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, QSAIndexerInternalBufIdx::BLOCK_SCORES});+ args.push_back({ArgumentDescriptor::Types::INPUT, QSAIn::KEY_LENGTH});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 1});+ for (uint32_t i = 0; i < 5; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[decode = m_decode](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ // A decode row is one latency-bound work-group: use all subgroups.+ const auto wg = (decode ? qsa::topk_max_subgroups : qsa::topk_wg_subgroups(rtp->pitch)) * sg;+ auto& wgs = kd.params.workGroups;+ wgs.global = {std::max<size_t>(1, rtp->chunk_row_end - rtp->chunk_row_begin) * wg, 1, 1};+ wgs.local = {wg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->num_tokens);+ qsa::push_u32(kd, rtp->seq_len);+ qsa::push_u32(kd, rtp->pitch);+ qsa::push_u32(kd, rtp->chunk_row_begin);+ qsa::push_u32(kd, rtp->chunk_row_end);+ }};+ }++private:+ bool m_decode;+};++class DenseScorePartitionGenerator : public qsa::QsaGenerator {+public:+ DenseScorePartitionGenerator() : QsaGenerator("qsa_indexer_score_partition", "qsa_indexer_score_partition") {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_jit(QsaGenerator::get_jit_constants(params), params.typed_desc<qsa_indexer>(), params);+ jit.make("QSA_SCORE_PARTITION_BLOCKS", score_partition_blocks);+ jit.make("QSA_DENSE_SCORE_BYPASS", 1);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, QSAIndexerInternalBufIdx::INDEXER_Q});+ args.push_back({ArgumentDescriptor::Types::OUTPUT, QSAOut::BLOCK_INDEX_KEYS_CACHE});+ args.push_back({ArgumentDescriptor::Types::INPUT, QSAIn::KEY_LENGTH});+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, QSAIndexerInternalBufIdx::BLOCK_SCORES});+ for (uint32_t i = 0; i < 7; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ auto* rtp = rt_of(rt);+ const auto sg = qsa::subgroup_size(params.get_device_info());+ auto& wgs = kd.params.workGroups;+ wgs.global = {std::max<size_t>(1, rtp->chunk_row_end - rtp->chunk_row_begin) * sg, 1, rtp->num_partitions};+ wgs.local = {sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, rtp->num_tokens);+ qsa::push_u32(kd, rtp->seq_len);+ qsa::push_u32(kd, rtp->summary_stride);+ qsa::push_u32(kd, rtp->pitch);+ qsa::push_u32(kd, rtp->num_partitions);+ qsa::push_u32(kd, rtp->chunk_row_begin);+ qsa::push_u32(kd, rtp->chunk_row_end);+ }};+ }+};++class QSAIndexerImpl : public PrimitiveImplOCL {+public:+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::QSAIndexerImpl)++ Stage::Ptr prepare = make_stage<DensePrepareGenerator>();+ Stage::Ptr score_dpas = make_stage<DenseScoreDpasGenerator>();+ Stage::Ptr score_partition = make_stage<DenseScorePartitionGenerator>();+ Stage::Ptr topk = make_stage<DenseTopkGenerator>();+ Stage::Ptr topk_decode = make_stage<DenseTopkGenerator>(true);++ QSAIndexerImpl() : PrimitiveImplOCL(QSAIndexerImplementationManager::get_type_info_static()) {+ m_rt_params = std::make_unique<QSAIndexerRuntimeParams>();+ }++ QSAIndexerRuntimeParams& rt() {+ if (m_rt_params == nullptr) {+ m_rt_params = std::make_unique<QSAIndexerRuntimeParams>();+ }+ return *static_cast<QSAIndexerRuntimeParams*>(m_rt_params.get());+ }++ explicit QSAIndexerImpl(const RuntimeParams& params) : QSAIndexerImpl() {+ const bool xmx = use_dpas_score(params);+ add_stage(prepare, params);+ if (may_decode(params) || (may_prefill(params) && !xmx)) {+ add_stage(score_partition, params);+ }+ if (may_decode(params)) {+ add_stage(topk_decode, params);+ }+ if (may_prefill(params)) {+ if (xmx) {+ add_stage(score_dpas, params);+ }+ add_stage(topk, params);+ }+ }++ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {+ return make_deep_copy<QSAIndexerImpl>(this);+ }++ [[nodiscard]] bool requires_update(primitive_inst& /*inst*/, const kernel_impl_params& /*impl_params*/) const override {+ return true;+ }++ [[nodiscard]] std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& params) const override {+ if (params.is_dynamic()) {+ return {};+ }+ const auto desc = params.typed_desc<qsa_indexer>();+ const auto& index_query_shape = params.get_input_layout(QSAIn::INDEX_QUERY).get_shape();+ const auto batch = std::max<size_t>(1, index_query_shape[0]);+ const auto seq_len = std::max<size_t>(1, index_query_shape[1]);+ const auto h_iq = index_heads_4d(params.get_input_layout(QSAIn::INDEX_QUERY));++ std::vector<BufferDescriptor> bufs;+ bufs.emplace_back(batch * seq_len * h_iq * desc->indexer_head_dim, ov::element::f16);+ bufs.emplace_back(score_scratch_elems(params, *desc), ov::element::f32);+ return bufs;+ }++ event::ptr execute(const std::vector<event::ptr>& events, primitive_inst& instance) override {+ kernel_dump_info.clear_entries();+ update_rt_params(instance);++ const auto& params = *instance.get_impl_params();+ auto* rtp = &rt();+ auto last = execute_stage(copy_state(events, instance), instance, prepare);+ const bool decode = is_decode_shape(params);+ if (!decode && use_dpas_score(params)) {+ rtp->chunk_row_begin = 0;+ rtp->chunk_row_end = rtp->num_tokens;+ auto scored = execute_stage({last}, instance, score_dpas);+ return execute_stage({scored}, instance, topk);+ }+ Stage& finalizer = decode ? *topk_decode : *topk;+ for (size_t begin = 0; begin < rtp->num_tokens; begin += rtp->chunk_rows) {+ rtp->chunk_row_begin = begin;+ rtp->chunk_row_end = std::min(rtp->num_tokens, begin + rtp->chunk_rows);+ qsa::force_stage_refresh(*score_partition);+ qsa::force_stage_refresh(finalizer);+ auto scored = execute_stage({last}, instance, score_partition);+ last = execute_stage({scored}, instance, finalizer);+ }+ return last;+ }++ void update_rt_params(const primitive_inst& instance) override {+ update_stages_flags(instance);+ qsa::force_stages_refresh(*this);+ auto* rtp = &rt();++ const auto& params = *instance.get_impl_params();+ const auto desc = params.typed_desc<qsa_indexer>();++ const auto& index_query_layout = params.get_input_layout(QSAIn::INDEX_QUERY);+ const auto& index_query_shape = index_query_layout.get_shape();+ const size_t batch = index_query_shape[0];+ const size_t seq_len = index_query_shape[1];++ rtp->batch = batch;+ rtp->seq_len = seq_len;+ rtp->num_tokens = batch * seq_len;+ rtp->index_query_heads = index_heads_4d(index_query_layout);+ rtp->summary_stride = params.get_input_layout(QSAIn::BLOCK_INDEX_KEYS_CACHE).get_shape()[2];++ // key_length stays in GPU memory: every size below is a bound from shapes only and the kernels derive the real+ // work (and drop the excess) from key_length.+ const auto r = desc->key_block_size;+ rtp->prepare_blocks_per_row = seq_len == 0 ? 0 : (seq_len - 1) / r + 2;+ rtp->prepare_wg_count = batch * rtp->prepare_blocks_per_row;+ const size_t max_blocks = std::max<size_t>(1, rtp->summary_stride);+ rtp->pitch = qsa::score_pitch(max_blocks);+ rtp->num_partitions = std::max<size_t>(1, (max_blocks + score_partition_blocks - 1) / score_partition_blocks);+ rtp->chunk_rows = std::max<size_t>(1, std::min(rtp->num_tokens, score_scratch_elems(params, *desc) / rtp->pitch));+ rtp->chunk_row_begin = 0;+ rtp->chunk_row_end = rtp->num_tokens;+ rtp->score_tile_count = batch * ((seq_len + qsa::dpas_query_tile - 1) / qsa::dpas_query_tile);+ }++private:+ /// Functional state: every state output starts as a copy of its input, then prepare overwrites the entries this call+ /// produces. Inputs and outputs are distinct buffers, so prepare reads the old incomplete block without a hazard.+ std::vector<event::ptr> copy_state(const std::vector<event::ptr>& events, primitive_inst& instance) {+ auto& stream = instance.get_network().get_stream();+ if (stream.get_queue_type() == QueueTypes::out_of_order) {+ stream.wait_for_events(events);+ }+ std::vector<event::ptr> deps = events;+ static constexpr std::array<std::pair<size_t, size_t>, 3> state = {std::pair{QSAIn::BLOCK_INDEX_KEYS_CACHE, QSAOut::BLOCK_INDEX_KEYS_CACHE},+ std::pair{QSAIn::PAST_INCOMPLETE_RAW_K, QSAOut::PAST_INCOMPLETE_RAW_K},+ std::pair{QSAIn::PAST_INCOMPLETE_ROPE, QSAOut::PAST_INCOMPLETE_ROPE}};+ const auto& params = *instance.get_impl_params();+ for (const auto& [in, out] : state) {+ auto src = instance.input_memory_ptr(in);+ auto dst = instance.output_memory_ptr(out);+ const auto bytes = params.get_output_layout(out).bytes_count();+ OPENVINO_ASSERT(!params.get_input_layout(in).data_padding && !params.get_output_layout(out).data_padding,+ "[GPU][OCL] qsa_indexer: padded state buffers are not supported");+ OPENVINO_ASSERT(src->size() >= bytes && dst->size() >= bytes, "[GPU][OCL] qsa_indexer: state buffer is too small");+ const bool aliased = src == dst || (src->buffer_ptr() != nullptr && src->buffer_ptr() == dst->buffer_ptr());+ // An aliased summary is safe (prepare only appends to it); the incomplete-block state is read and rewritten by+ // different work-groups of one dispatch.+ OPENVINO_ASSERT(!aliased || in == QSAIn::BLOCK_INDEX_KEYS_CACHE, "[GPU][OCL] qsa_indexer: incomplete-block state input and output must not alias");+ if (bytes == 0 || aliased) {+ continue;+ }+ deps.push_back(dst->copy_from(stream, *src, 0, 0, bytes, false));+ }+ return deps;+ }+};++} // namespace++bool QSAIndexerImplementationManager::validate_impl(const cldnn::program_node& node) const {+ assert(node.is_type<cldnn::qsa_indexer>());++ if (node.has_fused_primitives()) {+ return false;+ }++ const auto& info = node.get_program().get_engine().get_device_info();+ if (!qsa::subgroups_available(info)) {+ return false;+ }++ const auto desc = node.as<cldnn::qsa_indexer>().get_primitive();+ std::string reason;+ if (!ov::intel_gpu::op::QSAIndexer::validate_config(desc->get_config(), reason)) {+ return false;+ }++ if (desc->num_selection_heads != 1 || desc->indexer_head_dim % 16 != 0 || desc->indexer_head_dim % qsa::subgroup_size(info) != 0) {+ return false;+ }+ const auto& index_query_ps = node.get_input_layout(QSAIn::INDEX_QUERY).get_partial_shape();+ const auto& raw_index_keys_ps = node.get_input_layout(QSAIn::RAW_INDEX_KEYS).get_partial_shape();+ if (index_query_ps.rank().is_dynamic() || index_query_ps.size() != 4 || index_query_ps[2].is_dynamic()) {+ return false;+ }+ if (raw_index_keys_ps.rank().is_dynamic() || raw_index_keys_ps.size() != 4 || raw_index_keys_ps[2].is_dynamic() || raw_index_keys_ps[2].get_length() != 1) {+ return false;+ }++ return node.get_input_layout(QSAIn::INDEX_QUERY).data_type == ov::element::f16 &&+ node.get_input_layout(QSAIn::RAW_INDEX_KEYS).data_type == ov::element::f16;+}++std::unique_ptr<cldnn::primitive_impl> QSAIndexerImplementationManager::create_impl(const cldnn::program_node& node,+ const cldnn::kernel_impl_params& params) const {+ OPENVINO_ASSERT(node.is_type<cldnn::qsa_indexer>());+ return std::make_unique<QSAIndexerImpl>(params);+}++} // namespace ov::intel_gpu::ocl++BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::QSAIndexerImpl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/qsa_indexer.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/qsa_indexer.hppnew file mode 100644index 00000000000..015f2c8a4ab--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer/qsa_indexer.hpp@@ -0,0 +1,61 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <memory>+#include <utility>+#include <vector>++#include "common_utils/kernel_generator_base.hpp"+#include "intel_gpu/runtime/layout.hpp"+#include "program_node.h"+#include "qsa_indexer_inst.h"+#include "registry/implementation_manager.hpp"++namespace ov::intel_gpu::ocl {++struct QSAIndexerInternalBufIdx {+ static constexpr size_t INDEXER_Q = 0; ///< f16 [tokens=B*L, H_iq, D_idx]+ static constexpr size_t BLOCK_SCORES = 1; ///< f32 [rows, pitch]++ static constexpr size_t COUNT = 2;+};++struct QSAIndexerRuntimeParams : public ImplRuntimeParams {+ size_t batch = 0;+ size_t seq_len = 0;+ size_t num_tokens = 0;+ size_t pitch = 8; ///< row pitch of BLOCK_SCORES (multiple of 8)+ size_t prepare_blocks_per_row = 1;+ size_t prepare_wg_count = 0;+ size_t score_tile_count = 0;+ size_t num_partitions = 1;+ size_t chunk_rows = 1;+ size_t chunk_row_begin = 0;+ size_t chunk_row_end = 0;+ size_t index_query_heads = 0;+ size_t summary_stride = 0; ///< block_index_keys_cache entries per batch element, floor(S_cap / r)+};++/// @brief OpenCL implementation of the QSAIndexer (non-paged) primitive: Q1 prepare + Q2 score/top-k with direct dense+/// addressing (no page table).+struct QSAIndexerImplementationManager : public cldnn::ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("ocl::qsa_indexer")+ explicit QSAIndexerImplementationManager(cldnn::shape_types shape_type, cldnn::ValidateFunc vf = nullptr)+ : ImplementationManager(cldnn::impl_types::ocl, shape_type, std::move(vf)) {}++ [[nodiscard]] std::unique_ptr<cldnn::primitive_impl> create_impl(const cldnn::program_node& node, const cldnn::kernel_impl_params& params) const override;++ [[nodiscard]] cldnn::in_out_fmts_t query_formats(const cldnn::program_node& node) const override {+ std::vector<cldnn::format::type> in_fmts(node.get_dependencies().size(), cldnn::format::bfyx);+ std::vector<cldnn::format::type> out_fmts(node.get_outputs_count(), cldnn::format::bfyx);+ return {in_fmts, out_fmts};+ }++ [[nodiscard]] bool validate_impl(const cldnn::program_node& node) const override;+};++} // namespace ov::intel_gpu::ocldiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_prepare_dense.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_prepare_dense.clnew file mode 100644index 00000000000..30e76ce0c56--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_prepare_dense.cl@@ -0,0 +1,129 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q1 - QSAIndexer (non-paged, functional state) prepare.+//+// Same maths as qsa_indexer_prepare_paged.cl with dense addressing: batch IS the sequence axis, the flat token index+// is t = b * seq_len + l, and the staged incomplete block / its first-token rope row live in distinct input and output+// state buffers (the host has already copied every state input into its output).+//+// JIT: QSA_IDX_QUERY_HEADS, QSA_IDX_HEAD_DIM, QSA_IDX_ROTARY_DIM, QSA_COMPRESS_RATIO, QSA_IDX_NORM_EPS, SUBGROUP_SIZE+// Dispatch: gws = [SG, HIQ + 1, num_wg], lws = [SG, 1, 1]++#define QSA_INDEXER_HELPERS+#include "qsa_common.cl"++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(qsa_indexer_prepare_dense)(const __global half* q_idx, // [B, L, Hiq, Di]+ const __global half* k_idx, // [B, L, 1, Di]+ const __global half* q_norm_weight, // [Di]+ const __global half* k_norm_weight, // [Di]+ const __global half* rope_cos, // [B, L, rotary_dim]+ const __global half* rope_sin, // [B, L, rotary_dim]+ const __global int* key_length, // [B]+ const __global half* raw_in, // [B, 1, r-1, Di]+ const __global half* rope_in, // [B, 2*rotary_dim]+ __global half* summary_cache, // [B, 1, floor(S_cap/r), Di]+ __global half* raw_out, // [B, 1, r-1, Di]+ __global half* rope_out, // [B, 2*rotary_dim]+ __global half* indexer_q, // [tokens, Hiq, Di]+ const uint num_wg,+ const uint blocks_per_row,+ const uint seq_len,+ const uint summary_stride) {+ const uint HIQ = QSA_IDX_QUERY_HEADS;+ const uint DI = QSA_IDX_HEAD_DIM;+ const uint ROT = QSA_IDX_ROTARY_DIM;+ const uint R = QSA_COMPRESS_RATIO;++ const uint wg = get_group_id(2);+ const uint role = get_group_id(1);+ const uint lane = get_sub_group_local_id();+ if (wg >= num_wg) {+ return;+ }++ // key_length lives in GPU memory: work-group `slot` of row `batch` takes block past/r + slot.+ const uint batch = wg / blocks_per_row;+ const uint total_len = (uint)key_length[batch];+ const uint n_new = total_len < seq_len ? total_len : seq_len;+ const uint past_len = total_len - n_new;+ const uint qsa_block = past_len / R + wg % blocks_per_row;+ if (qsa_block * R >= total_len) {+ return;+ }++ // Flat token index of logical position `past_len` (the first real row of this call).+ const uint seq_begin = batch * seq_len + (seq_len - n_new);++ const uint block_start = qsa_block * R;+ const uint block_end = block_start + R;+ const bool block_completes = block_end <= total_len;+ const uint lo = block_start > past_len ? block_start : past_len;+ const uint hi = block_end < total_len ? block_end : total_len;++ if (role < HIQ) {+ for (uint p = lo; p < hi; p++) {+ const uint token_idx = seq_begin + (p - past_len);+ float q[QSA_NE];+ FUNC_CALL(qsa_rd_f32)(q_idx + (token_idx * HIQ + role) * DI, q, QSA_NE);+ FUNC_CALL(qsa_rms_norm)(q, q_norm_weight);+#if QSA_IDX_ROTARY_DIM > 0+ FUNC_CALL(qsa_rope)(q, rope_cos + token_idx * ROT, rope_sin + token_idx * ROT, 1);+#endif+ FUNC_CALL(qsa_wr_f32)(indexer_q + (token_idx * HIQ + role) * DI, q, QSA_NE);+ }+ return;+ }++ if (!block_completes) {+ // Stage the keys of the new incomplete block (slot p % r) and its first-token rope row.+ for (uint p = lo; p < hi; p++) {+ const uint token_idx = seq_begin + (p - past_len);+ ushort kh[QSA_NE];+ FUNC_CALL(qsa_rd)((const __global ushort*)(k_idx + token_idx * DI), kh, QSA_NE);+ FUNC_CALL(qsa_wr)((__global ushort*)(raw_out + (batch * (R - 1) + (p - block_start)) * DI), kh, QSA_NE);+#if QSA_IDX_ROTARY_DIM > 0+ if (p == block_start) {+ for (uint i = lane; i < ROT; i += QSA_SG) {+ rope_out[batch * 2 * ROT + 2 * i] = rope_cos[token_idx * ROT + i];+ rope_out[batch * 2 * ROT + 2 * i + 1] = rope_sin[token_idx * ROT + i];+ }+ }+#endif+ }+ return;+ }++ float acc[QSA_NE];+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ acc[j] = 0.0f;+ }+ for (uint s = 0; s < R; s++) {+ const uint p = block_start + s;+ float v[QSA_NE];+ if (p >= past_len) {+ FUNC_CALL(qsa_rd_f32)(k_idx + (seq_begin + (p - past_len)) * DI, v, QSA_NE);+ } else {+ // Staged by an earlier call; slot r-1 is never staged (it completes the block).+ FUNC_CALL(qsa_rd_f32)(raw_in + (batch * (R - 1) + s) * DI, v, QSA_NE);+ }+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ acc[j] += v[j];+ }+ }+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ acc[j] = convert_float(convert_half_rte(acc[j] * (1.0f / (float)R)));+ }+ FUNC_CALL(qsa_rms_norm)(acc, k_norm_weight);+#if QSA_IDX_ROTARY_DIM > 0+ if (block_start >= past_len) {+ const uint first_token = seq_begin + (block_start - past_len);+ FUNC_CALL(qsa_rope)(acc, rope_cos + first_token * ROT, rope_sin + first_token * ROT, 1);+ } else {+ FUNC_CALL(qsa_rope)(acc, rope_in + batch * 2 * ROT, rope_in + batch * 2 * ROT + 1, 2);+ }+#endif+ FUNC_CALL(qsa_wr_f32)(summary_cache + (batch * summary_stride + qsa_block) * DI, acc, QSA_NE);+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_prepare_paged.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_prepare_paged.clnew file mode 100644index 00000000000..566300a4535--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_prepare_paged.cl@@ -0,0 +1,159 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q1 - PagedQSAIndexer prepare.+//+// One subgroup owns one (sequence, QSA block, role) triple. Roles 0..HIQ-1 normalise + rotate one index-query head+// of every new token of the block; role HIQ writes the raw key cache, the per-block rope row and, once the block is+// complete, the block summary (mean pooling -> f16 -> RMSNorm -> RoPE). The roles are independent, so no SLM and no+// barrier is needed: the pooled rows of this call are read from the input, older rows from the raw key cache.+//+// JIT: QSA_IDX_QUERY_HEADS, QSA_IDX_HEAD_DIM, QSA_IDX_ROTARY_DIM, QSA_COMPRESS_RATIO, QSA_PAGE_SIZE,+// QSA_IDX_NORM_EPS, SUBGROUP_SIZE+// Dispatch: gws = [SG, HIQ + 1, num_wg], lws = [SG, 1, 1]++#define QSA_INDEXER_HELPERS+#include "qsa_common.cl"++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(qsa_indexer_prepare_paged)(const __global half* q_idx, // [tokens, Hiq*Di]+ const __global half* k_idx, // [tokens, Di]+ const __global half* q_norm_weight, // [Di]+ const __global half* k_norm_weight, // [Di]+ const __global half* rope_cos, // [tokens, rotary_dim]+ const __global half* rope_sin, // [tokens, rotary_dim]+ const __global int* past_lens, // [num_seqs]+ const __global int* subsequence_begins, // [num_seqs+1]+ const __global int* block_indices, // [used_blocks]+ const __global int* block_indices_begins, // [num_seqs+1]+ __global half* raw_k_cache, // [num_blocks, 1, page_size, Di]+ __global half* summary_cache, // [num_blocks, 1, page_size/r, Di]+ __global half* rope_cache, // [num_blocks, page_size/r, 2*rotary_dim]+ __global half* indexer_q, // [tokens, Hiq, Di]+ const uint num_wg,+ const uint num_seqs) {+ const uint HIQ = QSA_IDX_QUERY_HEADS;+ const uint DI = QSA_IDX_HEAD_DIM;+ const uint ROT = QSA_IDX_ROTARY_DIM;+ const uint R = QSA_COMPRESS_RATIO;+ const uint PAGE = QSA_PAGE_SIZE;+ const uint SPP = PAGE / R;++ const uint wg = get_group_id(2);+ const uint role = get_group_id(1);+ const uint lane = get_sub_group_local_id();+ if (wg >= num_wg) {+ return;+ }++ // Maps the work-group index onto the (sequence, QSA block) it prepares.+ uint seq = 0, qsa_block = 0;+ bool found = false;+ {+ uint acc = 0;+ for (uint i = 0; i < num_seqs && !found; i++) {+ const uint q_len = (uint)subsequence_begins[i + 1] - (uint)subsequence_begins[i];+ if (q_len == 0) {+ continue;+ }+ const uint past = (uint)past_lens[i];+ const uint first = past / R;+ const uint n = (past + q_len - 1) / R - first + 1;+ if (wg < acc + n) {+ seq = i;+ qsa_block = first + (wg - acc);+ found = true;+ }+ acc += n;+ }+ }+ if (!found) {+ return;+ }++ const uint seq_begin = (uint)subsequence_begins[seq];+ const uint q_len = (uint)subsequence_begins[seq + 1] - seq_begin;+ const uint past_len = (uint)past_lens[seq];+ const uint total_len = past_len + q_len;+ const uint page_begin = (uint)block_indices_begins[seq];++ const uint block_start = qsa_block * R;+ const uint block_end = block_start + R;+ const uint lo = block_start > past_len ? block_start : past_len;+ const uint hi = block_end < total_len ? block_end : total_len;++ if (role < HIQ) {+ for (uint p = lo; p < hi; p++) {+ const uint token_idx = seq_begin + (p - past_len);+ float q[QSA_NE];+ FUNC_CALL(qsa_rd_f32)(q_idx + (token_idx * HIQ + role) * DI, q, QSA_NE);+ FUNC_CALL(qsa_rms_norm)(q, q_norm_weight);+#if QSA_IDX_ROTARY_DIM > 0+ FUNC_CALL(qsa_rope)(q, rope_cos + token_idx * ROT, rope_sin + token_idx * ROT, 1);+#endif+ FUNC_CALL(qsa_wr_f32)(indexer_q + (token_idx * HIQ + role) * DI, q, QSA_NE);+ }+ return;+ }++ // Index key: cache layout transform only - no norm/RoPE before the write.+ for (uint p = lo; p < hi; p++) {+ const uint token_idx = seq_begin + (p - past_len);+ const uint page = (uint)block_indices[page_begin + p / PAGE];+ const uint dst = (page * PAGE + p % PAGE) * DI;+ ushort kh[QSA_NE];+ FUNC_CALL(qsa_rd)((const __global ushort*)(k_idx + token_idx * DI), kh, QSA_NE);+ FUNC_CALL(qsa_wr)((__global ushort*)(raw_k_cache + dst), kh, QSA_NE);+#if QSA_IDX_ROTARY_DIM > 0+ if (p == block_start) {+ // One row per block: the only row ever read back for it.+ const uint row = (page * SPP + qsa_block % SPP) * 2 * ROT;+ for (uint i = lane; i < ROT; i += QSA_SG) {+ rope_cache[row + 2 * i] = rope_cos[token_idx * ROT + i];+ rope_cache[row + 2 * i + 1] = rope_sin[token_idx * ROT + i];+ }+ }+#endif+ }++ // Only a fully written block produces a summary.+ if (block_end > total_len) {+ return;+ }++ float acc[QSA_NE];+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ acc[j] = 0.0f;+ }+ for (uint s = 0; s < R; s++) {+ const uint p = block_start + s;+ float v[QSA_NE];+ if (p >= past_len) {+ FUNC_CALL(qsa_rd_f32)(k_idx + (seq_begin + (p - past_len)) * DI, v, QSA_NE);+ } else {+ const uint page = (uint)block_indices[page_begin + p / PAGE];+ FUNC_CALL(qsa_rd_f32)(raw_k_cache + (page * PAGE + p % PAGE) * DI, v, QSA_NE);+ }+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ acc[j] += v[j];+ }+ }+ // The pooled mean is rounded to f16 before RMSNorm, like the reference model.+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ acc[j] = convert_float(convert_half_rte(acc[j] * (1.0f / (float)R)));+ }+ FUNC_CALL(qsa_rms_norm)(acc, k_norm_weight);+ const uint page = (uint)block_indices[page_begin + qsa_block / SPP];+#if QSA_IDX_ROTARY_DIM > 0+ // Coefficients of the block's first token: this call's input row, else the row persisted earlier.+ if (block_start >= past_len) {+ const uint first_token = seq_begin + (block_start - past_len);+ FUNC_CALL(qsa_rope)(acc, rope_cos + first_token * ROT, rope_sin + first_token * ROT, 1);+ } else {+ const uint row = (page * SPP + qsa_block % SPP) * 2 * ROT;+ FUNC_CALL(qsa_rope)(acc, rope_cache + row, rope_cache + row + 1, 2);+ }+#endif+ FUNC_CALL(qsa_wr_f32)(summary_cache + (page * SPP + qsa_block % SPP) * DI, acc, QSA_NE);+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_score_dpas.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_score_dpas.clnew file mode 100644index 00000000000..0b000f4d900--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_score_dpas.cl@@ -0,0 +1,168 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q2 prefill, systolic variant, shared by the paged and dense indexers+// through QSA_ADDRESS_MODE (0 = paged page-table gather, 1 = dense batch/stride addressing).+//+// XMX mapping (subgroup of 16): lane = query. A operand = 8 summary rows (a[i] = S[b0 + i][16 k + lane]), B operand+// = the lane's own 16 query halves of one K tile (kept in SLM, lane contiguous), C = 8 block scores of that query+// (c[i] = score[query = lane][b0 + i]), so the result needs no transpose. Each index head is ReLU-ed before the head+// sum; the sum is scaled by QSA_IDX_SCALE.+//+// JIT: QSA_IDX_QUERY_HEADS, QSA_IDX_HEAD_DIM, QSA_IDX_SCALE, QSA_COMPRESS_RATIO, QSA_BLOCK_TOPK, QSA_ADDRESS_MODE,+// QSA_SCORE_WG, SUBGROUP_SIZE and (paged) QSA_PAGE_SIZE+// Dispatch: gws = [num_tiles * QSA_SCORE_WG * SG, 1, 1], lws = [QSA_SCORE_WG * SG, 1, 1]; one work-group owns one+// 16-query tile. `pitch` is the row pitch of block_scores, a multiple of 8 so the 8-wide stores stay inside the row.++#define QSA_INDEXER_HELPERS+#include "qsa_common.cl"++#define QSA_KT (QSA_IDX_HEAD_DIM / 16)+#define QSA_MB 8++#if SUBGROUP_SIZE != 16+# error "the systolic indexer score needs a 16-wide subgroup"+#endif++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(qsa_indexer_score_dpas)(const __global half* indexer_q, // [tokens, Hiq, Di]+ const __global half* summary_cache, // paged: [N_phys,1,page/r,Di]; dense: [B,1,S_cap/r,Di]+ const __global int* past_lens, // paged: [num_seqs]; dense: [B]+#if QSA_ADDRESS_MODE == 0+ const __global int* subsequence_begins, // [num_seqs+1]+ const __global int* block_indices, // [used_blocks]+ const __global int* block_indices_begins, // [num_seqs+1]+#endif+ __global float* block_scores, // [tokens, pitch]+ const uint num_tiles,+#if QSA_ADDRESS_MODE == 0+ const uint num_seqs,+#else+ const uint seq_len,+ const uint summary_stride,+#endif+ const uint pitch) {+ const uint HIQ = QSA_IDX_QUERY_HEADS;+ const uint DI = QSA_IDX_HEAD_DIM;+ const uint R = QSA_COMPRESS_RATIO;+ const uint WGN = QSA_SCORE_WG;+ const uint NQ = QSA_SG;+#if QSA_ADDRESS_MODE == 0+ const uint PAGE = QSA_PAGE_SIZE;+ const uint SPP = PAGE / R;+#endif++ __local uint slm_q[QSA_IDX_QUERY_HEADS * QSA_KT][8][QSA_SG];++ const uint wg = get_group_id(0);+ if (wg >= num_tiles) {+ return;+ }+ const uint sg = get_sub_group_id();+ const uint lane = get_sub_group_local_id();++ uint anchor = 0; // paged: sequence; dense: batch row+ uint token_begin = 0; // paged: global first token; dense: first position within the row+#if QSA_ADDRESS_MODE == 0+ if (!FUNC_CALL(qsa_resolve_tile_paged)(subsequence_begins, num_seqs, wg, NQ, &anchor, &token_begin)) {+ return;+ }+ const uint seq_begin = (uint)subsequence_begins[anchor];+ const uint seq_end = (uint)subsequence_begins[anchor + 1];+ const uint past_len = (uint)past_lens[anchor];+ const uint page_begin = (uint)block_indices_begins[anchor];+ const uint token0 = token_begin;+ uint valid = seq_end > token0 ? seq_end - token0 : 0;+ const uint first_abs = past_len + token0 - seq_begin;+ const uint n_complete_lane = (lane + first_abs + 1) / R;+#else+ const uint tiles_per_row = (seq_len + NQ - 1) / NQ;+ anchor = wg / tiles_per_row;+ token_begin = (wg % tiles_per_row) * NQ;+ const uint past_len = (uint)past_lens[anchor];+ const uint token0 = anchor * seq_len + token_begin;+ uint valid = seq_len > token_begin ? seq_len - token_begin : 0;+ // Dense: past_lens holds key_length; position = key_length - seq_len + l, left padding sees no block.+ const uint shifted = lane + past_len + token_begin;+ const uint n_complete_lane = shifted < seq_len ? 0 : (shifted + 1 - seq_len) / R;+#endif+ if (valid > NQ) {+ valid = NQ;+ }+ const uint n_blocks_max = valid == 0 ? 0 : sub_group_broadcast(n_complete_lane, valid - 1);++ // Dense-prefix bypass: the finalizer selects every block of such a tile without reading any score.+ if (n_blocks_max <= (uint)QSA_BLOCK_TOPK) {+ return;+ }++ // Stage the query tile as B operands: slm_q[h*KT + k][i][lane] = (Q[lane][16k + 2i], Q[lane][16k + 2i + 1]).+ for (uint t = sg; t < HIQ * QSA_KT; t += WGN) {+ const uint h = t / QSA_KT;+ const uint k = t % QSA_KT;+ uint8 v = (uint8)(0);+ if (lane < valid) {+ v = vload8(0, (const __global uint*)(indexer_q + ((token0 + lane) * HIQ + h) * DI + k * 16));+ }+ slm_q[t][0][lane] = v.s0;+ slm_q[t][1][lane] = v.s1;+ slm_q[t][2][lane] = v.s2;+ slm_q[t][3][lane] = v.s3;+ slm_q[t][4][lane] = v.s4;+ slm_q[t][5][lane] = v.s5;+ slm_q[t][6][lane] = v.s6;+ slm_q[t][7][lane] = v.s7;+ }+ barrier(CLK_LOCAL_MEM_FENCE);++ for (uint b0 = sg * QSA_MB; b0 < n_blocks_max; b0 += WGN * QSA_MB) {+ ushort rowd[QSA_MB][QSA_KT];+ unroll_for (uint r = 0; r < QSA_MB; r++) {+ const uint b = b0 + r;+ if (b < n_blocks_max) {+#if QSA_ADDRESS_MODE == 0+ // A block past the last visible one has a page id outside this sequence's list: zero it instead.+ const uint page = (uint)block_indices[page_begin + b / SPP];+ const uint src = (page * SPP + b % SPP) * DI;+#else+ const uint src = (anchor * summary_stride + b) * DI;+#endif+ FUNC_CALL(qsa_rd)((const __global ushort*)(summary_cache + src), rowd[r], QSA_KT);+ } else {+ unroll_for (uint k = 0; k < QSA_KT; k++) {+ rowd[r][k] = 0;+ }+ }+ }++ // The head loop stays rolled: unrolled, the compiler hoists every head's B operands (HIQ * KT int8) into+ // registers ahead of the first mad and spills them.+ float8 acc = (float8)(0.0f);+ __attribute__((opencl_unroll_hint(1)))+ for (uint h = 0; h < HIQ; h++) {+ float8 st = (float8)(0.0f);+ unroll_for (uint k = 0; k < QSA_KT; k++) {+ const short8 a = (short8)((short)rowd[0][k], (short)rowd[1][k], (short)rowd[2][k], (short)rowd[3][k],+ (short)rowd[4][k], (short)rowd[5][k], (short)rowd[6][k], (short)rowd[7][k]);+#ifdef cl_intel_subgroup_local_block_io+ const int8 bq = as_int8(intel_sub_group_block_read8(&slm_q[h * QSA_KT + k][0][0]));+#else+ const int8 bq = (int8)(as_int(slm_q[h * QSA_KT + k][0][lane]), as_int(slm_q[h * QSA_KT + k][1][lane]),+ as_int(slm_q[h * QSA_KT + k][2][lane]), as_int(slm_q[h * QSA_KT + k][3][lane]),+ as_int(slm_q[h * QSA_KT + k][4][lane]), as_int(slm_q[h * QSA_KT + k][5][lane]),+ as_int(slm_q[h * QSA_KT + k][6][lane]), as_int(slm_q[h * QSA_KT + k][7][lane]));+#endif+ st = intel_sub_group_f16_f16_matrix_mad_k16(a, bq, st);+ }+ // ReLU per indexer head, strictly before the head reduction.+ acc += fmax(st, (float8)(0.0f));+ }+ acc *= (float)QSA_IDX_SCALE;++ // A row of a dense prefix is never published.+ if (lane < valid && n_complete_lane > (uint)QSA_BLOCK_TOPK) {+ vstore8(acc, 0, block_scores + (size_t)(token0 + lane) * pitch + b0);+ }+ }+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_score_partition.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_score_partition.clnew file mode 100644index 00000000000..588195ddaaa--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_score_partition.cl@@ -0,0 +1,128 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q2 score, decode-partition variant, shared by the paged and+// dense indexers through QSA_ADDRESS_MODE (0 = paged page-table gather, 1 = dense batch/stride addressing).+//+// One subgroup scores one partition of QSA_SCORE_PARTITION_BLOCKS blocks of one query token. Lanes cover the index+// head dimension (block reads), so each block/head dot product is a per-lane partial sum plus a subgroup reduction;+// the query stays in registers and U summary rows are kept in flight. It is also the scorer of the non-XMX prefill.+//+// JIT: QSA_IDX_QUERY_HEADS, QSA_IDX_HEAD_DIM, QSA_IDX_SCALE, QSA_COMPRESS_RATIO, QSA_ADDRESS_MODE, QSA_BLOCK_TOPK,+// QSA_SCORE_PARTITION_BLOCKS, QSA_DENSE_SCORE_BYPASS, SUBGROUP_SIZE and (paged) QSA_PAGE_SIZE+// Dispatch: gws = [(row_end - row_begin) * SG, 1, num_partitions], lws = [SG, 1, 1]+// `pitch` is the (8-aligned) row pitch of block_scores, which holds only rows [row_begin, row_end).++#define QSA_INDEXER_HELPERS+#include "qsa_common.cl"++#define QSA_U 8++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(qsa_indexer_score_partition)(const __global half* indexer_q, // [tokens, Hiq, Di]+ const __global half* summary_cache, // paged: [N_phys,1,page/r,Di]; dense: [B,1,S_cap/r,Di]+ const __global int* past_lens, // paged: [num_seqs]; dense: [B]+#if QSA_ADDRESS_MODE == 0+ const __global int* subsequence_begins, // [num_seqs+1]+ const __global int* block_indices, // [used_blocks]+ const __global int* block_indices_begins, // [num_seqs+1]+#endif+ __global float* block_scores, // [row_end - row_begin, pitch]+ const uint num_tokens,+#if QSA_ADDRESS_MODE == 0+ const uint num_seqs,+#else+ const uint seq_len,+ const uint summary_stride,+#endif+ const uint pitch,+ const uint num_partitions,+ const uint row_begin,+ const uint row_end) {+ const uint HIQ = QSA_IDX_QUERY_HEADS;+ const uint DI = QSA_IDX_HEAD_DIM;+#if QSA_ADDRESS_MODE == 0+ const uint PAGE = QSA_PAGE_SIZE;+ const uint SPP = PAGE / QSA_COMPRESS_RATIO;+#endif+ const uint lane = get_sub_group_local_id();++ const uint token_idx = get_group_id(0) + row_begin;+ const uint partition = get_group_id(2);+ if (token_idx >= row_end || token_idx >= num_tokens || partition >= num_partitions) {+ return;+ }++ uint seq = 0, abs_pos = 0;+#if QSA_ADDRESS_MODE == 0+ if (!FUNC_CALL(qsa_resolve_token_paged)(subsequence_begins, past_lens, num_seqs, token_idx, &seq, &abs_pos)) {+ return;+ }+ const uint page_begin = (uint)block_indices_begins[seq];+#else+ FUNC_CALL(qsa_resolve_token_dense)(past_lens, seq_len, token_idx, &seq, &abs_pos);+#endif++ const uint n_complete = FUNC_CALL(qsa_num_complete_blocks)(abs_pos);+#if QSA_DENSE_SCORE_BYPASS+ // The paired finalizer never reads the scores of a row that selects every block.+ if (n_complete <= (uint)QSA_BLOCK_TOPK) {+ return;+ }+#endif++ const uint begin = partition * (uint)QSA_SCORE_PARTITION_BLOCKS;+ if (begin >= n_complete) {+ return;+ }+ uint end = begin + (uint)QSA_SCORE_PARTITION_BLOCKS;+ if (end > n_complete) {+ end = n_complete;+ }++ __global float* row = block_scores + (size_t)(token_idx - row_begin) * pitch;++ // The query stays in registers for the whole partition scan; only summaries stream.+ float q[QSA_IDX_QUERY_HEADS][QSA_NE];+ unroll_for (uint h = 0; h < HIQ; h++) {+ FUNC_CALL(qsa_rd_f32)(indexer_q + (token_idx * HIQ + h) * DI, q[h], QSA_NE);+ }++ for (uint b0 = begin; b0 < end; b0 += QSA_U) {+ const uint n = (end - b0) < QSA_U ? (end - b0) : QSA_U;+ ushort s[QSA_U][QSA_NE];+ unroll_for (uint u = 0; u < QSA_U; u++) {+ if (u < n) {+ const uint b = b0 + u;+#if QSA_ADDRESS_MODE == 0+ const uint page = (uint)block_indices[page_begin + b / SPP];+ const uint src = (page * SPP + b % SPP) * DI;+#else+ const uint src = (seq * summary_stride + b) * DI;+#endif+ FUNC_CALL(qsa_rd)((const __global ushort*)(summary_cache + src), s[u], QSA_NE);+ }+ }+ float mine = 0.0f;+ unroll_for (uint u = 0; u < QSA_U; u++) {+ if (u < n) {+ float total = 0.0f;+ unroll_for (uint h = 0; h < HIQ; h++) {+ float dot = 0.0f;+ unroll_for (uint j = 0; j < QSA_NE; j++) {+ dot += q[h][j] * convert_float(as_half(s[u][j]));+ }+ dot = sub_group_reduce_add(dot);+ total += dot > 0.0f ? dot : 0.0f;+ }+ if (lane == u) {+ mine = total * (float)QSA_IDX_SCALE;+ }+ }+ }+ if (lane < n) {+ row[b0 + lane] = mine;+ }+ }+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_topk.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_topk.clnew file mode 100644index 00000000000..5886ecff41a--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_indexer_topk.cl@@ -0,0 +1,249 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q2 top-k finalize, shared by the paged and dense indexers through+// QSA_ADDRESS_MODE (0 = paged, 1 = dense).+//+// A work-group of QSA_TOPK_WG subgroups jointly selects the top-k blocks of one token row: score descending, block+// id ascending as tie-break, written in ASCENDING block order. The k-th largest order-preserving uint key is found by+// an (NT + 1)-ary count search: each probe counts the keys >= NT evenly spaced thresholds in one pass over the row and+// one barrier (per-subgroup partials are double-buffered in SLM and reduced redundantly by every work-item), so 32 key+// bits take ceil(32 / log2(NT + 1)) probes. The keys of the row live in registers (QSA_TOPK_REG_KEYS per lane); a row+// that does not fit rescans global memory on every probe, with the same result. Subgroup s owns the contiguous block+// range [s*chunk, (s+1)*chunk) and lane l of it the contiguous run of chunk/SG keys starting at l * chunk/SG, so every+// lane writes its picks in ascending order and one subgroup scan of the per-lane counts places them. A row that selects every+// block never reads its scores.+//+// JIT: QSA_BLOCK_TOPK, QSA_COMPRESS_RATIO, QSA_ADDRESS_MODE, QSA_TOPK_WG (most subgroups), QSA_TOPK_REG_KEYS, QSA_TOPK_THRESHOLDS (<= 7),+// SUBGROUP_SIZE+// Dispatch: gws = [rows * W * SG, 1, 1], lws = [W * SG, 1, 1] with W <= QSA_TOPK_WG subgroups (W = QSA_TOPK_WG if QSA_TOPK_FIXED_WG)+// block_scores holds only rows [row_begin, row_end) with row pitch `pitch`.++#include "qsa_common.cl"++#define QSA_NT QSA_TOPK_THRESHOLDS+#define QSA_KPL QSA_TOPK_REG_KEYS+#define QSA_GRP 8 // the register walk tests the run length once per QSA_GRP keys; QSA_KPL is a multiple of it++// Monotone float -> uint key.+inline uint FUNC(qsa_ordered_key)(float f) {+ const uint bits = as_uint(f);+ return bits ^ ((bits & 0x80000000u) ? 0xFFFFFFFFu : 0x80000000u);+}++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(qsa_indexer_topk)(const __global float* block_scores, // [row_end - row_begin, pitch]+ const __global int* past_lens, // paged: [num_seqs]; dense: [B]+#if QSA_ADDRESS_MODE == 0+ const __global int* subsequence_begins, // [num_seqs+1]+#endif+ __global int* selected_blocks, // [tokens, block_topk]+ __global int* selected_counts, // [tokens]+ const uint num_tokens,+#if QSA_ADDRESS_MODE == 0+ const uint num_seqs,+#else+ const uint seq_len,+#endif+ const uint pitch,+ const uint row_begin,+ const uint row_end) {+ const uint K = QSA_BLOCK_TOPK;+#ifdef QSA_TOPK_FIXED_WG+ // Compile-time work-group size (decode): the per-probe SLM reductions unroll.+ const uint WGN = QSA_TOPK_WG;+ const uint WGT = QSA_TOPK_WG * QSA_SG;+#else+ const uint WGN = get_num_sub_groups();+ const uint WGT = get_local_size(0);+#endif++ __local uint slm_cnt[2][QSA_TOPK_WG][8];+ __local uint slm_tie[QSA_TOPK_WG][2];++ const uint token = get_group_id(0) + row_begin;+ if (token >= row_end || token >= num_tokens) {+ return;+ }+ const uint sg = get_sub_group_id();+ const uint lane = get_sub_group_local_id();+ const uint lid = get_local_id(0);++ uint seq = 0, abs_pos = 0;+#if QSA_ADDRESS_MODE == 0+ if (!FUNC_CALL(qsa_resolve_token_paged)(subsequence_begins, past_lens, num_seqs, token, &seq, &abs_pos)) {+ return;+ }+#else+ FUNC_CALL(qsa_resolve_token_dense)(past_lens, seq_len, token, &seq, &abs_pos);+#endif++ const uint n = FUNC_CALL(qsa_num_complete_blocks)(abs_pos);+ const uint k = n < K ? n : K;+ __global int* out = selected_blocks + (size_t)token * K;+ if (lid == 0) {+ selected_counts[token] = (int)k;+ }+ for (uint i = k + lid; i < K; i += WGT) {+ out[i] = -1;+ }+ if (k == 0) {+ return;+ }+ if (k == n) {+ // Dense prefix: every visible block, ascending; no score is read.+ for (uint i = lid; i < k; i += WGT) {+ out[i] = (int)i;+ }+ return;+ }++ const __global float* scores = block_scores + (size_t)(token - row_begin) * pitch;++ // 64-aligned consecutive ownership, possibly empty subgroups; lane l of a subgroup owns the nj elements begin + l * nj + j.+ const uint chunk = ((n + WGN * 64 - 1) / (WGN * 64)) * 64;+ const uint begin = sg * chunk;+ const uint end = min(begin + chunk, n);+ const bool use_reg = chunk <= QSA_KPL * QSA_SG;+ const uint nj = chunk / QSA_SG; // keys per lane++ uint rk[QSA_KPL];+ if (use_reg) {+ // Every slot below the run length rounded up to QSA_GRP is defined: 0 past the run / the row.+ unroll_for (uint j = 0; j < QSA_KPL; j += 4) {+ if (j >= nj + (QSA_GRP - 4)) {+ break;+ }+ const uint idx = begin + lane * nj + j;+ const uint lim = j < nj ? min(end - min(end, idx), 4u) : 0u; // valid keys of this quad+ float4 v = (float4)(0.0f);+ if (lim == 4) {+ v = vload4(0, scores + idx);+ } else {+ v.s0 = lim > 0 ? scores[idx + 0] : 0.0f;+ v.s1 = lim > 1 ? scores[idx + 1] : 0.0f;+ v.s2 = lim > 2 ? scores[idx + 2] : 0.0f;+ v.s3 = lim > 3 ? scores[idx + 3] : 0.0f;+ }+ rk[j + 0] = lim > 0 ? FUNC_CALL(qsa_ordered_key)(v.s0) : 0u;+ rk[j + 1] = lim > 1 ? FUNC_CALL(qsa_ordered_key)(v.s1) : 0u;+ rk[j + 2] = lim > 2 ? FUNC_CALL(qsa_ordered_key)(v.s2) : 0u;+ rk[j + 3] = lim > 3 ? FUNC_CALL(qsa_ordered_key)(v.s3) : 0u;+ }+ }+// Visits this lane's keys in ascending block order: `key`, `idx` and `valid` (inside the row; `key` is 0 otherwise) are in+// scope in BODY. The register walk tests the run length once per QSA_GRP keys to keep branches out of the hot loops.+#define QSA_FOR_KEYS(...) \+ if (use_reg) { \+ unroll_for (uint jb = 0; jb < QSA_KPL; jb += QSA_GRP) { \+ if (jb >= nj) { \+ break; \+ } \+ unroll_for (uint jj = 0; jj < QSA_GRP; jj++) { \+ const uint j = jb + jj; \+ const uint idx = begin + lane * nj + j; \+ const bool valid = j < nj && idx < end; \+ const uint key = rk[j]; \+ __VA_ARGS__ \+ } \+ } \+ } else { \+ for (uint j = 0; j < nj; j++) { \+ const uint idx = begin + lane * nj + j; \+ const bool valid = idx < end; \+ const uint key = valid ? FUNC_CALL(qsa_ordered_key)(scores[idx]) : 0u; \+ __VA_ARGS__ \+ } \+ }++ // ---- (NT + 1)-ary count search for the k-th largest key: it stays inside [lo, hi] ----+ uint lo = 0, hi = 0xFFFFFFFFu;+ uint iter = 0;+ while (lo < hi) {+ const uint step = (hi - lo) / (QSA_NT + 1) + 1;+ uint th[QSA_NT];+ uint cnt[QSA_NT];+ unroll_for (uint i = 0; i < QSA_NT; i++) {+ const ulong m = (ulong)lo + (ulong)(i + 1) * step;+ th[i] = m > hi ? 0xFFFFFFFFu : (uint)m;+ cnt[i] = 0;+ }+ QSA_FOR_KEYS(+ unroll_for (uint i = 0; i < QSA_NT; i++) {+ cnt[i] += key >= th[i] ? 1u : 0u;+ })+ const uint slot = iter & 1;+ unroll_for (uint i = 0; i < QSA_NT; i++) {+ cnt[i] = sub_group_reduce_add(cnt[i]);+ }+ if (lane == 0) {+ unroll_for (uint i = 0; i < QSA_NT; i++) {+ slm_cnt[slot][sg][i] = cnt[i];+ }+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ uint8 tot = (uint8)(0);+ for (uint t = 0; t < WGN; t++) {+ tot += vload8(0, &slm_cnt[slot][t][0]);+ }+ const uint tc[8] = {tot.s0, tot.s1, tot.s2, tot.s3, tot.s4, tot.s5, tot.s6, tot.s7};+ uint nlo = lo, nhi = hi;+ bool below = false;+ unroll_for (uint i = 0; i < QSA_NT; i++) {+ const ulong m = (ulong)lo + (ulong)(i + 1) * step;+ if (m <= hi && !below) {+ if (tc[i] >= k) {+ nlo = (uint)m;+ } else {+ nhi = (uint)m - 1;+ below = true;+ }+ }+ }+ lo = nlo;+ hi = nhi;+ iter++;+ }++ // ---- entries strictly above / exactly at the threshold ----+ uint lane_greater = 0, lane_equal = 0;+ QSA_FOR_KEYS(+ lane_greater += (valid && key > lo) ? 1u : 0u;+ lane_equal += (valid && key == lo) ? 1u : 0u;)+ const uint greater = sub_group_reduce_add(lane_greater);+ const uint equal = sub_group_reduce_add(lane_equal);+ if (lane == 0) {+ slm_tie[sg][0] = greater;+ slm_tie[sg][1] = equal;+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ // Every subgroup derives its own output offset and its share of the threshold-level entries.+ uint total_greater = 0;+ for (uint t = 0; t < WGN; t++) {+ total_greater += slm_tie[t][0];+ }+ uint equals_left = k - total_greater, offset = 0, my_equal = 0;+ for (uint t = 0; t < WGN; t++) {+ const uint g = slm_tie[t][0];+ const uint e = min(equals_left, slm_tie[t][1]);+ if (t == sg) {+ my_equal = e;+ break;+ }+ offset += g + e;+ equals_left -= e;+ }++ // The first `my_equal` threshold-level entries of the subgroup (in block order) are taken: split them over lanes.+ const uint eq_before = sub_group_scan_exclusive_add(lane_equal);+ uint quota = my_equal > eq_before ? min(lane_equal, my_equal - eq_before) : 0u;+ uint written = offset + sub_group_scan_exclusive_add(lane_greater + quota);+ QSA_FOR_KEYS(+ if (valid && key > lo) {+ out[written++] = (int)idx;+ } else if (valid && key == lo && quota != 0) {+ quota--;+ out[written++] = (int)idx;+ })+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_stage_events.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_stage_events.hppnew file mode 100644index 00000000000..fddd04b93dc--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/qsa_stage_events.hpp@@ -0,0 +1,33 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <vector>++#include "intel_gpu/runtime/event.hpp"++namespace ov::intel_gpu::ocl::qsa {++/// Test / benchmark hook: while armed, the multi-stage QSA primitives (SparsePA, SparseSDPA) append the event of every+/// stage they dispatch, so a profiling-enabled queue can report the GPU time of the whole call (the primitive itself+/// only returns the event of its last stage).+struct QsaStageEvents {+ static bool& armed() {+ static bool value = false;+ return value;+ }+ static std::vector<cldnn::event::ptr>& events() {+ static std::vector<cldnn::event::ptr> value;+ return value;+ }+ static const cldnn::event::ptr& record(const cldnn::event::ptr& ev) {+ if (armed()) {+ events().push_back(ev);+ }+ return ev;+ }+};++} // namespace ov::intel_gpu::ocl::qsadiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmakeindex 0b75822ad1b..c85060e2f13 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake@@ -69,6 +69,16 @@ set(GPU_OCL_V2_IMPL_SOURCES${CMAKE_CURRENT_LIST_DIR}/paged_selective_ssm.cpp${CMAKE_CURRENT_LIST_DIR}/paged_selective_ssm.hpp${CMAKE_CURRENT_LIST_DIR}/primitive_ocl_base.hpp+ ${CMAKE_CURRENT_LIST_DIR}/qsa_host_common.hpp+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer/paged_qsa_indexer.cpp+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer/paged_qsa_indexer.hpp+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer/qsa_indexer.cpp+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer/qsa_indexer.hpp+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention/sparse_attention_common.hpp+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention/sparse_pa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention/sparse_pa.hpp+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention/sparse_sdpa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention/sparse_sdpa.hpp${CMAKE_CURRENT_LIST_DIR}/rope_opt.cpp${CMAKE_CURRENT_LIST_DIR}/rope_opt.hpp${CMAKE_CURRENT_LIST_DIR}/scatter_nd_update.cpp@@ -152,6 +162,12 @@ set(GPU_OCL_V2_KERNEL_SOURCES${CMAKE_CURRENT_LIST_DIR}/paged_selective_ssm_jit_precompute.cl${CMAKE_CURRENT_LIST_DIR}/paged_selective_ssm_large_state.cl${CMAKE_CURRENT_LIST_DIR}/paged_selective_ssm_opt.cl+ ${CMAKE_CURRENT_LIST_DIR}/qsa_common.cl+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer_prepare_dense.cl+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer_prepare_paged.cl+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer_score_dpas.cl+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer_score_partition.cl+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer_topk.cl${CMAKE_CURRENT_LIST_DIR}/rope_opt.cl${CMAKE_CURRENT_LIST_DIR}/scatter_nd_update_copy.cl${CMAKE_CURRENT_LIST_DIR}/scatter_nd_update_opt.cl@@ -168,4 +184,10 @@ set(GPU_OCL_V2_KERNEL_SOURCES${CMAKE_CURRENT_LIST_DIR}/selective_ssm_type_utils.cl${CMAKE_CURRENT_LIST_DIR}/slice_scatter_opt.cl${CMAKE_CURRENT_LIST_DIR}/slice_scatter_ref.cl+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention_dpas.cl+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention_gqa_dpas.cl+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention_kv_write.cl+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention_scalar.cl+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention_split.cl+ ${CMAKE_CURRENT_LIST_DIR}/sparse_attention_split_reduce.cl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_attention_common.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_attention_common.hppnew file mode 100644index 00000000000..20624f4fd03--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_attention_common.hpp@@ -0,0 +1,327 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Kernel generators shared by the OpenCL SparsePA (paged) and SparseSDPA (dense) implementations. The two primitives+// run the same kernels with a different QSA_ADDRESS_MODE; only the input slots and the scalar lists differ.++#pragma once++#include <algorithm>+#include <array>+#include <memory>+#include <optional>+#include <string>+#include <type_traits>+#include <utility>+#include <vector>++#include "../primitive_ocl_base.hpp"+#include "../qsa_host_common.hpp"+#include "intel_gpu/graph/kernel_impl_params.hpp"++namespace ov::intel_gpu::ocl::qsa {++struct SparseAttentionInternalBufIdx {+ static constexpr size_t SPLIT_ACC = 0; ///< f32 [rows, Hq, partitions, Dv]; decode split attention only+ static constexpr size_t SPLIT_ML = 1; ///< f32 [rows, Hq, partitions, 2]; decode split attention only++ static constexpr size_t COUNT = 2;+};++/// All sizes are upper bounds derived from shapes: the real sequence lengths live in GPU memory.+struct SparseAttentionRuntimeParams : public ImplRuntimeParams {+ size_t num_tokens = 0; ///< paged: tokens; dense: B * L+ size_t num_seqs = 0;+ size_t tile_count = 0;+ bool is_decode = false;+ size_t batch = 0;+ size_t seq_len = 0;+ size_t history_len = 0;+ size_t k_seq_pitch = 0;+ size_t v_seq_pitch = 0;+ size_t k_param_pitch = 0; ///< dense compressed K/V: allocated S of the key scale / zero point+ size_t v_param_pitch = 0; ///< dense compressed K/V: allocated S of the value scale / zero point+ size_t q_base = 0;+ size_t q_pitch = 0;+};++enum class AttKind { Scalar, Dpas, Gqa, GqaSplit, Split, Reduce };++/// Input slots of the primitive the generators serve.+struct SparseAttentionSlots {+ bool paged = true;+ size_t query = 0;+ size_t key = 0; ///< paged: key cache+ size_t value = 0;+ size_t past_lens = 0;+ size_t subsequence_begins = 0;+ size_t block_indices = 0;+ size_t block_indices_begins = 0;+ size_t selected_blocks = 0;+ size_t selected_count = 0;+ size_t key_length = 0;+ /// Dense compressed K/V parameter inputs (key scale, value scale, key zero point, value zero point), in that order.+ std::array<size_t, 4> kv_params = {0, 0, 0, 0};+};++template <class Desc, class = void>+struct has_page_size : std::false_type {};+template <class Desc>+struct has_page_size<Desc, std::void_t<decltype(std::declval<const Desc&>().page_size)>> : std::true_type {};++/// Tokens per physical page: the explicit attribute (quantized caches change the dim 2 of the cache), else dim 2 of an+/// f16 key cache. Dense (non paged) primitives have none.+template <class Desc>+inline std::optional<size_t> page_size_of(const SparseAttentionSlots& slots, const RuntimeParams& params, const Desc& desc) {+ if (!slots.paged) {+ return std::nullopt;+ }+ if constexpr (has_page_size<Desc>::value) {+ if (desc.page_size != 0) {+ return desc.page_size;+ }+ }+ const auto& ps = params.get_input_layout(slots.key).get_partial_shape();+ OPENVINO_ASSERT(ps.size() == 4 && ps[2].is_static(), "[GPU][OCL] sparse attention: key_cache must have a static page_size dim");+ return static_cast<size_t>(ps[2].get_length());+}++template <class Desc>+class AttentionGenerator : public QsaGenerator {+public:+ AttentionGenerator(AttKind kind, const SparseAttentionSlots& slots)+ : QsaGenerator(template_name(kind), entry_name(kind, slots.paged), kind == AttKind::Dpas || kind == AttKind::Gqa || kind == AttKind::GqaSplit),+ m_kind(kind),+ m_slots(slots) {}++ static std::string template_name(AttKind kind) {+ switch (kind) {+ case AttKind::Scalar:+ return "sparse_attention_scalar";+ case AttKind::Dpas:+ return "sparse_attention_dpas";+ case AttKind::Gqa:+ case AttKind::GqaSplit:+ return "sparse_attention_gqa_dpas";+ case AttKind::Split:+ return "sparse_attention_split";+ case AttKind::Reduce:+ return "sparse_attention_split_reduce";+ }+ return {};+ }++ // Entry names carry the addressing mode so the kernel is recognisable in dumps and tests.+ static std::string entry_name(AttKind kind, bool paged) {+ const std::string base = paged ? "sparse_attention_paged" : "sparse_attention_dense";+ switch (kind) {+ case AttKind::Scalar:+ return base;+ case AttKind::Dpas:+ return base + "_dpas";+ case AttKind::Gqa:+ return base + "_gqa_dpas";+ case AttKind::GqaSplit:+ return base + "_gqa_dpas_split";+ case AttKind::Split:+ return base + "_split";+ case AttKind::Reduce:+ return base + "_split_reduce";+ }+ return base;+ }++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = QsaGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<Desc>();+ const auto& sel_ps = params.get_input_layout(m_slots.selected_blocks).get_partial_shape();+ OPENVINO_ASSERT(sel_ps.rank().is_static() && sel_ps.size() >= 2 && sel_ps[sel_ps.size() - 1].is_static(),+ "[GPU][OCL] sparse attention expects a rank>=2 selected_block_indices input with a static K_max");+ const auto page = page_size_of(m_slots, params, *desc);++ jit.make("QSA_HEADS", desc->num_heads);+ jit.make("QSA_KV_HEADS", desc->num_kv_heads);+ jit.make("QSA_K_HEAD_SIZE", desc->k_head_size);+ jit.make("QSA_V_HEAD_SIZE", desc->v_head_size);+ jit.make("QSA_COMPRESS_RATIO", desc->key_block_size);+ jit.make("QSA_BLOCK_TOPK", sel_ps[sel_ps.size() - 1].get_length());+ jit.make("QSA_ADDRESS_MODE", m_slots.paged ? 0 : 1);+ jit.add(float_constant("QSA_SCALE", desc->scale));+ if (page) {+ jit.make("QSA_PAGE_SIZE", *page);+ }+ if constexpr (has_page_size<Desc>::value) {+ add_cache_jit(jit, "K", desc->key_quant, *page, desc->k_head_size);+ add_cache_jit(jit, "V", desc->value_quant, *page, desc->v_head_size);+ } else {+ jit.make("QSA_DENSE_QUANT", desc->kv_compressed() ? 1 : 0);+ add_dense_cache_jit(jit, "K", desc->key_quant, desc->k_head_size);+ add_dense_cache_jit(jit, "V", desc->value_quant, desc->v_head_size);+ }+ switch (m_kind) {+ case AttKind::Dpas:+ jit.make("QSA_ATT_WORKERS", std::max<size_t>(1, dpas_attention_workers(*desc)));+ jit.make("QSA_HEADS_PER_TILE", dpas_heads_per_tile(*desc));+ break;+ case AttKind::Gqa:+ jit.make("QSA_IS_CAUSAL", desc->causal ? 1 : 0);+ break;+ case AttKind::GqaSplit:+ jit.make("QSA_IS_CAUSAL", desc->causal ? 1 : 0);+ jit.make("QSA_GQA_SPLIT", 1);+ jit.make("QSA_SPLIT_PARTITIONS", gqa_split_partitions);+ break;+ case AttKind::Split:+ jit.make("QSA_SPLIT_PARTITIONS", split_partitions);+ break;+ case AttKind::Reduce:+ jit.make("QSA_SPLIT_PARTITIONS", decode_split_partitions(*desc, page, params.get_device_info()));+ jit.make("QSA_REDUCE_COLS", split_reduce_cols(desc->v_head_size));+ break;+ default:+ break;+ }+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ Arguments args;+ const auto input = [&](size_t idx) {+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)});+ };+ const auto internal = [&](size_t idx) {+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, static_cast<uint32_t>(idx)});+ };+ if (m_kind == AttKind::Reduce) {+ internal(SparseAttentionInternalBufIdx::SPLIT_ACC);+ internal(SparseAttentionInternalBufIdx::SPLIT_ML);+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});+ } else {+ input(m_slots.query);+ input(m_slots.key);+ input(m_slots.value);+ if (m_slots.paged) {+ input(m_slots.past_lens);+ input(m_slots.subsequence_begins);+ input(m_slots.block_indices);+ input(m_slots.block_indices_begins);+ input(m_slots.selected_blocks);+ input(m_slots.selected_count);+ } else {+ input(m_slots.selected_blocks);+ input(m_slots.selected_count);+ input(m_slots.key_length);+ if constexpr (!has_page_size<Desc>::value) {+ // Scales, then (asymmetric only) zero points.+ const size_t count = params.typed_desc<Desc>()->get_config().param_input_count();+ for (size_t i = 0; i < count; i++) {+ input(m_slots.kv_params[i]);+ }+ }+ }+ if (m_kind == AttKind::GqaSplit || m_kind == AttKind::Split) {+ internal(SparseAttentionInternalBufIdx::SPLIT_ACC);+ internal(SparseAttentionInternalBufIdx::SPLIT_ML);+ } else {+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});+ }+ }+ const uint32_t scalars = m_kind == AttKind::Reduce ? (m_slots.paged ? 1 : 2) : (m_slots.paged ? 4 : (dense_compressed(params) ? 7 : 5));+ for (uint32_t i = 0; i < scalars; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[kind = m_kind, paged = m_slots.paged](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<Desc>();+ auto* rtp = static_cast<SparseAttentionRuntimeParams*>(rt);+ OPENVINO_ASSERT(rtp != nullptr, "[GPU][OCL] sparse attention runtime params are not initialized");+ const size_t sg = subgroup_size(params.get_device_info());+ const size_t rows = std::max<size_t>(1, rtp->num_tokens);+ const size_t hq = desc->num_heads;+ auto& wgs = kd.params.workGroups;++ switch (kind) {+ case AttKind::Scalar:+ wgs.global = {hq * sg, rows, 1};+ wgs.local = {sg, 1, 1};+ break;+ case AttKind::Dpas: {+ const size_t workers = std::max<size_t>(1, dpas_attention_workers(*desc));+ const size_t ht = dpas_heads_per_tile(*desc);+ wgs.global = {(hq / ht) * workers * sg, std::max<size_t>(1, rtp->tile_count) * ht, 1};+ wgs.local = {workers * sg, 1, 1};+ break;+ }+ case AttKind::Gqa:+ case AttKind::GqaSplit:+ wgs.global = {rows * gqa_workers * sg, desc->num_kv_heads, kind == AttKind::GqaSplit ? gqa_split_partitions : 1};+ wgs.local = {gqa_workers * sg, 1, 1};+ break;+ case AttKind::Split:+ wgs.global = {hq * sg, rows, split_partitions};+ wgs.local = {sg, 1, 1};+ break;+ case AttKind::Reduce:+ wgs.global = {hq * sg, rows, desc->v_head_size / split_reduce_cols(desc->v_head_size)};+ wgs.local = {sg, 1, 1};+ break;+ }++ kd.params.scalars.clear();+ if (kind == AttKind::Reduce) {+ if (!paged) {+ push_u32(kd, rtp->seq_len);+ }+ push_u32(kd, rtp->num_tokens);+ return;+ }+ if (paged) {+ push_u32(kd, kind == AttKind::Dpas ? rtp->tile_count : rtp->num_tokens);+ push_u32(kd, rtp->num_seqs);+ push_u32(kd, rtp->q_base);+ push_u32(kd, rtp->q_pitch);+ } else {+ // scalar / split: (seq_len, history_len, rows, ...); dpas: (tiles, seq_len, history_len, ...);+ // gqa: (rows, seq_len, history_len, ...)+ if (kind == AttKind::Dpas || kind == AttKind::Gqa || kind == AttKind::GqaSplit) {+ push_u32(kd, kind == AttKind::Dpas ? rtp->tile_count : rtp->num_tokens);+ push_u32(kd, rtp->seq_len);+ push_u32(kd, rtp->history_len);+ } else {+ push_u32(kd, rtp->seq_len);+ push_u32(kd, rtp->history_len);+ push_u32(kd, rtp->num_tokens);+ }+ push_u32(kd, rtp->k_seq_pitch);+ push_u32(kd, rtp->v_seq_pitch);+ if constexpr (!has_page_size<Desc>::value) {+ if (desc->kv_compressed()) {+ push_u32(kd, rtp->k_param_pitch);+ push_u32(kd, rtp->v_param_pitch);+ }+ }+ }+ }};+ }++private:+ static bool dense_compressed(const RuntimeParams& params) {+ if constexpr (has_page_size<Desc>::value) {+ return false;+ } else {+ return params.typed_desc<Desc>()->kv_compressed();+ }+ }+ AttKind m_kind;+ SparseAttentionSlots m_slots;+};++} // namespace ov::intel_gpu::ocl::qsadiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_pa.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_pa.cppnew file mode 100644index 00000000000..403d1254a22--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_pa.cpp@@ -0,0 +1,398 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "sparse_pa.hpp"++#include <algorithm>+#include <array>+#include <cassert>+#include <memory>+#include <string>+#include <vector>++#include "../primitive_ocl_base.hpp"+#include "../qsa_host_common.hpp"+#include "../qsa_stage_events.hpp"+#include "common_utils/jitter.hpp"+#include "intel_gpu/graph/kernel_impl_params.hpp"+#include "intel_gpu/primitives/sparse_pa.hpp"+#include "primitive_inst.h"+#include "sparse_attention_common.hpp"++namespace ov::intel_gpu::ocl {++using namespace cldnn;+using SparsePAIn = cldnn::sparse_pa::InputIdx;++namespace {++qsa::SparseAttentionSlots pa_slots() {+ qsa::SparseAttentionSlots s;+ s.paged = true;+ s.query = SparsePAIn::QUERY;+ s.key = SparsePAIn::KEY_CACHE;+ s.value = SparsePAIn::VALUE_CACHE;+ s.past_lens = SparsePAIn::PAST_LENS;+ s.subsequence_begins = SparsePAIn::SUBSEQUENCE_BEGINS;+ s.block_indices = SparsePAIn::BLOCK_INDICES;+ s.block_indices_begins = SparsePAIn::BLOCK_INDICES_BEGINS;+ s.selected_blocks = SparsePAIn::SELECTED_BLOCK_INDICES;+ s.selected_count = SparsePAIn::SELECTED_BLOCK_COUNT;+ return s;+}++size_t token_pitch(const layout& l) {+ const auto& shape = l.get_shape();+ OPENVINO_ASSERT(shape.size() >= 2, "[GPU][OCL] sparse_pa expects a rank-2 (or legacy-padded) token-major input, got ", l.to_short_string());+ return shape[1];+}++/// Tokens per physical page: the explicit attribute, else dim 2 of an f16 key_cache.+size_t page_size_of(const kernel_impl_params& params) {+ const auto desc = params.typed_desc<sparse_pa>();+ if (desc->page_size != 0) {+ return desc->page_size;+ }+ const auto& ps = params.get_input_layout(SparsePAIn::KEY_CACHE).get_partial_shape();+ OPENVINO_ASSERT(ps.size() == 4 && ps[2].is_static(), "[GPU][OCL] sparse_pa: key_cache must have a static page_size dim");+ return static_cast<size_t>(ps[2].get_length());+}++bool is_decode_shape(const kernel_impl_params& params) {+ const auto& q_layout = params.get_input_layout(SparsePAIn::QUERY);+ const auto& past_lens_layout = params.get_input_layout(SparsePAIn::PAST_LENS);+ if (q_layout.is_dynamic() || past_lens_layout.is_dynamic()) {+ return false;+ }+ const auto tokens = q_layout.get_shape()[0];+ const auto seqs = past_lens_layout.get_shape()[0];+ return seqs > 0 && tokens == seqs;+}++bool may_decode(const kernel_impl_params& params) {+ return params.is_dynamic() || is_decode_shape(params);+}++// ===========================================================================+// Q0 - main KV cache write+// ===========================================================================+class KvWriteGenerator : public qsa::QsaGenerator {+public:+ KvWriteGenerator() : QsaGenerator("sparse_attention_kv_write", "sparse_attention_kv_write") {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = QsaGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<sparse_pa>();+ jit.make("QSA_KV_HEADS", desc->num_kv_heads);+ jit.make("QSA_K_HEAD_SIZE", desc->k_head_size);+ jit.make("QSA_V_HEAD_SIZE", desc->v_head_size);+ jit.make("QSA_PAGE_SIZE", page_size_of(params));+ jit.make("QSA_COMPRESS_RATIO", desc->key_block_size);+ qsa::add_cache_jit(jit, "K", desc->key_quant, page_size_of(params), desc->k_head_size);+ qsa::add_cache_jit(jit, "V", desc->value_quant, page_size_of(params), desc->v_head_size);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ for (auto idx : {SparsePAIn::KEY,+ SparsePAIn::VALUE,+ SparsePAIn::PAST_LENS,+ SparsePAIn::BLOCK_INDICES,+ SparsePAIn::BLOCK_INDICES_BEGINS,+ SparsePAIn::SUBSEQUENCE_BEGINS,+ SparsePAIn::KEY_CACHE,+ SparsePAIn::VALUE_CACHE}) {+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)});+ }+ for (uint32_t i = 0; i < 5; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<sparse_pa>();+ auto* rtp = static_cast<qsa::SparseAttentionRuntimeParams*>(rt);+ OPENVINO_ASSERT(rtp != nullptr, "[GPU][OCL] sparse_pa runtime params are not initialized");+ const auto sg = qsa::subgroup_size(params.get_device_info());++ auto& wgs = kd.params.workGroups;+ wgs.global = {sg, desc->num_kv_heads, std::max<size_t>(1, rtp->num_tokens)};+ wgs.local = {sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, token_pitch(params.get_input_layout(SparsePAIn::KEY)));+ qsa::push_u32(kd, params.get_input_layout(SparsePAIn::KEY).get_linear_offset());+ qsa::push_u32(kd, token_pitch(params.get_input_layout(SparsePAIn::VALUE)));+ qsa::push_u32(kd, params.get_input_layout(SparsePAIn::VALUE).get_linear_offset());+ qsa::push_u32(kd, rtp->num_seqs);+ }};+ }+};++using Gen = qsa::AttentionGenerator<sparse_pa>;++// ===========================================================================+// Q0 - BY_CHANNEL key cache write (group re-quantization)+// ===========================================================================+class KvWriteKChannelGenerator : public qsa::QsaGenerator {+public:+ KvWriteKChannelGenerator() : QsaGenerator("sparse_attention_kv_write", "sparse_attention_kv_write_kchannel", true) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = QsaGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<sparse_pa>();+ jit.make("QSA_KV_WRITE_KCHANNEL", 1);+ jit.make("QSA_KV_HEADS", desc->num_kv_heads);+ jit.make("QSA_K_HEAD_SIZE", desc->k_head_size);+ jit.make("QSA_PAGE_SIZE", page_size_of(params));+ jit.make("QSA_COMPRESS_RATIO", desc->key_block_size);+ qsa::add_cache_jit(jit, "K", desc->key_quant, page_size_of(params), desc->k_head_size);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ Arguments args;+ for (auto idx : {SparsePAIn::KEY,+ SparsePAIn::PAST_LENS,+ SparsePAIn::BLOCK_INDICES,+ SparsePAIn::BLOCK_INDICES_BEGINS,+ SparsePAIn::SUBSEQUENCE_BEGINS,+ SparsePAIn::KEY_CACHE}) {+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)});+ }+ for (uint32_t i = 0; i < 3; i++) {+ args.push_back({ArgumentDescriptor::Types::SCALAR, i});+ }+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<sparse_pa>();+ auto* rtp = static_cast<qsa::SparseAttentionRuntimeParams*>(rt);+ OPENVINO_ASSERT(rtp != nullptr, "[GPU][OCL] sparse_pa runtime params are not initialized");+ const auto sg = qsa::subgroup_size(params.get_device_info());++ // A sequence touches at most tokens / group + 2 groups (one partial group at each end).+ const size_t group = desc->key_quant.group_size;+ const size_t work_items = rtp->num_tokens / group + 2 * rtp->num_seqs;+ auto& wgs = kd.params.workGroups;+ wgs.global = {std::max<size_t>(1, work_items) * sg, desc->num_kv_heads, 1};+ wgs.local = {sg, 1, 1};++ kd.params.scalars.clear();+ qsa::push_u32(kd, token_pitch(params.get_input_layout(SparsePAIn::KEY)));+ qsa::push_u32(kd, params.get_input_layout(SparsePAIn::KEY).get_linear_offset());+ qsa::push_u32(kd, rtp->num_seqs);+ }};+ }+};++class SparsePAImpl : public PrimitiveImplOCL {+public:+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::SparsePAImpl)++ Stage::Ptr kv_write = make_stage<KvWriteGenerator>();+ Stage::Ptr kv_write_kchannel = make_stage<KvWriteKChannelGenerator>();+ Stage::Ptr attention = make_stage<Gen>(qsa::AttKind::Scalar, pa_slots());+ Stage::Ptr attention_dpas = make_stage<Gen>(qsa::AttKind::Dpas, pa_slots());+ Stage::Ptr attention_gqa_dpas = make_stage<Gen>(qsa::AttKind::Gqa, pa_slots());+ Stage::Ptr attention_gqa_split = make_stage<Gen>(qsa::AttKind::GqaSplit, pa_slots());+ Stage::Ptr split = make_stage<Gen>(qsa::AttKind::Split, pa_slots());+ Stage::Ptr split_reduce = make_stage<Gen>(qsa::AttKind::Reduce, pa_slots());++ SparsePAImpl() : PrimitiveImplOCL(SparsePAImplementationManager::get_type_info_static()) {+ m_rt_params = std::make_unique<qsa::SparseAttentionRuntimeParams>();+ }++ qsa::SparseAttentionRuntimeParams& rt() {+ if (m_rt_params == nullptr) {+ m_rt_params = std::make_unique<qsa::SparseAttentionRuntimeParams>();+ }+ return *static_cast<qsa::SparseAttentionRuntimeParams*>(m_rt_params.get());+ }++ explicit SparsePAImpl(const RuntimeParams& params) : SparsePAImpl() {+ const auto desc = params.typed_desc<sparse_pa>();+ add_stage(kv_write, params);+ if (desc->key_quant.mode == ov::intel_gpu::op::KVQuant::Mode::BY_CHANNEL) {+ add_stage(kv_write_kchannel, params);+ }+ add_stage(attention, params);+ if (use_gqa_dpas_attention(params)) {+ add_stage(attention_gqa_dpas, params);+ if (may_decode(params)) {+ add_stage(attention_gqa_split, params);+ add_stage(split_reduce, params);+ }+ } else if (!desc->key_quant.enabled() && !desc->value_quant.enabled()) {+ // The plain systolic and split kernels only read f16 caches; quantized pages use the scalar kernel here.+ if (use_dpas_attention(params)) {+ add_stage(attention_dpas, params);+ }+ if (may_decode(params)) {+ add_stage(split, params);+ add_stage(split_reduce, params);+ }+ }+ }++ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {+ return make_deep_copy<SparsePAImpl>(this);+ }++ [[nodiscard]] bool requires_update(primitive_inst& /*inst*/, const kernel_impl_params& /*impl_params*/) const override {+ return true;+ }++ static bool use_dpas_attention(const kernel_impl_params& params) {+ return qsa::can_use_dpas_attention(*params.typed_desc<sparse_pa>(), page_size_of(params), params.get_device_info());+ }+ static bool use_gqa_dpas_attention(const kernel_impl_params& params) {+ return qsa::can_use_gqa_dpas_attention(*params.typed_desc<sparse_pa>(), page_size_of(params), params.get_device_info());+ }++ // Split-selected-KV is only a decode fallback for configs without the GQA systolic kernel.+ bool use_split_attention() {+ return has_stage(split) && rt().is_decode;+ }++ [[nodiscard]] std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& params) const override {+ if (params.is_dynamic()) {+ return {};+ }+ const auto tokens = std::max<size_t>(1, params.get_input_layout(SparsePAIn::QUERY).get_shape()[0]);+ const auto desc = params.typed_desc<sparse_pa>();++ std::vector<BufferDescriptor> bufs;+ // Only decode-shaped calls dispatch the split kernels, where `tokens` equals the (small) sequence count.+ const auto split_rows = is_decode_shape(params) ? tokens : size_t{1};+ const auto partitions = qsa::decode_split_partitions(*desc, page_size_of(params), params.get_device_info());+ bufs.emplace_back(split_rows * desc->num_heads * partitions * desc->v_head_size, ov::element::f32); // SPLIT_ACC+ bufs.emplace_back(split_rows * desc->num_heads * partitions * 2, ov::element::f32); // SPLIT_ML+ return bufs;+ }++ event::ptr run_stage(const std::vector<event::ptr>& deps, primitive_inst& instance, Stage::Ptr& stage) {+ return qsa::QsaStageEvents::record(execute_stage(deps, instance, stage));+ }++ event::ptr execute(const std::vector<event::ptr>& events, primitive_inst& instance) override {+ kernel_dump_info.clear_entries();+ update_rt_params(instance);++ // The attention stages read the cache the K/V write just produced, so they wait for both the input events and+ // the write(s).+ auto kv_event = run_stage(events, instance, kv_write);+ std::vector<event::ptr> attn_deps = events;+ attn_deps.push_back(kv_event);+ if (has_stage(kv_write_kchannel)) {+ attn_deps.push_back(run_stage(events, instance, kv_write_kchannel));+ }++ const auto& params = *instance.get_impl_params();+ if (use_gqa_dpas_attention(params)) {+ if (has_stage(attention_gqa_split) && rt().is_decode) {+ auto split_event = run_stage(attn_deps, instance, attention_gqa_split);+ return run_stage({split_event}, instance, split_reduce);+ }+ return run_stage(attn_deps, instance, attention_gqa_dpas);+ }+ if (use_split_attention()) {+ auto split_event = run_stage(attn_deps, instance, split);+ return run_stage({split_event}, instance, split_reduce);+ }+ // Plain dpas needs a multi-token query tile; decode keeps the scalar kernel.+ if (has_stage(attention_dpas) && !rt().is_decode) {+ return run_stage(attn_deps, instance, attention_dpas);+ }+ return run_stage(attn_deps, instance, attention);+ }++ void update_rt_params(const primitive_inst& instance) override {+ update_stages_flags(instance);+ qsa::force_stages_refresh(*this);+ auto* rtp = &rt();++ const auto& params = *instance.get_impl_params();+ const auto& q_layout = params.get_input_layout(SparsePAIn::QUERY);+ rtp->num_seqs = params.get_input_layout(SparsePAIn::PAST_LENS).get_shape()[0];+ rtp->num_tokens = q_layout.get_shape()[0];+ rtp->is_decode = is_decode_shape(params);+ // At most tokens / 16 + num_seqs query tiles (a tile never straddles two sequences).+ rtp->tile_count = rtp->num_tokens / qsa::dpas_query_tile + rtp->num_seqs;+ rtp->q_base = q_layout.get_linear_offset();+ rtp->q_pitch = token_pitch(q_layout);+ }+};++} // namespace++bool SparsePAImplementationManager::validate_impl(const cldnn::program_node& node) const {+ assert(node.is_type<cldnn::sparse_pa>());++ if (node.has_fused_primitives()) {+ return false;+ }++ const auto& info = node.get_program().get_engine().get_device_info();+ if (!qsa::subgroups_available(info)) {+ return false;+ }++ const auto desc = node.as<cldnn::sparse_pa>().get_primitive();+ std::string reason;+ if (!cldnn::sparse_pa::validate_config(desc->get_config(), reason)) {+ return false;+ }++ // Single selection head; head rows must be 16-byte aligned and tile the subgroup.+ const size_t sg = qsa::subgroup_size(info);+ if (desc->num_selection_heads != 1 || desc->k_head_size % std::max<size_t>(16, sg) != 0 || desc->v_head_size % std::max<size_t>(16, sg) != 0) {+ return false;+ }++ const auto& key_cache_ps = node.get_input_layout(SparsePAIn::KEY_CACHE).get_partial_shape();+ const size_t page = desc->page_size != 0+ ? desc->page_size+ : (key_cache_ps.size() == 4 && key_cache_ps[2].is_static() ? static_cast<size_t>(key_cache_ps[2].get_length()) : 0);+ if (key_cache_ps.size() != 4 || page == 0 || page % desc->key_block_size != 0) {+ return false;+ }++ static constexpr std::array f16_inputs = {SparsePAIn::QUERY, SparsePAIn::KEY, SparsePAIn::VALUE};+ for (auto idx : f16_inputs) {+ if (node.get_input_layout(idx).data_type != ov::element::f16) {+ return false;+ }+ }+ // A quantized cache is a u8 page tensor, an f16 cache keeps the f16 layout.+ if (node.get_input_layout(SparsePAIn::KEY_CACHE).data_type != (desc->key_quant.enabled() ? ov::element::u8 : ov::element::f16) ||+ node.get_input_layout(SparsePAIn::VALUE_CACHE).data_type != (desc->value_quant.enabled() ? ov::element::u8 : ov::element::f16)) {+ return false;+ }+ return node.get_input_layout(SparsePAIn::SELECTED_BLOCK_INDICES).data_type == ov::element::i32 &&+ node.get_input_layout(SparsePAIn::SELECTED_BLOCK_COUNT).data_type == ov::element::i32;+}++std::unique_ptr<cldnn::primitive_impl> SparsePAImplementationManager::create_impl(const cldnn::program_node& node,+ const cldnn::kernel_impl_params& params) const {+ OPENVINO_ASSERT(node.is_type<cldnn::sparse_pa>());+ return std::make_unique<SparsePAImpl>(params);+}++} // namespace ov::intel_gpu::ocl++BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::SparsePAImpl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_pa.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_pa.hppnew file mode 100644index 00000000000..b2ac4f70732--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_pa.hpp@@ -0,0 +1,39 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <memory>+#include <utility>+#include <vector>++#include "common_utils/kernel_generator_base.hpp"+#include "intel_gpu/runtime/layout.hpp"+#include "program_node.h"+#include "registry/implementation_manager.hpp"+#include "sparse_pa_inst.h"++namespace ov::intel_gpu::ocl {++/// @brief OpenCL implementation of the SparsePA primitive: Q0 (K/V cache write) + Q3 (selected-block attention with the+/// automatically derived causal tail). Q0 writes directly into the caller-owned KEY_CACHE/VALUE_CACHE inputs and Q3+/// reads the paired indexer's selection inputs directly.+struct SparsePAImplementationManager : public cldnn::ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("ocl::sparse_pa")+ explicit SparsePAImplementationManager(cldnn::shape_types shape_type, cldnn::ValidateFunc vf = nullptr)+ : ImplementationManager(cldnn::impl_types::ocl, shape_type, std::move(vf)) {}++ [[nodiscard]] std::unique_ptr<cldnn::primitive_impl> create_impl(const cldnn::program_node& node, const cldnn::kernel_impl_params& params) const override;++ [[nodiscard]] cldnn::in_out_fmts_t query_formats(const cldnn::program_node& node) const override {+ std::vector<cldnn::format::type> in_fmts(node.get_dependencies().size(), cldnn::format::bfyx);+ std::vector<cldnn::format::type> out_fmts(node.get_outputs_count(), cldnn::format::bfyx);+ return {in_fmts, out_fmts};+ }++ [[nodiscard]] bool validate_impl(const cldnn::program_node& node) const override;+};++} // namespace ov::intel_gpu::ocldiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_sdpa.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_sdpa.cppnew file mode 100644index 00000000000..b2fdf484417--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_sdpa.cpp@@ -0,0 +1,301 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "sparse_sdpa.hpp"++#include <algorithm>+#include <array>+#include <cassert>+#include <memory>+#include <string>+#include <tuple>+#include <vector>++#include "../primitive_ocl_base.hpp"+#include "../qsa_host_common.hpp"+#include "../qsa_stage_events.hpp"+#include "common_utils/jitter.hpp"+#include "intel_gpu/graph/kernel_impl_params.hpp"+#include "intel_gpu/primitives/kv_cache.hpp"+#include "intel_gpu/primitives/sparse_sdpa.hpp"+#include "primitive_inst.h"+#include "sparse_attention_common.hpp"++namespace ov::intel_gpu::ocl {++using namespace cldnn;+using SparseSDPAIn = ov::intel_gpu::op::SparseSDPA::InputIdx;++namespace {++// Decode for the dense op is L == 1; below this history the scalar kernel wins over the split pair.+constexpr size_t split_decode_min_past = 2048;++qsa::SparseAttentionSlots sdpa_slots() {+ qsa::SparseAttentionSlots s;+ s.paged = false;+ s.query = SparseSDPAIn::QUERY;+ s.key = SparseSDPAIn::KEY;+ s.value = SparseSDPAIn::VALUE;+ s.selected_blocks = SparseSDPAIn::SELECTED_BLOCK_INDICES;+ s.selected_count = SparseSDPAIn::SELECTED_BLOCK_COUNT;+ s.key_length = SparseSDPAIn::KEY_LENGTH;+ s.kv_params = {sparse_sdpa::InputIdx::KEY_SCALE, sparse_sdpa::InputIdx::VALUE_SCALE, sparse_sdpa::InputIdx::KEY_ZP, sparse_sdpa::InputIdx::VALUE_ZP};+ return s;+}++bool is_decode_shape(const kernel_impl_params& params) {+ const auto& q_layout = params.get_input_layout(SparseSDPAIn::QUERY);+ if (q_layout.is_dynamic()) {+ return false;+ }+ const auto& shape = q_layout.get_shape();+ OPENVINO_ASSERT(shape.size() == 4, "[GPU][OCL] sparse_sdpa expects a rank-4 [B,H,*,D] query input");+ return shape[2] == 1;+}++bool may_decode(const kernel_impl_params& params) {+ return params.is_dynamic() || is_decode_shape(params);+}++/// Allocated sequence pitch of a [B, H, S, D] K/V input. KVCache hands its consumers a buffer with dynamic upper padding+/// on S, so this can exceed the logical S.+size_t seq_pitch(const layout& l, const char* name) {+ const auto& pad = l.data_padding;+ for (size_t axis : {size_t{0}, size_t{1}, size_t{3}}) {+ OPENVINO_ASSERT(pad._lower_size[axis] == 0 && pad._upper_size[axis] == 0,+ "[GPU][OCL] sparse_sdpa: ",+ name,+ " padding is only supported on the sequence axis, got ",+ l.to_short_string());+ }+ OPENVINO_ASSERT(pad._lower_size[2] == 0, "[GPU][OCL] sparse_sdpa: ", name, " lower sequence padding is not supported, got ", l.to_short_string());+ return l.get_shape()[2] + static_cast<size_t>(pad._upper_size[2]);+}++using Gen = qsa::AttentionGenerator<sparse_sdpa>;++class SparseSDPAImpl : public PrimitiveImplOCL {+public:+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::SparseSDPAImpl)++ Stage::Ptr attention = make_stage<Gen>(qsa::AttKind::Scalar, sdpa_slots());+ Stage::Ptr attention_dpas = make_stage<Gen>(qsa::AttKind::Dpas, sdpa_slots());+ Stage::Ptr attention_gqa_dpas = make_stage<Gen>(qsa::AttKind::Gqa, sdpa_slots());+ Stage::Ptr attention_gqa_split = make_stage<Gen>(qsa::AttKind::GqaSplit, sdpa_slots());+ Stage::Ptr split = make_stage<Gen>(qsa::AttKind::Split, sdpa_slots());+ Stage::Ptr split_reduce = make_stage<Gen>(qsa::AttKind::Reduce, sdpa_slots());++ SparseSDPAImpl() : PrimitiveImplOCL(SparseSDPAImplementationManager::get_type_info_static()) {+ m_rt_params = std::make_unique<qsa::SparseAttentionRuntimeParams>();+ }++ qsa::SparseAttentionRuntimeParams& rt() {+ if (m_rt_params == nullptr) {+ m_rt_params = std::make_unique<qsa::SparseAttentionRuntimeParams>();+ }+ return *static_cast<qsa::SparseAttentionRuntimeParams*>(m_rt_params.get());+ }++ explicit SparseSDPAImpl(const RuntimeParams& params) : SparseSDPAImpl() {+ add_stage(attention, params);+ if (use_gqa_dpas_attention(params)) {+ add_stage(attention_gqa_dpas, params);+ if (may_decode(params)) {+ add_stage(attention_gqa_split, params);+ add_stage(split_reduce, params);+ }+ } else if (!params.typed_desc<sparse_sdpa>()->kv_compressed()) {+ // The plain systolic and split kernels only read f16 K/V; compressed K/V use the scalar kernel here.+ if (use_dpas_attention(params)) {+ add_stage(attention_dpas, params);+ }+ if (may_decode(params)) {+ add_stage(split, params);+ add_stage(split_reduce, params);+ }+ }+ }++ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {+ return make_deep_copy<SparseSDPAImpl>(this);+ }++ void update(primitive_inst& inst, const kernel_impl_params& impl_params) override {+ update_rt_params(inst);+ PrimitiveImplOCL::update(inst, impl_params);+ }++ [[nodiscard]] bool requires_update(primitive_inst& /*inst*/, const kernel_impl_params& /*impl_params*/) const override {+ return true;+ }++ static bool use_dpas_attention(const kernel_impl_params& params) {+ return qsa::can_use_dpas_attention(*params.typed_desc<sparse_sdpa>(), std::nullopt, params.get_device_info());+ }+ static bool use_gqa_dpas_attention(const kernel_impl_params& params) {+ return qsa::can_use_gqa_dpas_attention(*params.typed_desc<sparse_sdpa>(), std::nullopt, params.get_device_info());+ }++ // Split-selected-KV is only a decode fallback for configs without the GQA systolic kernel.+ bool use_split_attention() {+ return has_stage(split) && rt().is_decode && rt().history_len >= split_decode_min_past;+ }++ [[nodiscard]] std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& params) const override {+ if (params.is_dynamic()) {+ return {};+ }+ const auto& query_shape = params.get_input_layout(SparseSDPAIn::QUERY).get_shape();+ const auto batch = std::max<size_t>(1, query_shape[0]);+ const auto seq_len = std::max<size_t>(1, query_shape[2]);+ const auto desc = params.typed_desc<sparse_sdpa>();++ std::vector<BufferDescriptor> bufs;+ // Only decode-shaped calls dispatch the split kernels, where batch * seq_len == batch is small.+ const auto split_rows = is_decode_shape(params) ? batch * seq_len : size_t{1};+ const auto partitions = qsa::decode_split_partitions(*desc, std::nullopt, params.get_device_info());+ bufs.emplace_back(split_rows * desc->num_heads * partitions * desc->v_head_size, ov::element::f32); // SPLIT_ACC+ bufs.emplace_back(split_rows * desc->num_heads * partitions * 2, ov::element::f32); // SPLIT_ML+ return bufs;+ }++ event::ptr run_stage(const std::vector<event::ptr>& deps, primitive_inst& instance, Stage::Ptr& stage) {+ return qsa::QsaStageEvents::record(execute_stage(deps, instance, stage));+ }++ event::ptr execute(const std::vector<event::ptr>& events, primitive_inst& instance) override {+ kernel_dump_info.clear_entries();+ update_rt_params(instance);+ const auto& params = *instance.get_impl_params();+ if (use_gqa_dpas_attention(params)) {+ if (has_stage(attention_gqa_split) && rt().is_decode) {+ auto split_event = run_stage(events, instance, attention_gqa_split);+ return run_stage({split_event}, instance, split_reduce);+ }+ return run_stage(events, instance, attention_gqa_dpas);+ }+ if (use_split_attention()) {+ auto split_event = run_stage(events, instance, split);+ return run_stage({split_event}, instance, split_reduce);+ }+ // Plain dpas needs a multi-token query tile; decode keeps the scalar kernel.+ if (has_stage(attention_dpas) && !rt().is_decode) {+ return run_stage(events, instance, attention_dpas);+ }+ return run_stage(events, instance, attention);+ }++ void update_rt_params(const primitive_inst& instance) override {+ update_stages_flags(instance);+ qsa::force_stages_refresh(*this);+ auto* rtp = &rt();++ const auto& params = *instance.get_impl_params();+ const auto& query_shape = params.get_input_layout(SparseSDPAIn::QUERY).get_shape();+ const auto& key_shape = params.get_input_layout(SparseSDPAIn::KEY).get_shape();+ OPENVINO_ASSERT(query_shape.size() == 4 && key_shape.size() == 4, "[GPU][OCL] sparse_sdpa expects rank-4 [B,H,*,D] query/key inputs");+ OPENVINO_ASSERT(!params.get_input_layout(SparseSDPAIn::QUERY).data_padding && !params.get_output_layout(0).data_padding,+ "[GPU][OCL] sparse_sdpa: padded query/output buffers are not supported");++ rtp->batch = query_shape[0];+ rtp->seq_len = query_shape[2];+ rtp->history_len = key_shape[2];+ rtp->num_tokens = rtp->batch * rtp->seq_len;+ rtp->k_seq_pitch = seq_pitch(params.get_input_layout(SparseSDPAIn::KEY), "key");+ rtp->v_seq_pitch = seq_pitch(params.get_input_layout(SparseSDPAIn::VALUE), "value");+ if (params.typed_desc<sparse_sdpa>()->kv_compressed()) {+ using CI = sparse_sdpa::InputIdx;+ // Data and parameter tensors of a KVCache are padded independently, so each keeps its own pitch.+ rtp->k_param_pitch = seq_pitch(params.get_input_layout(CI::KEY_SCALE), "key_scale");+ rtp->v_param_pitch = seq_pitch(params.get_input_layout(CI::VALUE_SCALE), "value_scale");+ if (!params.typed_desc<sparse_sdpa>()->key_quant.symmetric) {+ OPENVINO_ASSERT(seq_pitch(params.get_input_layout(CI::KEY_ZP), "key_zp") == rtp->k_param_pitch &&+ seq_pitch(params.get_input_layout(CI::VALUE_ZP), "value_zp") == rtp->v_param_pitch,+ "[GPU][OCL] sparse_sdpa: a zero-point tensor must share the sequence padding of its scale tensor");+ }+ }+ rtp->is_decode = rtp->seq_len == 1;+ rtp->tile_count = rtp->batch * ((rtp->seq_len + qsa::dpas_query_tile - 1) / qsa::dpas_query_tile);+ }+};++} // namespace++bool SparseSDPAImplementationManager::validate_impl(const cldnn::program_node& node) const {+ assert(node.is_type<cldnn::sparse_sdpa>());++ if (node.has_fused_primitives()) {+ return false;+ }++ const auto& info = node.get_program().get_engine().get_device_info();+ if (!qsa::subgroups_available(info)) {+ return false;+ }++ const auto desc = node.as<cldnn::sparse_sdpa>().get_primitive();+ std::string reason;+ if (!ov::intel_gpu::op::SparseSDPA::validate_config(desc->get_config(), reason)) {+ return false;+ }++ // Every dense kernel adds the causal tail and applies the causal bound; head rows must be 16-byte aligned and tile+ // the subgroup.+ const size_t sg = qsa::subgroup_size(info);+ if (desc->num_selection_heads != 1 || !desc->causal || desc->k_head_size % std::max<size_t>(16, sg) != 0 ||+ desc->v_head_size % std::max<size_t>(16, sg) != 0) {+ return false;+ }++ if (node.get_input_layout(SparseSDPAIn::QUERY).data_type != ov::element::f16) {+ return false;+ }+ const auto kv_type = desc->kv_compressed() ? ov::element::i8 : ov::element::f16;+ if (node.get_input_layout(SparseSDPAIn::KEY).data_type != kv_type || node.get_input_layout(SparseSDPAIn::VALUE).data_type != kv_type) {+ return false;+ }+ if (desc->kv_compressed()) {+ using CI = sparse_sdpa::InputIdx;+ // 4-bit data rows are packed two codes per byte: the last dimension holds the row bytes.+ const std::array<std::tuple<size_t, const ov::intel_gpu::op::KVQuant*, size_t>, 2> caches = {+ std::tuple{SparseSDPAIn::KEY, &desc->key_quant, desc->k_head_size},+ std::tuple{SparseSDPAIn::VALUE, &desc->value_quant, desc->v_head_size}};+ for (const auto& [idx, quant, head_size] : caches) {+ const auto& ps = node.get_input_layout(idx).get_partial_shape();+ if (ps.size() != 4 || (ps[3].is_static() && static_cast<size_t>(ps[3].get_length()) != ov::intel_gpu::op::dense_row_bytes(*quant, head_size))) {+ return false;+ }+ }+ if (node.get_input_layout(CI::KEY_SCALE).data_type != ov::element::f16 || node.get_input_layout(CI::VALUE_SCALE).data_type != ov::element::f16) {+ return false;+ }+ if (!desc->key_quant.symmetric) {+ const auto zp_type = [](const ov::intel_gpu::op::KVQuant& q) {+ return ov::intel_gpu::op::dense_zp_is_f16(q) ? ov::element::f16 : ov::element::i8;+ };+ if (node.get_input_layout(CI::KEY_ZP).data_type != zp_type(desc->key_quant) ||+ node.get_input_layout(CI::VALUE_ZP).data_type != zp_type(desc->value_quant)) {+ return false;+ }+ }+ }+ static constexpr std::array i32_inputs = {SparseSDPAIn::SELECTED_BLOCK_INDICES, SparseSDPAIn::SELECTED_BLOCK_COUNT, SparseSDPAIn::KEY_LENGTH};+ for (auto idx : i32_inputs) {+ if (node.get_input_layout(idx).data_type != ov::element::i32) {+ return false;+ }+ }+ return true;+}++std::unique_ptr<cldnn::primitive_impl> SparseSDPAImplementationManager::create_impl(const cldnn::program_node& node,+ const cldnn::kernel_impl_params& params) const {+ OPENVINO_ASSERT(node.is_type<cldnn::sparse_sdpa>());+ return std::make_unique<SparseSDPAImpl>(params);+}++} // namespace ov::intel_gpu::ocl++BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::SparseSDPAImpl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_sdpa.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_sdpa.hppnew file mode 100644index 00000000000..4de63b10b36--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention/sparse_sdpa.hpp@@ -0,0 +1,37 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <memory>+#include <utility>+#include <vector>++#include "common_utils/kernel_generator_base.hpp"+#include "intel_gpu/runtime/layout.hpp"+#include "program_node.h"+#include "registry/implementation_manager.hpp"+#include "sparse_sdpa_inst.h"++namespace ov::intel_gpu::ocl {++/// @brief OpenCL implementation of the SparseSDPA primitive: selected-block attention over dense, read-only K/V.+struct SparseSDPAImplementationManager : public cldnn::ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("ocl::sparse_sdpa")+ explicit SparseSDPAImplementationManager(cldnn::shape_types shape_type, cldnn::ValidateFunc vf = nullptr)+ : ImplementationManager(cldnn::impl_types::ocl, shape_type, std::move(vf)) {}++ [[nodiscard]] std::unique_ptr<cldnn::primitive_impl> create_impl(const cldnn::program_node& node, const cldnn::kernel_impl_params& params) const override;++ [[nodiscard]] cldnn::in_out_fmts_t query_formats(const cldnn::program_node& node) const override {+ std::vector<cldnn::format::type> in_fmts(node.get_dependencies().size(), cldnn::format::bfyx);+ std::vector<cldnn::format::type> out_fmts(node.get_outputs_count(), cldnn::format::bfyx);+ return {in_fmts, out_fmts};+ }++ [[nodiscard]] bool validate_impl(const cldnn::program_node& node) const override;+};++} // namespace ov::intel_gpu::ocldiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_dpas.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_dpas.clnew file mode 100644index 00000000000..0cb26b58a41--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_dpas.cl@@ -0,0 +1,293 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q3 prefill, systolic sparse attention over the union of several tokens' selections, shared by SparsePA (QSA_ADDRESS_MODE 0) and SparseSDPA (1).+//+// The lane axis of the XMX tile is filled with QSA_HEADS_PER_TILE (HT) heads x TT = 16 / HT tokens, head-major+// (lane = head * TT + token), so a tile only needs the UNION of TT per-token selections. The union is produced by a+// TT-way merge of the ascending per-token lists, done in parallel by the lanes < TT with subgroup reductions+// (lane t is the cursor of token t). A work-group is QSA_ATT_WORKERS subgroups splitting Dh / Dv; their QK partial+// tiles are summed through SLM in a fixed order. The XMX operand mapping is documented in qsa_common.cl.+//+// JIT: QSA_HEADS, QSA_KV_HEADS, QSA_K_HEAD_SIZE, QSA_V_HEAD_SIZE, QSA_COMPRESS_RATIO, QSA_BLOCK_TOPK, QSA_SCALE,+// QSA_ATT_WORKERS, QSA_HEADS_PER_TILE, QSA_ADDRESS_MODE, SUBGROUP_SIZE, (paged) QSA_PAGE_SIZE+// Dispatch: gws = [(QSA_HEADS / HT) * W * SG, tiles * HT, 1], lws = [W * SG, 1, 1]++#define QSA_XMX_WORKERS QSA_ATT_WORKERS+#define QSA_ATTENTION_HELPERS+#include "qsa_common.cl"++#if SUBGROUP_SIZE != 16+# error "the systolic attention needs a 16-wide subgroup"+#endif++#define DPAS_HT QSA_HEADS_PER_TILE+#define DPAS_TT (16 / QSA_HEADS_PER_TILE)+#define DPAS_BLOCKS (16 / QSA_COMPRESS_RATIO)++#if (QSA_K_HEAD_SIZE % (QSA_XW * 16)) != 0 || (QSA_V_HEAD_SIZE % (QSA_XW * 16)) != 0+# error "head sizes must split evenly into per-worker XMX tiles"+#endif++// Applies one KV step to the online-softmax state of every column. `keep` bit i says whether row i is visible to+// this lane's column; hidden rows get zero weight.+inline void FUNC(qsa_dpas_softmax_pv)(const __global half* value_cache,+ const uint voff,+ const bool lv,+ const uint keep,+ __private float* st,+ const uint worker,+ __private float* running_max,+ __private float* running_sum,+ __private float8* ro) {+ unroll_for (uint i = 0; i < 16; i++) {+ st[i] = ((keep >> i) & 1u) ? st[i] : QSA_NEG_INF;+ }+ float tile_max = st[0];+ unroll_for (uint i = 1; i < 16; i++) {+ tile_max = fmax(tile_max, st[i]);+ }+ const float new_max = fmax(*running_max, tile_max);+ const float corr = native_exp2(*running_max - new_max);+ float p[16];+ float tile_sum = 0.0f;+ unroll_for (uint i = 0; i < 16; i++) {+ const float e = native_exp2(st[i] - new_max);+ p[i] = st[i] <= QSA_NEG_INF ? 0.0f : e;+ tile_sum += p[i];+ }+ *running_sum = *running_sum * corr + tile_sum;+ *running_max = new_max;+ unroll_for (uint d = 0; d < QSA_XVT; d++) {+ ro[d] *= corr;+ }+ FUNC_CALL(qsa_xmx_pv)(value_cache, voff, lv, p, worker, ro);+}++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(sparse_attention_dpas)(QSA_ATT_INPUT_ARGS,+ __global half* output, // paged: [tokens, Hq*Dv]; dense: [B, Hq, L, Dv]+#if QSA_ADDRESS_MODE == 0+ const uint num_tiles,+ const uint num_seqs,+ const uint q_base,+ const uint q_pitch+#else+ const uint num_tiles,+ const uint seq_len,+ const uint history_len,+ const uint k_pitch,+ const uint v_pitch+#endif+) {+ const uint HQ = QSA_HEADS;+ const uint HKV = QSA_KV_HEADS;+ const uint DH = QSA_K_HEAD_SIZE;+ const uint DV = QSA_V_HEAD_SIZE;+ const uint R = QSA_COMPRESS_RATIO;+ const uint K_TOPK = QSA_BLOCK_TOPK;+ const uint TT = DPAS_TT;++#if QSA_XW > 1+ __local float slm_st[2][QSA_XW][2][8][QSA_SG];+ uint st_buf = 0;+#endif++ const uint worker = get_sub_group_id();+ const uint lane = get_sub_group_local_id();+ const uint head_group = get_group_id(0);+ const uint tile = get_group_id(1) / DPAS_HT;+ const uint sub = get_group_id(1) % DPAS_HT;+ if (head_group >= HQ / DPAS_HT || tile >= num_tiles) {+ return;+ }+ const uint head_base = head_group * DPAS_HT;+ // All heads of the group share one KV head - that is what makes the tile legal.+ const uint kv_head = head_base / (HQ / HKV);++ const uint col_tok = lane % TT;+ const uint col_head = lane / TT;++#if QSA_ADDRESS_MODE == 0+ uint seq = 0, tile_begin = 0;+ if (!FUNC_CALL(qsa_resolve_tile_paged)(subsequence_begins, num_seqs, tile, 16, &seq, &tile_begin)) {+ return;+ }+ const uint token0 = tile_begin + sub * TT;+ const uint seq_begin = (uint)subsequence_begins[seq];+ const uint seq_end = (uint)subsequence_begins[seq + 1];+ const uint past_len = (uint)past_lens[seq];+ const uint page_begin = (uint)block_indices_begins[seq];+ uint valid = seq_end > token0 ? seq_end - token0 : 0;+ if (valid > TT) {+ valid = TT;+ }+ if (valid == 0) {+ return;+ }+ const uint first_abs = past_len + token0 - seq_begin;+ const uint abs_pos = col_tok + first_abs;+ const bool lane_valid = col_tok < valid;+ const uint sel_row0 = token0;+ const uint tail_begin = (first_abs + 1) / R * R;+ const uint tail_end = first_abs + valid - 1;+ const uint q_col = q_base + (token0 + col_tok) * q_pitch + (head_base + col_head) * DH;+ const uint out_col = ((token0 + col_tok) * HQ + head_base + col_head) * DV;+ const bool tok_ok = lane < valid;+#else+ const uint tiles_per_row = (seq_len + 16 - 1) / 16;+ const uint batch = tile / tiles_per_row;+ const uint tile_begin = (tile % tiles_per_row) * 16;+ const uint token0 = tile_begin + sub * TT;+ uint valid = seq_len > token0 ? seq_len - token0 : 0;+ if (valid > TT) {+ valid = TT;+ }+ if (valid == 0) {+ return;+ }+ uint kl = (uint)key_length[batch];+ kl = kl < history_len ? kl : history_len;+ const uint shift = history_len - kl;+ const uint pad_q = seq_len - (kl < seq_len ? kl : seq_len);+ const uint abs_pos = col_tok + token0 + kl - seq_len;+ const bool lane_valid = (col_tok < valid) && (col_tok + token0 >= pad_q);+ const uint first_l = token0 > pad_q ? token0 : pad_q;+ const bool any_real = token0 + valid > pad_q;+ const uint sel_row0 = batch * seq_len + token0;+ const uint tail_begin = any_real ? (first_l + kl + 1 - seq_len) / R * R : 1;+ const uint tail_end = any_real ? token0 + valid - 1 + kl - seq_len : 0;+ const uint q_col = (((batch * HQ) + head_base + col_head) * seq_len + token0 + col_tok) * DH;+ const uint out_col = (((batch * HQ) + head_base + col_head) * seq_len + token0 + col_tok) * DV;+ const bool tok_ok = lane < valid && lane + token0 >= pad_q;+#endif+ const uint n_complete = (abs_pos + 1) / R;++ // Q as the B operand: the lane's own (head, token) row slice, pre-scaled by scale * log2(e) in half.+ int8 rq[QSA_XKT];+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ half16 qh = (half16)((half)0.0f);+ if (col_tok < valid) {+ qh = vload16(0, query + q_col + worker * QSA_XDH + k * 16);+ }+ qh = qh * (half)((float)QSA_SCALE * QSA_LOG2E);+ rq[k] = as_int8(qh);+ }++ float running_max = QSA_NEG_INF;+ float running_sum = 0.0f;+ float8 ro[QSA_XVT];+ unroll_for (uint d = 0; d < QSA_XVT; d++) {+ ro[d] = (float8)(0.0f);+ }++ // Lane t < TT owns the ascending selected list of token t.+ int cnt_l = 0;+ int cur_l = 0;+ int hv = 0x7fffffff;+ if (lane < TT && tok_ok) {+ cnt_l = selected_counts[sel_row0 + lane];+ if (cnt_l > 0) {+ hv = selected_blocks[(sel_row0 + lane) * K_TOPK];+ }+ }++ const uint lane_blk = lane / R;+ const uint lane_rr = lane % R;+ const uint row_mask = (1u << R) - 1u;++ for (;;) {+ // ---- pack the next DPAS_BLOCKS union blocks (minimum over the TT cursor heads) ----+ int blk[DPAS_BLOCKS];+ uint msk[DPAS_BLOCKS];+ bool have = true;+ unroll_for (uint j = 0; j < DPAS_BLOCKS; j++) {+ blk[j] = -1;+ msk[j] = 0;+ if (have) {+ const int next = sub_group_reduce_min(hv);+ if (next == 0x7fffffff) {+ have = false;+ } else {+ const bool sel = hv == next;+ msk[j] = sub_group_reduce_add(sel ? (1u << lane) : 0u);+ blk[j] = next;+ if (sel) {+ cur_l++;+ hv = cur_l < cnt_l ? selected_blocks[(sel_row0 + lane) * K_TOPK + cur_l] : 0x7fffffff;+ }+ }+ }+ }+ if (blk[0] < 0) {+ break;+ }+ const bool exhausted = blk[DPAS_BLOCKS - 1] < 0;++ // Lane = KV row of this step; a row is visible to a column iff that column's token selected its block.+ int bl = -1;+ uint keep = 0;+ unroll_for (uint j = 0; j < DPAS_BLOCKS; j++) {+ bl = lane_blk == j ? blk[j] : bl;+ keep |= (lane_valid && ((msk[j] >> col_tok) & 1u)) ? (row_mask << (j * R)) : 0u;+ }+ const bool lv = bl >= 0;+ const uint pos = (uint)bl * R + lane_rr;+ uint koff = 0, voff = 0;+ if (lv) {+ koff = QSA_KROW(pos);+ voff = QSA_VROW(pos);+ }+ const uint valid_kv = sub_group_reduce_add(lv ? 1u : 0u);++ float st[16];+#if QSA_XW > 1+ FUNC_CALL(qsa_xmx_qk)(key_cache, koff, valid_kv, rq, worker, &slm_st[st_buf][0][0][0][0], st);+ st_buf ^= 1;+#else+ FUNC_CALL(qsa_xmx_qk)(key_cache, koff, valid_kv, rq, worker, st);+#endif+ FUNC_CALL(qsa_dpas_softmax_pv)(value_cache, voff, lv, keep, st, worker, &running_max, &running_sum, ro);++ if (exhausted) {+ break;+ }+ }++ // ---- always-visible tail: the union of [n_complete(t) * r, abs_pos(t)] spans at most TT + r - 1 positions ----+ for (uint base = tail_begin; base <= tail_end; base += 16) {+ const uint pos = base + lane;+ const bool lv = pos <= tail_end;+ uint koff = 0, voff = 0;+ if (lv) {+ koff = QSA_KROW(pos);+ voff = QSA_VROW(pos);+ }+ const uint valid_kv = sub_group_reduce_add(lv ? 1u : 0u);++ // Position `base + i` is visible to a column iff n_complete * r <= base + i <= abs_pos.+ uint keep = 0;+ unroll_for (uint i = 0; i < 16; i++) {+ const uint pi = base + i;+ keep |= (lane_valid && n_complete * R <= pi && abs_pos >= pi) ? (1u << i) : 0u;+ }++ float st[16];+#if QSA_XW > 1+ FUNC_CALL(qsa_xmx_qk)(key_cache, koff, valid_kv, rq, worker, &slm_st[st_buf][0][0][0][0], st);+ st_buf ^= 1;+#else+ FUNC_CALL(qsa_xmx_qk)(key_cache, koff, valid_kv, rq, worker, st);+#endif+ FUNC_CALL(qsa_dpas_softmax_pv)(value_cache, voff, lv, keep, st, worker, &running_max, &running_sum, ro);+ }++ // Columns past the end of the sequence belong to no token.+ if (col_tok < valid) {+ const float inv = running_sum > 0.0f ? 1.0f / running_sum : 0.0f;+ unroll_for (uint d = 0; d < QSA_XVT; d++) {+ vstore8(convert_half8_rte(ro[d] * inv), 0, output + out_col + worker * QSA_XDV + d * 8);+ }+ }+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_gqa_dpas.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_gqa_dpas.clnew file mode 100644index 00000000000..7363e97e0f0--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_gqa_dpas.cl@@ -0,0 +1,561 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q3 GQA-aware systolic sparse attention, shared by+// SparsePA (QSA_ADDRESS_MODE 0) and SparseSDPA (QSA_ADDRESS_MODE 1). With QSA_GQA_SPLIT the block steps of a token+// are partitioned over QSA_SPLIT_PARTITIONS work-groups that emit partial (max, sum, acc) state for+// sparse_attention_split_reduce.cl.+//+// One work-group = 4 subgroups = ONE token x ONE KV head. A KV step is 16 rows (16 / r selected blocks); each subgroup+// owns a Dh / 4 slice of the QK reduction and a Dv / 4 slice of the output.+// QK: A = K rows of the step (2D block reads), B = Q with lane = query head of the KV group (the remaining lanes+// carry zero Q); the score tile has lane = head, so the softmax is in-lane. Worker partials meet in SLM.+// PV: A = P with lane = KV row (transposed through a per-worker SLM tile), B = V in VNNI form, so the accumulator+// has element = head, lane = output column.+// Valid rows of a step are always the prefix [0, valid_kv), made of page-local runs of R rows. A step that is one+// contiguous 16-row run is read with one 2D message per 32 columns (VNNI transform for V), otherwise with one message+// per block and 32 columns, all issued before any is consumed (rows past a short block read as zero; V is packed to+// VNNI in registers). The 2D path needs 64-byte aligned K/V buffers; without 2D block IO rows are+// read one by one.+// p stays below 2^8 in half thanks to a lazy rescale of the running max (scores are in log2 units).+//+// Quantized K/V (paged u8 pages or dense i8 tensors with separate scales / zero points, see qsa_common.cl) are read row by row and+// dequantized to half in registers, so the dpas operands are identical to the f16 ones; the 2D block path is f16 only.+//+// JIT: QSA_HEADS, QSA_KV_HEADS, QSA_K_HEAD_SIZE, QSA_V_HEAD_SIZE, QSA_COMPRESS_RATIO, QSA_BLOCK_TOPK, QSA_SCALE,+// QSA_IS_CAUSAL, QSA_ADDRESS_MODE, SUBGROUP_SIZE, (split) QSA_GQA_SPLIT, QSA_SPLIT_PARTITIONS, (paged) QSA_PAGE_SIZE,+// QSA_{K,V}_{MODE,BITS,SYM,GROUP,ROW_BYTES,PAGE_BYTES,PARAM_OFFSET}, (dense) QSA_DENSE_QUANT,+// QSA_{K,V}_{SIGNED,ZP_F16}+// Dispatch: gws = [tokens * 4 * SG, QSA_KV_HEADS, P (split) | 1], lws = [4 * SG, 1, 1]++#define QSA_XMX_WORKERS 4+#define QSA_ATTENTION_HELPERS+#include "qsa_common.cl"++#if SUBGROUP_SIZE != 16+# error "the systolic attention needs a 16-wide subgroup"+#endif+#if !QSA_IS_CAUSAL+# error "only causal QSA is supported"+#endif+#ifndef QSA_GQA_SPLIT+# define QSA_GQA_SPLIT 0+#endif+#if QSA_COMPRESS_RATIO != 2 && QSA_COMPRESS_RATIO != 4 && QSA_COMPRESS_RATIO != 8 && QSA_COMPRESS_RATIO != 16+# error "R must be 2, 4, 8 or 16"+#endif+#if (QSA_K_HEAD_SIZE % (QSA_XW * 32)) != 0 || (QSA_V_HEAD_SIZE % (QSA_XW * 32)) != 0+# error "worker slices must be 32-half aligned"+#endif++#define GQA_R QSA_COMPRESS_RATIO+#define GQA_BLOCKS (16 / QSA_COMPRESS_RATIO)+#define GQA_RESCALE_LOG2 8.0f+#define GQA_VT (QSA_XDV / 16) // 16-column PV tiles of a worker+#define GQA_HEADS (QSA_HEADS / QSA_KV_HEADS)+#define GQA_HH (GQA_HEADS > 8 ? 2 : 1) // 8-head halves of the PV accumulator++#undef GQA_BLOCK_READ+#ifdef cl_intel_subgroup_2d_block_io+# define GQA_2D 1+# if QSA_COMPRESS_RATIO == 2+# define GQA_BLOCK_READ intel_sub_group_2d_block_read_16b_2r16x2c+# elif QSA_COMPRESS_RATIO == 4+# define GQA_BLOCK_READ intel_sub_group_2d_block_read_16b_4r16x2c+# elif QSA_COMPRESS_RATIO == 8+# define GQA_BLOCK_READ intel_sub_group_2d_block_read_16b_8r16x2c+# else+# define GQA_BLOCK_READ intel_sub_group_2d_block_read_16b_16r16x2c+# endif+#else+# define GQA_2D 0+#endif++#define GQA_S8(t, o) as_short8((ushort8)((t)[(o) + 0], (t)[(o) + 1], (t)[(o) + 2], (t)[(o) + 3], (t)[(o) + 4], (t)[(o) + 5], (t)[(o) + 6], (t)[(o) + 7]))+#define GQA_I8(t, o) as_int8((uint8)((t)[(o) + 0], (t)[(o) + 1], (t)[(o) + 2], (t)[(o) + 3], (t)[(o) + 4], (t)[(o) + 5], (t)[(o) + 6], (t)[(o) + 7]))++// K of one step as A operands: ka[k][h] holds rows 8h..8h+7 (element) x columns worker * XDH + 16 k + lane.+// Quantized K: `koff` is the byte offset of this lane's row and `kpar` its parameter locator (see QSA_LOAD_K_COLS).+inline void FUNC(gqa_load_k)(QSA_QP_DECL const __global QSA_KC_T* key_cache,+ const uint koff,+ const uint kpar,+ const uint valid_kv,+ const bool contiguous,+ const uint worker,+ __private short8 (*ka)[2]) {+ const int row_bytes = QSA_K_HEAD_SIZE * 2;+ const uint x0 = worker * QSA_XDH;+#if QSA_K_QUANT+ {+ unroll_for (uint i = 0; i < 16; i++) {+ const uint ro = sub_group_broadcast(koff, i);+ const uint po = sub_group_broadcast(kpar, i);+ float x[QSA_XKT];+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ x[k] = 0.0f;+ }+ if (i < valid_kv) {+ QSA_LOAD_K_COLS(ro, po, x0, x, QSA_XKT);+ }+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ ka[k][i / 8][i % 8] = as_short(convert_half_rte(x[k]));+ }+ }+ }+#elif GQA_2D+ {+ if (contiguous) {+ const __global half* base = key_cache + sub_group_broadcast(koff, 0);+ unroll_for (uint m = 0; m < QSA_XKT / 2; m++) {+ ushort t[32];+ intel_sub_group_2d_block_read_16b_16r16x2c(base, row_bytes, 16, row_bytes, (int2)(x0 + m * 32, 0), t);+ ka[2 * m][0] = GQA_S8(t, 0);+ ka[2 * m][1] = GQA_S8(t, 8);+ ka[2 * m + 1][0] = GQA_S8(t, 16);+ ka[2 * m + 1][1] = GQA_S8(t, 24);+ }+ return;+ }+ // Every read is issued before any is consumed (an empty block reads one row of a valid address and is+ // masked), so the latencies overlap instead of serializing on per-block branches.+ ushort t[GQA_BLOCKS][QSA_XKT / 2][2 * GQA_R];+ unroll_for (uint j = 0; j < GQA_BLOCKS; j++) {+ const uint rows = valid_kv > j * GQA_R ? min(valid_kv - j * GQA_R, (uint)GQA_R) : 0u;+ const __global half* base = key_cache + sub_group_broadcast(koff, j * GQA_R);+ unroll_for (uint m = 0; m < QSA_XKT / 2; m++) {+ GQA_BLOCK_READ(base, row_bytes, (int)max(rows, 1u), row_bytes, (int2)(x0 + m * 32, 0), t[j][m]);+ }+ }+ unroll_for (uint j = 0; j < GQA_BLOCKS; j++) {+ const bool empty = valid_kv <= j * GQA_R;+ unroll_for (uint m = 0; m < QSA_XKT / 2; m++) {+ unroll_for (uint r = 0; r < GQA_R; r++) {+ ka[2 * m][(j * GQA_R + r) / 8][(j * GQA_R + r) % 8] = empty ? 0 : (short)t[j][m][r];+ ka[2 * m + 1][(j * GQA_R + r) / 8][(j * GQA_R + r) % 8] = empty ? 0 : (short)t[j][m][GQA_R + r];+ }+ }+ }+ }+#else+ unroll_for (uint i = 0; i < 16; i++) {+ ushort r[QSA_XKT];+ const uint ko = sub_group_broadcast(koff, i);+ if (i < valid_kv) {+ FUNC_CALL(qsa_rd)((const __global ushort*)(key_cache + ko + x0), r, QSA_XKT);+ } else {+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ r[k] = 0;+ }+ }+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ ka[k][i / 8][i % 8] = (short)r[k];+ }+ }+#endif+}++// V of one step as VNNI B operands: vb[t] element j packs rows 2j, 2j+1 of column worker * XDV + 16 t + lane.+inline void FUNC(gqa_load_v)(QSA_QP_DECL const __global QSA_VC_T* value_cache,+ const uint voff,+ const uint vpar,+ const uint valid_kv,+ const bool contiguous,+ const uint worker,+ __private int8* vb) {+ const int row_bytes = QSA_V_HEAD_SIZE * 2;+ const uint x0 = worker * QSA_XDV;+#if QSA_V_QUANT+ {+ unroll_for (uint i = 0; i < 16; i += 2) {+ const uint ro0 = sub_group_broadcast(voff, i);+ const uint ro1 = sub_group_broadcast(voff, i + 1);+ const uint po0 = sub_group_broadcast(vpar, i);+ const uint po1 = sub_group_broadcast(vpar, i + 1);+ float v0[GQA_VT], v1[GQA_VT];+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ v0[t] = 0.0f;+ v1[t] = 0.0f;+ }+ if (i < valid_kv) {+ QSA_LOAD_V_COLS(ro0, po0, x0, v0, GQA_VT);+ }+ if (i + 1 < valid_kv) {+ QSA_LOAD_V_COLS(ro1, po1, x0, v1, GQA_VT);+ }+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ vb[t][i / 2] = (int)((uint)as_ushort(convert_half_rte(v0[t])) | ((uint)as_ushort(convert_half_rte(v1[t])) << 16));+ }+ }+ }+#elif GQA_2D+ {+ if (contiguous) {+ const __global half* base = value_cache + sub_group_broadcast(voff, 0);+ unroll_for (uint m = 0; m < GQA_VT / 2; m++) {+ uint t[16];+ intel_sub_group_2d_block_read_transform_16b_16r16x2c(base, row_bytes, 16, row_bytes, (int2)(x0 + m * 32, 0), t);+ vb[2 * m] = GQA_I8(t, 0);+ vb[2 * m + 1] = GQA_I8(t, 8);+ }+ return;+ }+ // A VNNI transform read is at least 16 rows high, so short blocks are read plainly (all reads first, as for K)+ // and packed in registers.+ ushort t[GQA_BLOCKS][GQA_VT / 2][2 * GQA_R];+ unroll_for (uint j = 0; j < GQA_BLOCKS; j++) {+ const uint rows = valid_kv > j * GQA_R ? min(valid_kv - j * GQA_R, (uint)GQA_R) : 0u;+ const __global half* base = value_cache + sub_group_broadcast(voff, j * GQA_R);+ unroll_for (uint m = 0; m < GQA_VT / 2; m++) {+ GQA_BLOCK_READ(base, row_bytes, (int)max(rows, 1u), row_bytes, (int2)(x0 + m * 32, 0), t[j][m]);+ }+ }+ unroll_for (uint j = 0; j < GQA_BLOCKS; j++) {+ const bool empty = valid_kv <= j * GQA_R;+ unroll_for (uint m = 0; m < GQA_VT / 2; m++) {+ unroll_for (uint q = 0; q < GQA_R / 2; q++) {+ const uint lo = (uint)t[j][m][2 * q] | ((uint)t[j][m][2 * q + 1] << 16);+ const uint hi = (uint)t[j][m][GQA_R + 2 * q] | ((uint)t[j][m][GQA_R + 2 * q + 1] << 16);+ vb[2 * m][j * GQA_R / 2 + q] = empty ? 0 : (int)lo;+ vb[2 * m + 1][j * GQA_R / 2 + q] = empty ? 0 : (int)hi;+ }+ }+ }+ }+#else+ unroll_for (uint i = 0; i < 16; i += 2) {+ ushort r0[GQA_VT], r1[GQA_VT];+ const uint vo0 = sub_group_broadcast(voff, i);+ const uint vo1 = sub_group_broadcast(voff, i + 1);+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ r0[t] = 0;+ r1[t] = 0;+ }+ if (i < valid_kv) {+ FUNC_CALL(qsa_rd)((const __global ushort*)(value_cache + vo0 + x0), r0, GQA_VT);+ }+ if (i + 1 < valid_kv) {+ FUNC_CALL(qsa_rd)((const __global ushort*)(value_cache + vo1 + x0), r1, GQA_VT);+ }+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ vb[t][i / 2] = (int)((uint)r0[t] | ((uint)r1[t] << 16));+ }+ }+#endif+}++// One KV step of the online softmax for this worker: QK partials summed over the workers through `slm_st`, softmax+// with a lazy rescale, P^T through the worker's `slm_p` tile, then PV into ro.+inline void FUNC(gqa_step)(QSA_QP_DECL const __global QSA_KC_T* key_cache,+ const __global QSA_VC_T* value_cache,+ const uint koff,+ const uint voff,+ const uint kpar,+ const uint vpar,+ const uint valid_kv,+ const bool kcont,+ const bool vcont,+ const uint worker,+ __private const int8* rq,+ __local float* slm_st, // [W][2][8][SG] of the current slot+ __local uint8* slm_p, // [16] of this worker and slot+ __private float* running_max,+ __private float* running_sum,+ __private float8 (*ro)[GQA_VT]) {+ const uint lane = get_sub_group_local_id();+ short8 ka[QSA_XKT][2];+ FUNC_CALL(gqa_load_k)(QSA_QP_ARGS key_cache, koff, kpar, valid_kv, kcont, worker, ka);+ // V is in flight during QK and the softmax.+ int8 vb[GQA_VT];+ FUNC_CALL(gqa_load_v)(QSA_QP_ARGS value_cache, voff, vpar, valid_kv, vcont, worker, vb);++ // QK partial of this worker, summed over the workers in the fixed order 0..W-1 (bit-identical everywhere).+ float8 st0 = (float8)(0.0f);+ float8 st1 = (float8)(0.0f);+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ st0 = intel_sub_group_f16_f16_matrix_mad_k16(ka[k][0], rq[k], st0);+ st1 = intel_sub_group_f16_f16_matrix_mad_k16(ka[k][1], rq[k], st1);+ }+ QSA_SLM_WRITE8(slm_st + worker * QSA_XST_FLOATS, st0);+ QSA_SLM_WRITE8(slm_st + worker * QSA_XST_FLOATS + 8 * QSA_SG, st1);+ barrier(CLK_LOCAL_MEM_FENCE);+ st0 = QSA_SLM_READ8(slm_st);+ st1 = QSA_SLM_READ8(slm_st + 8 * QSA_SG);+ unroll_for (uint w = 1; w < QSA_XW; w++) {+ st0 += QSA_SLM_READ8(slm_st + w * QSA_XST_FLOATS);+ st1 += QSA_SLM_READ8(slm_st + w * QSA_XST_FLOATS + 8 * QSA_SG);+ }+ float st[16];+ vstore8(st0, 0, st);+ vstore8(st1, 0, st + 8);++ // Padded head lanes see zero Q (finite scores, never stored): only the rows past valid_kv need masking.+ if (valid_kv != 16) {+ unroll_for (uint i = 0; i < 16; i++) {+ st[i] = i >= valid_kv ? QSA_NEG_INF : st[i];+ }+ }+ float tile_max = st[0];+ unroll_for (uint i = 1; i < 16; i++) {+ tile_max = fmax(tile_max, st[i]);+ }+ // Lazy rescale: the running max only moves when some lane grows by more than 2^GQA_RESCALE_LOG2.+ float m = *running_max;+ float s = *running_sum;+ if (sub_group_any(tile_max > m + GQA_RESCALE_LOG2)) {+ const float new_max = fmax(m, tile_max);+ const float corr = native_exp2(m - new_max);+ s *= corr;+ m = new_max;+ unroll_for (uint hh = 0; hh < GQA_HH; hh++) {+ float8 c;+ unroll_for (uint i = 0; i < 8; i++) {+ c[i] = sub_group_broadcast(corr, hh * 8 + i);+ }+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ ro[hh][t] *= c;+ }+ }+ }+ float p[16];+ unroll_for (uint i = 0; i < 16; i++) {+ p[i] = native_exp2(st[i] - m);+ s += p[i];+ }+ *running_max = m;+ *running_sum = s;++ // P^T through SLM: lane h stores its row P[h][0..15]; a block read then gives lane = KV row, element = head.+ slm_p[lane] = (uint8)(as_uint(convert_half2_rte((float2)(p[0], p[1]))), as_uint(convert_half2_rte((float2)(p[2], p[3]))),+ as_uint(convert_half2_rte((float2)(p[4], p[5]))), as_uint(convert_half2_rte((float2)(p[6], p[7]))),+ as_uint(convert_half2_rte((float2)(p[8], p[9]))), as_uint(convert_half2_rte((float2)(p[10], p[11]))),+ as_uint(convert_half2_rte((float2)(p[12], p[13]))), as_uint(convert_half2_rte((float2)(p[14], p[15]))));+ sub_group_barrier(CLK_LOCAL_MEM_FENCE);+ unroll_for (uint hh = 0; hh < GQA_HH; hh++) {+ const __local ushort* pt = (const __local ushort*)slm_p + hh * 128;+#ifdef cl_intel_subgroup_local_block_io+ const short8 pa = as_short8(intel_sub_group_block_read_us8(pt));+#else+ const short8 pa = (short8)((short)pt[lane], (short)pt[16 + lane], (short)pt[32 + lane], (short)pt[48 + lane],+ (short)pt[64 + lane], (short)pt[80 + lane], (short)pt[96 + lane], (short)pt[112 + lane]);+#endif+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ ro[hh][t] = intel_sub_group_f16_f16_matrix_mad_k16(pa, vb[t], ro[hh][t]);+ }+ }+}++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(sparse_attention_gqa_dpas)(QSA_ATT_INPUT_ARGS,+#if QSA_GQA_SPLIT+ __global float* partial_acc, // [tokens, Hq, P, Dv]+ __global float* partial_ml, // [tokens, Hq, P, 2]+#else+ __global half* output, // paged: [tokens, Hq*Dv]; dense: [B, Hq, L, Dv]+#endif+#if QSA_ADDRESS_MODE == 0+ const uint num_entries,+ const uint num_seqs,+ const uint q_base,+ const uint q_pitch+#else+ const uint num_entries,+ const uint seq_len,+ const uint history_len,+ const uint k_pitch,+ const uint v_pitch+# if QSA_DENSE_QUANT+ ,+ const uint k_ppitch,+ const uint v_ppitch+# endif+#endif+) {+ const uint HQ = QSA_HEADS;+ const uint HKV = QSA_KV_HEADS;+ const uint DH = QSA_K_HEAD_SIZE;+ const uint DV = QSA_V_HEAD_SIZE;+ const uint R = QSA_COMPRESS_RATIO;+ const uint K_TOPK = QSA_BLOCK_TOPK;+ const uint HEADS = GQA_HEADS;++ __local float slm_st[2][QSA_XW][2][8][QSA_SG];+ __local uint8 slm_p[2][QSA_XW][16]; // per worker: row h = P[head h][kv rows 0..15] as halves++ const uint worker = get_sub_group_id();+ const uint lane = get_sub_group_local_id();+ const uint entry = get_group_id(0);+ const uint kv_head = get_group_id(1);+ if (kv_head >= HKV || entry >= num_entries) {+ return;+ }+ const uint head_base = kv_head * HEADS;+ const uint lane_blk = lane / R;+ const uint lane_rr = lane % R;++#if QSA_ADDRESS_MODE == 0+ const uint token = entry;+ uint seq = 0, abs_pos = 0;+ if (!FUNC_CALL(qsa_resolve_token_paged)(subsequence_begins, past_lens, num_seqs, token, &seq, &abs_pos)) {+ return;+ }+ const uint page_begin = (uint)block_indices_begins[seq];+ const uint count = (uint)selected_counts[token];+ const uint sel_base = token * K_TOPK;+ const uint tail_begin = (abs_pos + 1) / R * R;+ const uint tail_rows = abs_pos + 1 - tail_begin;+ const uint q_head0 = q_base + token * q_pitch + head_base * DH;+# define GQA_Q_HEAD(h) (q_head0 + (h) * DH)+# define GQA_OUT_ROW(h) (token * HQ + head_base + (h))+#else+ const uint batch = entry / seq_len;+ const uint l = entry - batch * seq_len;+ uint kl = (uint)key_length[batch];+ kl = kl < history_len ? kl : history_len;+ const uint shift = history_len - kl;+ const bool pad_row = kl + l < seq_len;+ const uint abs_pos = kl + l - seq_len;+ const uint count = pad_row ? 0 : (uint)selected_counts[entry];+ const uint sel_base = entry * K_TOPK;+ const uint tail_begin = pad_row ? 0 : (abs_pos + 1) / R * R;+ const uint tail_rows = pad_row ? 0 : abs_pos + 1 - tail_begin;+# define GQA_Q_HEAD(h) ((((batch * HQ) + head_base + (h)) * seq_len + l) * DH)+# define GQA_OUT_ROW(h) (((batch * HQ) + head_base + (h)) * seq_len + l)+#endif++ // Q as the B operand: this lane's own head row slice, pre-scaled by scale * log2(e) in the half domain.+ int8 rq[QSA_XKT];+ unroll_for (uint k = 0; k < QSA_XKT; k++) {+ half16 qh = (half16)((half)0.0f);+ if (lane < HEADS) {+ qh = vload16(0, query + GQA_Q_HEAD(lane) + worker * QSA_XDH + k * 16);+ }+ qh = qh * (half)((float)QSA_SCALE * QSA_LOG2E);+ rq[k] = as_int8(qh);+ }++ float running_max = QSA_NEG_INF; // of head `lane`+ float running_sum = 0.0f;+ float8 ro[GQA_HH][GQA_VT]; // element = head 8 hh + i, lane = output column 16 t + lane of the worker slice+ unroll_for (uint hh = 0; hh < GQA_HH; hh++) {+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ ro[hh][t] = (float8)(0.0f);+ }+ }++ const uint steps = (count + GQA_BLOCKS - 1) / GQA_BLOCKS;+#if QSA_GQA_SPLIT+ const uint P = QSA_SPLIT_PARTITIONS;+ const uint part = get_group_id(2);+ // The last partition exclusively owns the tail step.+ const uint step_begin = steps * part / P;+ const uint step_end = steps * (part + 1) / P + (part == P - 1 && tail_rows != 0 ? 1 : 0);+#else+ const uint step_begin = 0;+ const uint step_end = steps + (tail_rows != 0 ? 1 : 0);+#endif++#define GQA_LOAD_ID(step) (((step) < steps && (step) * GQA_BLOCKS + lane_blk < count) ? selected_blocks[sel_base + (step) * GQA_BLOCKS + lane_blk] : -1)+// Lane = KV row of the step: its validity and absolute position (step == steps is the tail).+#define GQA_META(step, id, lv, pos) \+ if ((step) == steps) { \+ lv = lane < tail_rows; \+ pos = tail_begin + lane; \+ } else { \+ lv = (id) >= 0; \+ pos = (uint)(id) * R + lane_rr; \+ }+#if QSA_ADDRESS_MODE == 0+# define GQA_PAGE(lv, pos) ((lv) ? (uint)block_indices[page_begin + (pos) / QSA_PAGE_SIZE] : 0u)+#else+# define GQA_PAGE(lv, pos) 0u+#endif++ // Software-pipelined metadata: the next step's pages and the following step's ids are in flight while a step+ // computes, so the KV loads never wait on the id -> page chain.+ bool cur_lv;+ uint cur_pos;+ const int first_id = GQA_LOAD_ID(step_begin);+ GQA_META(step_begin, first_id, cur_lv, cur_pos);+ uint cur_page = GQA_PAGE(cur_lv, cur_pos);+ int next_id = GQA_LOAD_ID(step_begin + 1);++ for (uint step = step_begin; step < step_end; step++) {+ bool nlv;+ uint npos;+ GQA_META(step + 1, next_id, nlv, npos);+ const uint npage = GQA_PAGE(nlv, npos);+ next_id = GQA_LOAD_ID(step + 2);++ const bool lv = cur_lv;+ const uint pos = cur_pos;+ uint koff = 0, voff = 0, kpar = 0, vpar = 0;+ if (lv) {+#if QSA_ADDRESS_MODE == 0+# if QSA_K_QUANT+ QSA_K_LOC(cur_page, pos % QSA_PAGE_SIZE, &koff, &kpar);+# else+ koff = FUNC_CALL(qsa_kv_cache_offset)(cur_page, kv_head, pos % QSA_PAGE_SIZE, HKV, QSA_PAGE_SIZE, DH);+# endif+# if QSA_V_QUANT+ QSA_V_LOC(cur_page, pos % QSA_PAGE_SIZE, &voff, &vpar);+# else+ voff = FUNC_CALL(qsa_kv_cache_offset)(cur_page, kv_head, pos % QSA_PAGE_SIZE, HKV, QSA_PAGE_SIZE, DV);+# endif+#else+# if QSA_K_QUANT+ koff = QSA_KROWB(pos);+ kpar = QSA_KPAR(pos);+# else+ koff = QSA_KROW(pos);+# endif+# if QSA_V_QUANT+ voff = QSA_VROWB(pos);+ vpar = QSA_VPAR(pos);+# else+ voff = QSA_VROW(pos);+# endif+#endif+ }+ const uint valid_kv = sub_group_reduce_add(lv ? 1u : 0u);+ // A step read with one 2D message per operand needs ascending contiguous f16 rows.+ bool kcont = false, vcont = false;+#if !QSA_K_QUANT+ kcont = valid_kv == 16 && sub_group_all(koff == sub_group_broadcast(koff, 0) + lane * DH);+#endif+#if !QSA_V_QUANT+ vcont = valid_kv == 16 && sub_group_all(voff == sub_group_broadcast(voff, 0) + lane * DV);+#endif++ FUNC_CALL(gqa_step)(QSA_QP_ARGS key_cache, value_cache, koff, voff, kpar, vpar, valid_kv, kcont, vcont, worker, rq, &slm_st[step & 1][0][0][0][0],+ &slm_p[step & 1][worker][0], &running_max, &running_sum, ro);+ cur_lv = nlv;+ cur_pos = npos;+ cur_page = npage;+ }++ // Never store the padded heads: that would overwrite the next KV group or token.+#if QSA_GQA_SPLIT+ if (worker == 0 && lane < HEADS) {+ // The reduce pass expects natural-log maxima; scores here are in log2 units.+ const uint prow = GQA_OUT_ROW(lane) * P + part;+ partial_ml[prow * 2] = running_max * 0.6931471805599453f;+ partial_ml[prow * 2 + 1] = running_sum;+ }+ unroll_for (uint h = 0; h < GQA_HEADS; h++) {+ __global uint* dst = (__global uint*)(partial_acc + (GQA_OUT_ROW(h) * P + part) * DV + worker * QSA_XDV);+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ intel_sub_group_block_write(dst + t * 16, as_uint(ro[h / 8][t][h % 8]));+ }+ }+#else+ const float inv = running_sum > 0.0f ? 1.0f / running_sum : 0.0f;+ unroll_for (uint h = 0; h < GQA_HEADS; h++) {+ const float ih = sub_group_broadcast(inv, h);+ __global ushort* dst = (__global ushort*)(output + GQA_OUT_ROW(h) * DV + worker * QSA_XDV);+ unroll_for (uint t = 0; t < GQA_VT; t++) {+ intel_sub_group_block_write_us(dst + t * 16, as_ushort(convert_half_rte(ro[h / 8][t][h % 8] * ih)));+ }+ }+#endif+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_kv_write.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_kv_write.clnew file mode 100644index 00000000000..117c6ae08a2--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_kv_write.cl@@ -0,0 +1,316 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q0 - SparsePA main K/V cache write. Two kernels share this file, selected by QSA_KV_WRITE_KCHANNEL.+//+// Default: one subgroup copies (f16 caches) or quantizes (BY_TOKEN quantized caches) the K and V row of one+// (token, kv head) into the paged cache. The input rows may be padded and offset (key_pitch / key_offset), so they are+// read lane-wise without any alignment assumption. BY_CHANNEL keys are skipped here.+// JIT: QSA_KV_HEADS, QSA_K_HEAD_SIZE, QSA_V_HEAD_SIZE, QSA_PAGE_SIZE, SUBGROUP_SIZE,+// QSA_{K,V}_{MODE,BITS,SYM,GROUP,ROW_BYTES,PAGE_BYTES,PARAM_OFFSET} (see qsa_common.cl)+// Dispatch: gws = [SG, QSA_KV_HEADS, tokens_padded], lws = [SG, 1, 1]+//+// QSA_KV_WRITE_KCHANNEL: BY_CHANNEL key cache write. One subgroup owns one (sequence, token group, kv head); a group is+// QSA_K_GROUP consecutive tokens of one page that share one scale / zero point per channel, so appending a token+// re-quantizes the whole group: pass 1 gets the per-channel range (cached tokens dequantized with their old parameters,+// new tokens from the key input), pass 2 re-quantizes and rewrites every row, then the parameters. Groups without a new+// token are never touched.+// Dispatch: gws = [(tokens / QSA_K_GROUP + 2 * num_seqs) * SG, QSA_KV_HEADS, 1], lws = [SG, 1, 1]++#define QSA_KVQ_HELPERS+#include "qsa_common.cl"++#if QSA_KV_WRITE_KCHANNEL++#define KCH_NE (QSA_K_HEAD_SIZE / QSA_SG)++#if (QSA_K_HEAD_SIZE % SUBGROUP_SIZE) != 0 || QSA_K_HEAD_SIZE > QSA_MAX_NE * SUBGROUP_SIZE+# error "head size must be a whole number of subgroup rows of at most QSA_MAX_NE elements per lane"+#endif+#if QSA_K_MODE != 2+# error "this kernel only writes BY_CHANNEL keys"+#endif+#if (QSA_PAGE_SIZE % QSA_K_GROUP) != 0+# error "a group must fit a page"+#endif++// Maps work-group `wg` of a grid sized `tokens / group + 2 * num_seqs` onto the (sequence, token group) it re-quantizes:+// sequence i owns the groups touched by its new tokens.+inline bool FUNC(qsa_resolve_group)(const __global int* subsequence_begins,+ const __global int* past_lens,+ const uint num_seqs,+ const uint wg,+ const uint group_size,+ __private uint* seq,+ __private uint* group) {+ uint acc = 0;+ for (uint i = 0; i < num_seqs; i++) {+ const uint q_len = (uint)subsequence_begins[i + 1] - (uint)subsequence_begins[i];+ if (q_len == 0) {+ continue;+ }+ const uint past = (uint)past_lens[i];+ const uint first = past / group_size;+ const uint n = (past + q_len - 1) / group_size - first + 1;+ if (wg < acc + n) {+ *seq = i;+ *group = first + (wg - acc);+ return true;+ }+ acc += n;+ }+ return false;+}++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(sparse_attention_kv_write_kchannel)(const __global half* key, // [num_tokens, Hkv*Dh] token-major+ const __global int* past_lens, // [num_seqs]+ const __global int* block_indices, // [used_blocks]+ const __global int* block_indices_begins, // [num_seqs+1]+ const __global int* subsequence_begins, // [num_seqs+1]+ __global uchar* key_cache, // [num_blocks, Hkv, page_size + parameter rows, row bytes]+ const uint key_pitch,+ const uint key_offset,+ const uint num_seqs) {+ const uint KV_HEADS = QSA_KV_HEADS;+ const uint DH = QSA_K_HEAD_SIZE;+ const uint PAGE = QSA_PAGE_SIZE;+ const uint G = QSA_K_GROUP;+ const uint BITS = QSA_K_BITS;+ const uint ROWB = QSA_K_ROW_BYTES;+ const uint SYM = QSA_K_SYM;+ const uint REC_BYTES = DH * (SYM ? 2 : 4);+ const float QMAX = BITS == 8 ? 255.0f : 15.0f;++ const uint head = get_group_id(1);+ const uint lane = get_sub_group_local_id();+ uint seq = 0, group = 0;+ if (head >= KV_HEADS || !FUNC_CALL(qsa_resolve_group)(subsequence_begins, past_lens, num_seqs, get_group_id(0), G, &seq, &group)) {+ return;+ }++ const uint seq_begin = (uint)subsequence_begins[seq];+ const uint past = (uint)past_lens[seq];+ const uint total = past + (uint)subsequence_begins[seq + 1] - seq_begin;+ const uint g0 = group * G;+ const uint n_valid = total - g0 < G ? total - g0 : G;+ const uint n_old = past > g0 ? (past - g0 < n_valid ? past - g0 : n_valid) : 0;++ const uint tok0 = g0 % PAGE;+ const uint physical_page = (uint)block_indices[(uint)block_indices_begins[seq] + g0 / PAGE];+ const uint pb = (physical_page * KV_HEADS + head) * QSA_K_PAGE_BYTES;+ const uint rec = pb + QSA_K_PARAM_OFFSET + (tok0 / G) * REC_BYTES;++ float old_scale[QSA_K_HEAD_SIZE / QSA_SG];+ float old_zp[QSA_K_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < KCH_NE; j++) {+ const uint c = lane + QSA_SG * j;+ old_scale[j] = 1.0f;+ old_zp[j] = 0.0f;+ if (n_old > 0) {+ old_scale[j] = convert_float(*(const __global half*)(key_cache + rec + c * 2));+ old_zp[j] = SYM ? FUNC_CALL(qsa_q_zero_sym)(BITS) : convert_float(*(const __global half*)(key_cache + rec + DH * 2 + c * 2));+ }+ }++ // Row t of the group as f32 (cached rows dequantized with their old parameters in f16 arithmetic).+#define KCH_LOAD_ROW(t, h) \+ { \+ if ((t) < n_old) { \+ const uint row_off = pb + (tok0 + (t)) * ROWB; \+ unroll_for (uint j = 0; j < KCH_NE; j++) { \+ const uint c = lane + QSA_SG * j; \+ float code; \+ if (BITS == 8) { \+ code = convert_float(key_cache[row_off + c]); \+ } else { \+ const uchar b = key_cache[row_off + (c >> 1)]; \+ code = convert_float((c & 1) ? (b >> 4) : (b & 0xF)); \+ } \+ h[j] = FUNC_CALL(qsa_q_dq)(code, old_zp[j], old_scale[j]); \+ } \+ } else { \+ const __global ushort* src = (const __global ushort*)key + key_offset + (seq_begin + (g0 + (t) - past)) * key_pitch + head * DH + lane; \+ unroll_for (uint j = 0; j < KCH_NE; j++) { \+ h[j] = convert_float(as_half(src[j * QSA_SG])); \+ } \+ } \+ }++ // Pass 1: per-channel range, always including 0 so that the zero point stays inside the f16 range.+ float mn[QSA_K_HEAD_SIZE / QSA_SG];+ float mx[QSA_K_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < KCH_NE; j++) {+ mn[j] = 0.0f;+ mx[j] = 0.0f;+ }+ for (uint t = 0; t < n_valid; t++) {+ float h[QSA_K_HEAD_SIZE / QSA_SG];+ KCH_LOAD_ROW(t, h);+ unroll_for (uint j = 0; j < KCH_NE; j++) {+ mn[j] = fmin(mn[j], h[j]);+ mx[j] = fmax(mx[j], h[j]);+ }+ }++ half scale_h[QSA_K_HEAD_SIZE / QSA_SG];+ half zero_h[QSA_K_HEAD_SIZE / QSA_SG];+ float inv[QSA_K_HEAD_SIZE / QSA_SG];+ float zero_f[QSA_K_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < KCH_NE; j++) {+ float scale, zero;+ if (SYM) {+ scale = fmax(fmax(mx[j], -mn[j]) / (BITS == 8 ? 127.0f : 7.0f), QSA_KVQ_MIN_SCALE);+ zero = FUNC_CALL(qsa_q_zero_sym)(BITS);+ } else {+ scale = fmax((mx[j] - mn[j]) / QMAX, QSA_KVQ_MIN_SCALE);+ zero = -mn[j] / scale;+ }+ scale_h[j] = convert_half_rte(scale);+ zero_h[j] = convert_half_rte(zero);+ inv[j] = 1.0f / convert_float(scale_h[j]);+ zero_f[j] = convert_float(zero_h[j]);+ }++ // Pass 2: re-quantize every row of the group with the new parameters.+ for (uint t = 0; t < n_valid; t++) {+ float h[QSA_K_HEAD_SIZE / QSA_SG];+ KCH_LOAD_ROW(t, h);+ uint code[QSA_K_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < KCH_NE; j++) {+ code[j] = (uint)(clamp(h[j] * inv[j] + zero_f[j], 0.0f, QMAX) + 0.5f);+ }+ FUNC_CALL(qsa_q_store_codes)(key_cache, pb + (tok0 + t) * ROWB, code, KCH_NE, BITS);+ }++ unroll_for (uint j = 0; j < KCH_NE; j++) {+ const uint c = lane + QSA_SG * j;+ *(__global half*)(key_cache + rec + c * 2) = scale_h[j];+ if (!SYM) {+ *(__global half*)(key_cache + rec + DH * 2 + c * 2) = zero_h[j];+ }+ }+}++#else // QSA_KV_WRITE_KCHANNEL++#if (QSA_K_HEAD_SIZE % SUBGROUP_SIZE) != 0 || (QSA_V_HEAD_SIZE % SUBGROUP_SIZE) != 0 || QSA_K_HEAD_SIZE > QSA_MAX_NE * SUBGROUP_SIZE || QSA_V_HEAD_SIZE > QSA_MAX_NE * SUBGROUP_SIZE+# error "head sizes must be whole subgroup rows of at most QSA_MAX_NE elements per lane"+#endif++#if QSA_K_MODE != 0+# define QSA_KV_K_T uchar+#else+# define QSA_KV_K_T half+#endif+#if QSA_V_MODE != 0+# define QSA_KV_V_T uchar+#else+# define QSA_KV_V_T half+#endif++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(sparse_attention_kv_write)(const __global half* key, // [num_tokens, Hkv*Dh] token-major+ const __global half* value, // [num_tokens, Hkv*Dv] token-major+ const __global int* past_lens, // [num_seqs]+ const __global int* block_indices, // [used_blocks]+ const __global int* block_indices_begins, // [num_seqs+1]+ const __global int* subsequence_begins, // [num_seqs+1]+ __global QSA_KV_K_T* key_cache, // [num_blocks, Hkv, page_size (+ parameter rows), row]+ __global QSA_KV_V_T* value_cache, // [num_blocks, Hkv, page_size (+ parameter rows), row]+ const uint key_pitch,+ const uint key_offset,+ const uint value_pitch,+ const uint value_offset,+ const uint num_seqs) {+ const uint KV_HEADS = QSA_KV_HEADS;+ const uint K_HEAD = QSA_K_HEAD_SIZE;+ const uint V_HEAD = QSA_V_HEAD_SIZE;+ const uint PAGE = QSA_PAGE_SIZE;++ const uint head_idx = get_group_id(1);+ const uint token_idx = get_group_id(2);+ const uint lane = get_sub_group_local_id();++ if (token_idx >= (uint)subsequence_begins[num_seqs]) {+ return;+ }++ uint seq = 0;+ for (uint i = 0; i < num_seqs; i++) {+ if (token_idx >= (uint)subsequence_begins[i] && token_idx < (uint)subsequence_begins[i + 1]) {+ seq = i;+ break;+ }+ }++ const uint abs_pos = (uint)past_lens[seq] + token_idx - (uint)subsequence_begins[seq];+ const uint physical_page = (uint)block_indices[(uint)block_indices_begins[seq] + abs_pos / PAGE];+ const uint token_in_page = abs_pos % PAGE;++ const uint k_src = key_offset + token_idx * key_pitch + head_idx * K_HEAD;+ const uint v_src = value_offset + token_idx * value_pitch + head_idx * V_HEAD;+ const uint kv_head = head_idx;+ const __global ushort* ks = (const __global ushort*)key + k_src + lane;+ const __global ushort* vs = (const __global ushort*)value + v_src + lane;++ // Every load is issued before the first store: the source and cache pointers may alias as far as the compiler+ // knows, so interleaving them would serialize one memory round trip per element.+#if QSA_K_MODE == 0+ ushort kr[QSA_K_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < K_HEAD / QSA_SG; j++) {+ kr[j] = ks[j * QSA_SG];+ }+#elif QSA_K_MODE == 1+ float kf[QSA_K_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < K_HEAD / QSA_SG; j++) {+ kf[j] = convert_float(as_half(ks[j * QSA_SG]));+ }+#endif+#if QSA_V_MODE == 0+ ushort vr[QSA_V_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < V_HEAD / QSA_SG; j++) {+ vr[j] = vs[j * QSA_SG];+ }+#else+ float vf[QSA_V_HEAD_SIZE / QSA_SG];+ unroll_for (uint j = 0; j < V_HEAD / QSA_SG; j++) {+ vf[j] = convert_float(as_half(vs[j * QSA_SG]));+ }+#endif++#if QSA_K_MODE == 0+ FUNC_CALL(qsa_wr)((__global ushort*)(key_cache + FUNC_CALL(qsa_kv_cache_offset)(physical_page, head_idx, token_in_page, KV_HEADS, PAGE, K_HEAD)), kr, K_HEAD / QSA_SG);+#elif QSA_K_MODE == 1+ {+ uint ro, po;+ QSA_K_LOC(physical_page, token_in_page, &ro, &po);+ uint code[QSA_K_HEAD_SIZE / QSA_SG];+ half sh, zh;+ FUNC_CALL(qsa_q_quant_row)(kf, code, K_HEAD / QSA_SG, QSA_K_BITS, QSA_K_SYM, &sh, &zh);+ FUNC_CALL(qsa_q_store_codes)((__global uchar*)key_cache, ro, code, K_HEAD / QSA_SG, QSA_K_BITS);+ if (lane == 0) {+ *(__global uint*)((__global uchar*)key_cache + po) = (uint)as_ushort(sh) | ((uint)as_ushort(zh) << 16);+ }+ }+#endif++#if QSA_V_MODE == 0+ FUNC_CALL(qsa_wr)((__global ushort*)(value_cache + FUNC_CALL(qsa_kv_cache_offset)(physical_page, head_idx, token_in_page, KV_HEADS, PAGE, V_HEAD)), vr, V_HEAD / QSA_SG);+#else+ {+ uint ro, po;+ QSA_V_LOC(physical_page, token_in_page, &ro, &po);+ uint code[QSA_V_HEAD_SIZE / QSA_SG];+ half sh, zh;+ FUNC_CALL(qsa_q_quant_row)(vf, code, V_HEAD / QSA_SG, QSA_V_BITS, QSA_V_SYM, &sh, &zh);+ FUNC_CALL(qsa_q_store_codes)((__global uchar*)value_cache, ro, code, V_HEAD / QSA_SG, QSA_V_BITS);+ if (lane == 0) {+ *(__global uint*)((__global uchar*)value_cache + po) = (uint)as_ushort(sh) | ((uint)as_ushort(zh) << 16);+ }+ }+#endif+}++#endif // QSA_KV_WRITE_KCHANNELdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_scalar.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_scalar.clnew file mode 100644index 00000000000..46546174ce9--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_scalar.cl@@ -0,0 +1,143 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q3 - selected-block sparse attention, scalar variant, shared by+// SparsePA (QSA_ADDRESS_MODE 0, paged K/V) and SparseSDPA (QSA_ADDRESS_MODE 1, dense left-padded K/V).+//+// One subgroup = one (query head, token); lanes cover the head dimensions, a dot product is a per-lane partial sum+// plus a subgroup reduction. Every selected block (r tokens) is followed by the always-visible causal tail, with an+// online softmax over all of them.+//+// JIT: QSA_HEADS, QSA_KV_HEADS, QSA_K_HEAD_SIZE, QSA_V_HEAD_SIZE, QSA_COMPRESS_RATIO, QSA_BLOCK_TOPK, QSA_SCALE,+// QSA_ADDRESS_MODE, SUBGROUP_SIZE and (paged) QSA_PAGE_SIZE, QSA_{K,V}_{MODE,BITS,SYM,GROUP,ROW_BYTES,PAGE_BYTES,+// PARAM_OFFSET}; (dense) QSA_DENSE_QUANT and QSA_{K,V}_{BITS,SYM,ROW_BYTES,SIGNED,ZP_F16} for quantized K/V+// history tensors with separate scale / zero point inputs (see op/sparse_kv_quant.hpp)+// Quantized rows are dequantized to f32 on load; f16 rows go through the subgroup block reads.+// Dispatch: gws = [QSA_HEADS * SG, num_tokens (paged) | B*L (dense), 1], lws = [SG, 1, 1]++#define QSA_ATTENTION_HELPERS+#include "qsa_common.cl"++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(sparse_attention_scalar)(QSA_ATT_INPUT_ARGS,+ __global half* output, // paged: [num_tokens, Hq*Dv]; dense: [B, Hq, L, Dv]+#if QSA_ADDRESS_MODE == 0+ const uint num_tokens,+ const uint num_seqs,+ const uint q_base,+ const uint q_pitch+#else+ const uint seq_len,+ const uint history_len,+ const uint num_rows,+ const uint k_pitch,+ const uint v_pitch+# if QSA_DENSE_QUANT+ ,+ const uint k_ppitch,+ const uint v_ppitch+# endif+#endif+) {+ const uint HQ = QSA_HEADS;+ const uint HKV = QSA_KV_HEADS;+ const uint DH = QSA_K_HEAD_SIZE;+ const uint DV = QSA_V_HEAD_SIZE;+ const uint R = QSA_COMPRESS_RATIO;+ const uint K_TOPK = QSA_BLOCK_TOPK;+ const uint lane = get_sub_group_local_id();++ const uint head = get_group_id(0);+ const uint kv_head = head / (HQ / HKV);++#if QSA_ADDRESS_MODE == 0+ const uint token_idx = get_group_id(1);+ if (head >= HQ || token_idx >= num_tokens) {+ return;+ }+ uint seq = 0, abs_pos = 0;+ if (!FUNC_CALL(qsa_resolve_token_paged)(subsequence_begins, past_lens, num_seqs, token_idx, &seq, &abs_pos)) {+ return;+ }+ const uint page_begin = (uint)block_indices_begins[seq];+ const uint q_elem = q_base + token_idx * q_pitch + head * DH;+ const uint sel_row = token_idx;+ const uint selected = (uint)selected_counts[sel_row];+ const bool has_tail = true;+ const uint out_elem = (token_idx * HQ + head) * DV;+#else+ const uint row = get_group_id(1);+ if (head >= HQ || row >= num_rows) {+ return;+ }+ const uint batch = row / seq_len;+ const uint l = row - batch * seq_len;+ uint kl = (uint)key_length[batch];+ kl = kl < history_len ? kl : history_len;+ // Left-padded K/V: logical key j of this row is stored at row (history_len - kl) + j.+ const uint shift = history_len - kl;+ const bool pad_row = kl + l < seq_len;+ const uint abs_pos = kl + l - seq_len;+ const uint q_elem = ((batch * HQ + head) * seq_len + l) * DH;+ const uint sel_row = row;+ const uint selected = pad_row ? 0 : (uint)selected_counts[sel_row];+ const bool has_tail = !pad_row;+ const uint out_elem = ((batch * HQ + head) * seq_len + l) * DV;+#endif++ float q[QSA_NEK];+ unroll_for (uint j = 0; j < QSA_NEK; j++) {+ q[j] = convert_float(query[q_elem + lane + QSA_SG * j]) * (float)QSA_SCALE;+ }++ float running_max = -1e30f;+ float running_sum = 0.0f;+ float acc[QSA_NEV];+ unroll_for (uint j = 0; j < QSA_NEV; j++) {+ acc[j] = 0.0f;+ }++ for (uint i = 0; i < selected && i < K_TOPK; i++) {+ const int b = selected_blocks[sel_row * K_TOPK + i];+ if (b < 0) {+ continue;+ }+ const uint pos0 = (uint)b * R;+#if QSA_ANY_QUANT+ unroll_for (uint s = 0; s < R; s++) {+ float kf[QSA_NEK], vf[QSA_NEV];+ QSA_LOAD_K(kf, pos0 + s);+ QSA_LOAD_V(vf, pos0 + s);+ FUNC_CALL(qsa_scalar_attend_vals)(kf, vf, q, acc, &running_max, &running_sum);+ }+#else+ const uint kbase = QSA_KROW(pos0);+ const uint vbase = QSA_VROW(pos0);+ unroll_for (uint s = 0; s < R; s++) {+ FUNC_CALL(qsa_scalar_attend)(key_cache + kbase + s * DH, value_cache + vbase + s * DV, q, acc, &running_max, &running_sum);+ }+#endif+ }++ if (has_tail) {+ const uint tail_begin = FUNC_CALL(qsa_num_complete_blocks)(abs_pos) * R;+ for (uint p = tail_begin; p <= abs_pos; p++) {+#if QSA_ANY_QUANT+ float kf[QSA_NEK], vf[QSA_NEV];+ QSA_LOAD_K(kf, p);+ QSA_LOAD_V(vf, p);+ FUNC_CALL(qsa_scalar_attend_vals)(kf, vf, q, acc, &running_max, &running_sum);+#else+ FUNC_CALL(qsa_scalar_attend)(key_cache + QSA_KROW(p), value_cache + QSA_VROW(p), q, acc, &running_max, &running_sum);+#endif+ }+ }++ const float inv_sum = running_sum > 0.0f ? 1.0f / running_sum : 0.0f;+ float o[QSA_NEV];+ unroll_for (uint j = 0; j < QSA_NEV; j++) {+ o[j] = acc[j] * inv_sum;+ }+ FUNC_CALL(qsa_wr_f32)(output + out_elem, o, QSA_NEV);+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_split.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_split.clnew file mode 100644index 00000000000..3d6e6de938a--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_split.cl@@ -0,0 +1,126 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q3 decode, split-selected-KV variant, pass 1.+//+// Decode has one query per sequence, so a query-owned subgroup would leave the GPU idle. Each token's own selected+// list is split over QSA_SPLIT_PARTITIONS independent subgroups, each producing a partial (max, sum, weighted-V)+// state; sparse_attention_split_reduce.cl merges them. The last partition also owns the causal tail (also for K = 0).+// Every partition writes its whole row (zeros when empty): the reduce pass reads all of them unconditionally.+//+// JIT: as sparse_attention_scalar.cl plus QSA_SPLIT_PARTITIONS+// Dispatch: gws = [QSA_HEADS * SG, num_tokens (paged) | B*L (dense), QSA_SPLIT_PARTITIONS], lws = [SG, 1, 1]++#define QSA_ATTENTION_HELPERS+#include "qsa_common.cl"++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(sparse_attention_split)(QSA_ATT_INPUT_ARGS,+ __global float* partial_acc, // [tokens, Hq, P, Dv]+ __global float* partial_ml, // [tokens, Hq, P, 2]+#if QSA_ADDRESS_MODE == 0+ const uint num_tokens,+ const uint num_seqs,+ const uint q_base,+ const uint q_pitch+#else+ const uint seq_len,+ const uint history_len,+ const uint num_rows,+ const uint k_pitch,+ const uint v_pitch+#endif+) {+ const uint HQ = QSA_HEADS;+ const uint HKV = QSA_KV_HEADS;+ const uint DH = QSA_K_HEAD_SIZE;+ const uint DV = QSA_V_HEAD_SIZE;+ const uint R = QSA_COMPRESS_RATIO;+ const uint K_TOPK = QSA_BLOCK_TOPK;+ const uint P = QSA_SPLIT_PARTITIONS;+ const uint lane = get_sub_group_local_id();++ const uint head = get_group_id(0);+ const uint part = get_group_id(2);+ const uint kv_head = head / (HQ / HKV);++#if QSA_ADDRESS_MODE == 0+ const uint token_idx = get_group_id(1);+ if (head >= HQ || token_idx >= num_tokens || part >= P) {+ return;+ }+ uint seq = 0, abs_pos = 0;+ if (!FUNC_CALL(qsa_resolve_token_paged)(subsequence_begins, past_lens, num_seqs, token_idx, &seq, &abs_pos)) {+ return;+ }+ const uint page_begin = (uint)block_indices_begins[seq];+ const uint q_elem = q_base + token_idx * q_pitch + head * DH;+ const uint sel_row = token_idx;+ const uint count = (uint)selected_counts[sel_row];+ const bool has_tail = true;+#else+ const uint row = get_group_id(1);+ if (head >= HQ || row >= num_rows || part >= P) {+ return;+ }+ const uint batch = row / seq_len;+ const uint l = row - batch * seq_len;+ uint kl = (uint)key_length[batch];+ kl = kl < history_len ? kl : history_len;+ const uint shift = history_len - kl;+ const bool pad_row = kl + l < seq_len;+ const uint abs_pos = kl + l - seq_len;+ const uint q_elem = ((batch * HQ + head) * seq_len + l) * DH;+ const uint sel_row = row;+ const uint count = pad_row ? 0 : (uint)selected_counts[sel_row];+ const bool has_tail = !pad_row;+#endif++ float q[QSA_NEK];+ unroll_for (uint j = 0; j < QSA_NEK; j++) {+ q[j] = convert_float(query[q_elem + lane + QSA_SG * j]) * (float)QSA_SCALE;+ }++ float running_max = -1e30f;+ float running_sum = 0.0f;+ float acc[QSA_NEV];+ unroll_for (uint j = 0; j < QSA_NEV; j++) {+ acc[j] = 0.0f;+ }++ // Split slot ranges, not absolute positions, so every partition's share of the list is contiguous.+ const uint selected = count < K_TOPK ? count : K_TOPK;+ const uint begin = selected * part / P;+ const uint end = selected * (part + 1) / P;+ for (uint i = begin; i < end; i++) {+ const int b = selected_blocks[sel_row * K_TOPK + i];+ if (b < 0) {+ continue; // must precede any KV address computation+ }+ const uint pos0 = (uint)b * R;+ const uint kbase = QSA_KROW(pos0);+ const uint vbase = QSA_VROW(pos0);+ unroll_for (uint s = 0; s < R; s++) {+ FUNC_CALL(qsa_scalar_attend)(key_cache + kbase + s * DH, value_cache + vbase + s * DV, q, acc, &running_max, &running_sum);+ }+ }+ if (part == P - 1 && has_tail) {+ for (uint pos = FUNC_CALL(qsa_num_complete_blocks)(abs_pos) * R; pos <= abs_pos; pos++) {+ FUNC_CALL(qsa_scalar_attend)(key_cache + QSA_KROW(pos), value_cache + QSA_VROW(pos), q, acc, &running_max, &running_sum);+ }+ }++#if QSA_ADDRESS_MODE == 0+ const uint prow = (token_idx * HQ + head) * P + part;+#else+ const uint prow = (row * HQ + head) * P + part;+#endif+ if (lane == 0) {+ partial_ml[prow * 2] = running_max;+ partial_ml[prow * 2 + 1] = running_sum;+ }+ unroll_for (uint j = 0; j < QSA_NEV; j++) {+ partial_acc[prow * DV + lane + QSA_SG * j] = acc[j];+ }+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_split_reduce.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_split_reduce.clnew file mode 100644index 00000000000..89332c58da1--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sparse_attention_split_reduce.cl@@ -0,0 +1,99 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Q3 decode, split-selected-KV variant, pass 2 - merge.+//+// Merges the (max, sum, weighted-V) state of every partition with the online-softmax combine rule. The maxima are in+// natural-log units. An empty partition (sum <= 0) is skipped BEFORE exponentiating so its possibly garbage max can+// not contaminate the running max.+//+// JIT: QSA_HEADS, QSA_V_HEAD_SIZE, QSA_SPLIT_PARTITIONS, QSA_REDUCE_COLS, QSA_ADDRESS_MODE, SUBGROUP_SIZE+// Dispatch: gws = [QSA_HEADS * SG, num_rows, QSA_V_HEAD_SIZE / QSA_REDUCE_COLS], lws = [SG, 1, 1]++#include "qsa_common.cl"++#ifndef QSA_ADDRESS_MODE+# define QSA_ADDRESS_MODE 0+#endif++REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)+KERNEL(sparse_attention_split_reduce)(const __global float* partial_acc, // [rows, Hq, P, Dv]+ const __global float* partial_ml, // [rows, Hq, P, 2]+ __global half* output, // paged: [rows, Hq*Dv]; dense: [B, Hq, L, Dv]+#if QSA_ADDRESS_MODE == 0+ const uint num_rows+#else+ const uint seq_len,+ const uint num_rows+#endif+) {+ const uint HQ = QSA_HEADS;+ const uint DV = QSA_V_HEAD_SIZE;+ const uint P = QSA_SPLIT_PARTITIONS;+ const uint COLS = QSA_REDUCE_COLS;+ const uint lane = get_sub_group_local_id();++ const uint head = get_group_id(0);+ const uint row = get_group_id(1);+ const uint col0 = get_group_id(2) * COLS;+ if (head >= HQ || row >= num_rows || col0 >= DV) {+ return;+ }++ const uint row0 = (row * HQ + head) * P;+ const uint PG = (QSA_SPLIT_PARTITIONS + QSA_SG - 1) / QSA_SG;++ // Lane i of group g holds partition g * SG + i; an empty partition contributes neither max nor weight.+ float m[(QSA_SPLIT_PARTITIONS + QSA_SG - 1) / QSA_SG];+ float l[(QSA_SPLIT_PARTITIONS + QSA_SG - 1) / QSA_SG];+ float m_max = -1e30f;+ unroll_for (uint g = 0; g < PG; g++) {+ const uint p = g * QSA_SG + lane;+ const float2 ml = p < P ? vload2(row0 + p, partial_ml) : (float2)(-1e30f, 0.0f);+ l[g] = ml.s1;+ m[g] = ml.s1 > 0.0f ? ml.s0 : -1e30f;+ m_max = fmax(m_max, m[g]);+ }+ m_max = sub_group_reduce_max(m_max);++ float w[(QSA_SPLIT_PARTITIONS + QSA_SG - 1) / QSA_SG];+ float sum = 0.0f;+ unroll_for (uint g = 0; g < PG; g++) {+ w[g] = l[g] > 0.0f ? native_exp2((m[g] - m_max) * QSA_LOG2E) : 0.0f;+ sum += w[g] * l[g];+ }+ sum = sub_group_reduce_add(sum);++ float acc[QSA_REDUCE_COLS / QSA_SG];+ unroll_for (uint j = 0; j < COLS / QSA_SG; j++) {+ acc[j] = 0.0f;+ }+ // Every producer writes all P rows (zeros when empty), so unconditional loads are safe.+ unroll_for (uint p = 0; p < P; p++) {+ const float wp = sub_group_broadcast(w[p / QSA_SG], p % QSA_SG);+ const __global uint* src = (const __global uint*)(partial_acc + (row0 + p) * DV + col0);+#if QSA_REDUCE_COLS == 2 * SUBGROUP_SIZE+ const float2 a = as_float2(intel_sub_group_block_read2(src));+ acc[0] += a.s0 * wp;+ acc[1] += a.s1 * wp;+#else+ unroll_for (uint j = 0; j < COLS / QSA_SG; j++) {+ acc[j] += as_float(intel_sub_group_block_read(src + j * QSA_SG)) * wp;+ }+#endif+ }++ const float inv_sum = sum > 0.0f ? 1.0f / sum : 0.0f;+ float o[QSA_REDUCE_COLS / QSA_SG];+ unroll_for (uint j = 0; j < COLS / QSA_SG; j++) {+ o[j] = acc[j] * inv_sum;+ }+#if QSA_ADDRESS_MODE == 0+ const uint out_row = row * HQ + head;+#else+ const uint batch = row / seq_len;+ const uint out_row = (batch * HQ + head) * seq_len + (row - batch * seq_len);+#endif+ FUNC_CALL(qsa_wr_f32)(output + out_row * DV + col0, o, COLS / QSA_SG);+}diff --git a/src/plugins/intel_gpu/src/graph/include/paged_qsa_indexer_inst.h b/src/plugins/intel_gpu/src/graph/include/paged_qsa_indexer_inst.hnew file mode 100644index 00000000000..226a1772671--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/include/paged_qsa_indexer_inst.h@@ -0,0 +1,43 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "intel_gpu/primitives/paged_qsa_indexer.hpp"+#include "primitive_inst.h"++namespace cldnn {++template <>+struct typed_program_node<paged_qsa_indexer> : public typed_program_node_base<paged_qsa_indexer> {+ using parent = typed_program_node_base<paged_qsa_indexer>;++public:+ using parent::parent;++ program_node& input(size_t index = 0) const {+ return get_dependency(index);+ }+};+using paged_qsa_indexer_node = typed_program_node<paged_qsa_indexer>;++template <>+class typed_primitive_inst<paged_qsa_indexer> : public typed_primitive_inst_base<paged_qsa_indexer> {+ using parent = typed_primitive_inst_base<paged_qsa_indexer>;+ using parent::parent;++public:+ template <typename ShapeType>+ static std::vector<layout> calc_output_layouts(const paged_qsa_indexer_node& node, const kernel_impl_params& impl_params);+ static layout calc_output_layout(const paged_qsa_indexer_node& node, const kernel_impl_params& impl_params);++ static std::string to_string(const paged_qsa_indexer_node& node);+ typed_primitive_inst(network& network, const paged_qsa_indexer_node& node);+};++using paged_qsa_indexer_inst = typed_primitive_inst<paged_qsa_indexer>;++} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/include/qsa_indexer_inst.h b/src/plugins/intel_gpu/src/graph/include/qsa_indexer_inst.hnew file mode 100644index 00000000000..bd2c9878c81--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/include/qsa_indexer_inst.h@@ -0,0 +1,43 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "intel_gpu/primitives/qsa_indexer.hpp"+#include "primitive_inst.h"++namespace cldnn {++template <>+struct typed_program_node<qsa_indexer> : public typed_program_node_base<qsa_indexer> {+ using parent = typed_program_node_base<qsa_indexer>;++public:+ using parent::parent;++ program_node& input(size_t index = 0) const {+ return get_dependency(index);+ }+};+using qsa_indexer_node = typed_program_node<qsa_indexer>;++template <>+class typed_primitive_inst<qsa_indexer> : public typed_primitive_inst_base<qsa_indexer> {+ using parent = typed_primitive_inst_base<qsa_indexer>;+ using parent::parent;++public:+ template <typename ShapeType>+ static std::vector<layout> calc_output_layouts(const qsa_indexer_node& node, const kernel_impl_params& impl_params);+ static layout calc_output_layout(const qsa_indexer_node& node, const kernel_impl_params& impl_params);++ static std::string to_string(const qsa_indexer_node& node);+ typed_primitive_inst(network& network, const qsa_indexer_node& node);+};++using qsa_indexer_inst = typed_primitive_inst<qsa_indexer>;++} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/include/sparse_pa_inst.h b/src/plugins/intel_gpu/src/graph/include/sparse_pa_inst.hnew file mode 100644index 00000000000..a569e31313c--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/include/sparse_pa_inst.h@@ -0,0 +1,49 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "intel_gpu/primitives/sparse_pa.hpp"+#include "primitive_inst.h"++namespace cldnn {++template <>+struct typed_program_node<sparse_pa> : public typed_program_node_base<sparse_pa> {+ using parent = typed_program_node_base<sparse_pa>;++public:+ using parent::parent;++ program_node& input(size_t index = 0) const {+ return get_dependency(index);+ }++ // Output shapes come from the query alone; past_lens / subsequence_begins stay in GPU+ // memory (the impl sizes everything from shape-derived bounds), so no host readback.+ std::vector<size_t> get_shape_infer_dependencies() const override {+ return {};+ }+};+using sparse_pa_node = typed_program_node<sparse_pa>;++template <>+class typed_primitive_inst<sparse_pa> : public typed_primitive_inst_base<sparse_pa> {+ using parent = typed_primitive_inst_base<sparse_pa>;+ using parent::parent;++public:+ template <typename ShapeType>+ static std::vector<layout> calc_output_layouts(const sparse_pa_node& node, const kernel_impl_params& impl_params);+ static layout calc_output_layout(const sparse_pa_node& node, const kernel_impl_params& impl_params);++ static std::string to_string(const sparse_pa_node& node);+ typed_primitive_inst(network& network, const sparse_pa_node& node);+};++using sparse_pa_inst = typed_primitive_inst<sparse_pa>;++} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/include/sparse_sdpa_inst.h b/src/plugins/intel_gpu/src/graph/include/sparse_sdpa_inst.hnew file mode 100644index 00000000000..97b4a975227--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/include/sparse_sdpa_inst.h@@ -0,0 +1,43 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "intel_gpu/primitives/sparse_sdpa.hpp"+#include "primitive_inst.h"++namespace cldnn {++template <>+struct typed_program_node<sparse_sdpa> : public typed_program_node_base<sparse_sdpa> {+ using parent = typed_program_node_base<sparse_sdpa>;++public:+ using parent::parent;++ program_node& input(size_t index = 0) const {+ return get_dependency(index);+ }+};+using sparse_sdpa_node = typed_program_node<sparse_sdpa>;++template <>+class typed_primitive_inst<sparse_sdpa> : public typed_primitive_inst_base<sparse_sdpa> {+ using parent = typed_primitive_inst_base<sparse_sdpa>;+ using parent::parent;++public:+ template <typename ShapeType>+ static std::vector<layout> calc_output_layouts(const sparse_sdpa_node& node, const kernel_impl_params& impl_params);+ static layout calc_output_layout(const sparse_sdpa_node& node, const kernel_impl_params& impl_params);++ static std::string to_string(const sparse_sdpa_node& node);+ typed_primitive_inst(network& network, const sparse_sdpa_node& node);+};++using sparse_sdpa_inst = typed_primitive_inst<sparse_sdpa>;++} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/paged_qsa_indexer.cpp b/src/plugins/intel_gpu/src/graph/paged_qsa_indexer.cppnew file mode 100644index 00000000000..ac0d3ef1cb9--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/paged_qsa_indexer.cpp@@ -0,0 +1,67 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <sstream>+#include <string>+#include <vector>++#include "json_object.h"+#include "paged_qsa_indexer_inst.h"+#include "primitive_type_base.h"+#include "to_string_utils.h"++namespace cldnn {++GPU_DEFINE_PRIMITIVE_TYPE_ID(paged_qsa_indexer)++layout paged_qsa_indexer_inst::calc_output_layout(const paged_qsa_indexer_node& node, const kernel_impl_params& impl_param) {+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[0];+}++template <typename ShapeType>+std::vector<layout> paged_qsa_indexer_inst::calc_output_layouts(const paged_qsa_indexer_node& node, const kernel_impl_params& impl_param) {+ const auto& desc = impl_param.typed_desc<paged_qsa_indexer>();+ const auto index_query_shape = impl_param.get_input_layout(paged_qsa_indexer::InputIdx::INDEX_QUERY).get<ShapeType>();+ OPENVINO_ASSERT(index_query_shape.rank().is_static() && index_query_shape.size() == 2,+ "[GPU] paged_qsa_indexer expects a rank-2 [tokens, H_iq*D_idx] index_query input");++ const auto num_selection_heads_dim = ov::Dimension(static_cast<int64_t>(desc->num_selection_heads));+ ShapeType selected_block_indices_shape{index_query_shape[0], num_selection_heads_dim, ov::Dimension(static_cast<int64_t>(desc->block_topk))};+ ShapeType selected_block_count_shape{index_query_shape[0], num_selection_heads_dim};++ return {layout{selected_block_indices_shape, ov::element::i32, cldnn::format::get_default_format(selected_block_indices_shape.size())},+ layout{selected_block_count_shape, ov::element::i32, cldnn::format::get_default_format(selected_block_count_shape.size())}};+}++template std::vector<layout> paged_qsa_indexer_inst::calc_output_layouts<ov::PartialShape>(const paged_qsa_indexer_node& node,+ const kernel_impl_params& impl_param);++std::string paged_qsa_indexer_inst::to_string(const paged_qsa_indexer_node& node) {+ auto node_info = node.desc_to_json();+ auto desc = node.get_primitive();++ std::stringstream primitive_description;+ json_composite info;+ info.add("key_block_size", desc->key_block_size);+ info.add("block_topk", desc->block_topk);+ info.add("num_selection_heads", desc->num_selection_heads);+ info.add("indexer_head_dim", desc->indexer_head_dim);+ info.add("indexer_rotary_dim", desc->indexer_rotary_dim);+ info.add("scale", desc->scale);+ node_info->add("paged_qsa_indexer_info", info);+ node_info->dump(primitive_description);++ return primitive_description.str();+}++paged_qsa_indexer_inst::typed_primitive_inst(network& network, const paged_qsa_indexer_node& node) : parent(network, node) {+ std::string reason;+ OPENVINO_ASSERT(ov::intel_gpu::op::PagedQSAIndexer::validate_config(node.get_primitive()->get_config(), reason),+ "[GPU] Invalid paged_qsa_indexer primitive: ",+ reason);+}++} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::paged_qsa_indexer)diff --git a/src/plugins/intel_gpu/src/graph/qsa_indexer.cpp b/src/plugins/intel_gpu/src/graph/qsa_indexer.cppnew file mode 100644index 00000000000..30fa2606dc6--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/qsa_indexer.cpp@@ -0,0 +1,78 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <sstream>+#include <string>+#include <vector>++#include "json_object.h"+#include "primitive_type_base.h"+#include "qsa_indexer_inst.h"+#include "to_string_utils.h"++namespace cldnn {++GPU_DEFINE_PRIMITIVE_TYPE_ID(qsa_indexer)++layout qsa_indexer_inst::calc_output_layout(const qsa_indexer_node& node, const kernel_impl_params& impl_param) {+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[0];+}++template <typename ShapeType>+std::vector<layout> qsa_indexer_inst::calc_output_layouts(const qsa_indexer_node& node, const kernel_impl_params& impl_param) {+ const auto& desc = impl_param.typed_desc<qsa_indexer>();+ const auto index_query_shape = impl_param.get_input_layout(qsa_indexer::InputIdx::INDEX_QUERY).get<ShapeType>();+ OPENVINO_ASSERT(index_query_shape.rank().is_static() && index_query_shape.size() == 4,+ "[GPU] qsa_indexer expects a rank-4 [B, L, H_iq, D_idx] index_query input");++ const auto num_selection_heads_dim = ov::Dimension(static_cast<int64_t>(desc->num_selection_heads));+ ShapeType selected_block_indices_shape{index_query_shape[0],+ num_selection_heads_dim,+ index_query_shape[1],+ ov::Dimension(static_cast<int64_t>(desc->block_topk))};+ ShapeType selected_block_count_shape{index_query_shape[0], num_selection_heads_dim, index_query_shape[1]};++ std::vector<layout> layouts = {+ layout{selected_block_indices_shape, ov::element::i32, cldnn::format::get_default_format(selected_block_indices_shape.size())},+ layout{selected_block_count_shape, ov::element::i32, cldnn::format::get_default_format(selected_block_count_shape.size())}};+ // The updated state has the shape and type of the corresponding state input.+ for (size_t in :+ {qsa_indexer::InputIdx::BLOCK_INDEX_KEYS_CACHE, qsa_indexer::InputIdx::PAST_INCOMPLETE_RAW_K, qsa_indexer::InputIdx::PAST_INCOMPLETE_ROPE}) {+ const auto& in_layout = impl_param.get_input_layout(in);+ const auto shape = in_layout.get<ShapeType>();+ layouts.emplace_back(shape, in_layout.data_type, cldnn::format::get_default_format(shape.size()));+ }+ return layouts;+}++template std::vector<layout> qsa_indexer_inst::calc_output_layouts<ov::PartialShape>(const qsa_indexer_node& node, const kernel_impl_params& impl_param);++std::string qsa_indexer_inst::to_string(const qsa_indexer_node& node) {+ auto node_info = node.desc_to_json();+ auto desc = node.get_primitive();++ std::stringstream primitive_description;+ json_composite info;+ info.add("key_block_size", desc->key_block_size);+ info.add("block_topk", desc->block_topk);+ info.add("num_selection_heads", desc->num_selection_heads);+ info.add("indexer_head_dim", desc->indexer_head_dim);+ info.add("indexer_rotary_dim", desc->indexer_rotary_dim);+ info.add("scale", desc->scale);+ node_info->add("qsa_indexer_info", info);+ node_info->dump(primitive_description);++ return primitive_description.str();+}++qsa_indexer_inst::typed_primitive_inst(network& network, const qsa_indexer_node& node) : parent(network, node) {+ std::string reason;+ OPENVINO_ASSERT(ov::intel_gpu::op::QSAIndexer::validate_config(node.get_primitive()->get_config(), reason),+ "[GPU] Invalid qsa_indexer primitive: ",+ reason);+}++} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::qsa_indexer)diff --git a/src/plugins/intel_gpu/src/graph/registry/paged_qsa_indexer_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/paged_qsa_indexer_impls.cppnew file mode 100644index 00000000000..29ecb380e22--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/registry/paged_qsa_indexer_impls.cpp@@ -0,0 +1,27 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/primitives/paged_qsa_indexer.hpp"+#include "primitive_inst.h"+#include "registry.hpp"++#if OV_GPU_WITH_OCL+# include "impls/ocl_v2/qsa_indexer/paged_qsa_indexer.hpp"+#endif++namespace ov::intel_gpu {++using namespace cldnn;++const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<paged_qsa_indexer>::get_implementations() {+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+#if OV_GPU_WITH_OCL+ OV_GPU_CREATE_INSTANCE_OCL(ocl::PagedQSAIndexerImplementationManager, shape_types::any)+#endif+ };++ return impls;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/registry/qsa_indexer_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/qsa_indexer_impls.cppnew file mode 100644index 00000000000..ee8f7fdb9f6--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/registry/qsa_indexer_impls.cpp@@ -0,0 +1,27 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/primitives/qsa_indexer.hpp"+#include "primitive_inst.h"+#include "registry.hpp"++#if OV_GPU_WITH_OCL+# include "impls/ocl_v2/qsa_indexer/qsa_indexer.hpp"+#endif++namespace ov::intel_gpu {++using namespace cldnn;++const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<qsa_indexer>::get_implementations() {+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+#if OV_GPU_WITH_OCL+ OV_GPU_CREATE_INSTANCE_OCL(ocl::QSAIndexerImplementationManager, shape_types::any)+#endif+ };++ return impls;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/registry/registry.hpp b/src/plugins/intel_gpu/src/graph/registry/registry.hppindex 4bdcf726d34..c3d21bd232d 100644--- a/src/plugins/intel_gpu/src/graph/registry/registry.hpp+++ b/src/plugins/intel_gpu/src/graph/registry/registry.hpp@@ -195,6 +195,10 @@ REGISTER_IMPLS(gather_matmul);REGISTER_IMPLS(mlir_primitive);#endifREGISTER_IMPLS(grouped_matmul);+REGISTER_IMPLS(paged_qsa_indexer);+REGISTER_IMPLS(qsa_indexer);+REGISTER_IMPLS(sparse_pa);+REGISTER_IMPLS(sparse_sdpa);REGISTER_DEFAULT_IMPLS(assign, CPU_S, CPU_D);REGISTER_DEFAULT_IMPLS(read_value, CPU_S, CPU_D);diff --git a/src/plugins/intel_gpu/src/graph/registry/sparse_pa_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/sparse_pa_impls.cppnew file mode 100644index 00000000000..170113b7e28--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/registry/sparse_pa_impls.cpp@@ -0,0 +1,27 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/primitives/sparse_pa.hpp"+#include "primitive_inst.h"+#include "registry.hpp"++#if OV_GPU_WITH_OCL+# include "impls/ocl_v2/sparse_attention/sparse_pa.hpp"+#endif++namespace ov::intel_gpu {++using namespace cldnn;++const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<sparse_pa>::get_implementations() {+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+#if OV_GPU_WITH_OCL+ OV_GPU_CREATE_INSTANCE_OCL(ocl::SparsePAImplementationManager, shape_types::any)+#endif+ };++ return impls;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/registry/sparse_sdpa_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/sparse_sdpa_impls.cppnew file mode 100644index 00000000000..4e2e3733d1c--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/registry/sparse_sdpa_impls.cpp@@ -0,0 +1,27 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/primitives/sparse_sdpa.hpp"+#include "primitive_inst.h"+#include "registry.hpp"++#if OV_GPU_WITH_OCL+# include "impls/ocl_v2/sparse_attention/sparse_sdpa.hpp"+#endif++namespace ov::intel_gpu {++using namespace cldnn;++const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<sparse_sdpa>::get_implementations() {+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+#if OV_GPU_WITH_OCL+ OV_GPU_CREATE_INSTANCE_OCL(ocl::SparseSDPAImplementationManager, shape_types::any)+#endif+ };++ return impls;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/sources.cmake b/src/plugins/intel_gpu/src/graph/sources.cmakeindex 600c97ce3a8..18d2ef8bb0f 100644--- a/src/plugins/intel_gpu/src/graph/sources.cmake+++ b/src/plugins/intel_gpu/src/graph/sources.cmake@@ -181,6 +181,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/include/paged_attention_inst.h${CMAKE_CURRENT_LIST_DIR}/include/paged_causal_conv1d_inst.h${CMAKE_CURRENT_LIST_DIR}/include/paged_gated_delta_net_inst.h+ ${CMAKE_CURRENT_LIST_DIR}/include/paged_qsa_indexer_inst.h${CMAKE_CURRENT_LIST_DIR}/include/paged_selective_ssm_inst.h${CMAKE_CURRENT_LIST_DIR}/include/pass_manager.h${CMAKE_CURRENT_LIST_DIR}/include/permute_inst.h@@ -193,6 +194,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/include/program_helpers.h${CMAKE_CURRENT_LIST_DIR}/include/program_node.h${CMAKE_CURRENT_LIST_DIR}/include/proposal_inst.h+ ${CMAKE_CURRENT_LIST_DIR}/include/qsa_indexer_inst.h${CMAKE_CURRENT_LIST_DIR}/include/quantize_inst.h${CMAKE_CURRENT_LIST_DIR}/include/random_uniform_inst.h${CMAKE_CURRENT_LIST_DIR}/include/range_inst.h@@ -227,6 +229,8 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/include/space_to_batch_inst.h${CMAKE_CURRENT_LIST_DIR}/include/space_to_depth_inst.h${CMAKE_CURRENT_LIST_DIR}/include/sparse_fill_empty_rows_inst.h+ ${CMAKE_CURRENT_LIST_DIR}/include/sparse_pa_inst.h+ ${CMAKE_CURRENT_LIST_DIR}/include/sparse_sdpa_inst.h${CMAKE_CURRENT_LIST_DIR}/include/stateless_kv_inst.h${CMAKE_CURRENT_LIST_DIR}/include/stft_inst.h${CMAKE_CURRENT_LIST_DIR}/include/strided_slice_inst.h@@ -270,6 +274,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/paged_attention.cpp${CMAKE_CURRENT_LIST_DIR}/paged_causal_conv1d.cpp${CMAKE_CURRENT_LIST_DIR}/paged_gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/paged_qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/paged_selective_ssm.cpp${CMAKE_CURRENT_LIST_DIR}/pass_manager.cpp${CMAKE_CURRENT_LIST_DIR}/permute.cpp@@ -281,6 +286,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/program_helpers.cpp${CMAKE_CURRENT_LIST_DIR}/program_node.cpp${CMAKE_CURRENT_LIST_DIR}/proposal.cpp+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/quantize.cpp${CMAKE_CURRENT_LIST_DIR}/random_uniform.cpp${CMAKE_CURRENT_LIST_DIR}/range.cpp@@ -330,10 +336,12 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/registry/paged_attention_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/paged_causal_conv1d_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/paged_gated_delta_net_impls.cpp+ ${CMAKE_CURRENT_LIST_DIR}/registry/paged_qsa_indexer_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/paged_selective_ssm_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/pooling_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/predicates.cpp${CMAKE_CURRENT_LIST_DIR}/registry/predicates.hpp+ ${CMAKE_CURRENT_LIST_DIR}/registry/qsa_indexer_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/range_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/reduce_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/registry.hpp@@ -350,6 +358,8 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/registry/shape_of_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/slice_scatter_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/softmax_impls.cpp+ ${CMAKE_CURRENT_LIST_DIR}/registry/sparse_pa_impls.cpp+ ${CMAKE_CURRENT_LIST_DIR}/registry/sparse_sdpa_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/strided_slice_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/tile_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/vl_sdpa_impls.cpp@@ -380,6 +390,8 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/space_to_batch.cpp${CMAKE_CURRENT_LIST_DIR}/space_to_depth.cpp${CMAKE_CURRENT_LIST_DIR}/sparse_fill_empty_rows.cpp+ ${CMAKE_CURRENT_LIST_DIR}/sparse_pa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/sparse_sdpa.cpp${CMAKE_CURRENT_LIST_DIR}/stateless_kv.cpp${CMAKE_CURRENT_LIST_DIR}/stft.cpp${CMAKE_CURRENT_LIST_DIR}/strided_slice.cppdiff --git a/src/plugins/intel_gpu/src/graph/sparse_pa.cpp b/src/plugins/intel_gpu/src/graph/sparse_pa.cppnew file mode 100644index 00000000000..e88aeb2fafd--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/sparse_pa.cpp@@ -0,0 +1,73 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <sstream>+#include <string>+#include <vector>++#include "json_object.h"+#include "primitive_type_base.h"+#include "sparse_pa_inst.h"+#include "to_string_utils.h"++namespace cldnn {++GPU_DEFINE_PRIMITIVE_TYPE_ID(sparse_pa)++layout sparse_pa_inst::calc_output_layout(const sparse_pa_node& node, const kernel_impl_params& impl_param) {+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[0];+}++template <typename ShapeType>+std::vector<layout> sparse_pa_inst::calc_output_layouts(const sparse_pa_node& node, const kernel_impl_params& impl_param) {+ const auto& desc = impl_param.typed_desc<sparse_pa>();+ const auto query_layout = impl_param.get_input_layout(sparse_pa::InputIdx::QUERY);++ auto out_shape = ShapeType{query_layout.get<ShapeType>()};+ OPENVINO_ASSERT(out_shape.rank().is_static() && out_shape.size() >= 2 &&+ std::all_of(out_shape.begin() + 2,+ out_shape.end(),+ [](const ov::Dimension& dim) {+ return dim.compatible(1);+ }),+ "[GPU] sparse_pa expects a rank-2 [tokens, num_heads*k_head_size] query input, got ",+ query_layout.to_short_string());+ out_shape[1] = ov::Dimension(static_cast<int64_t>(desc->num_heads * desc->v_head_size));++ const auto out_dt =+ desc->output_data_types.empty() || !desc->output_data_types[0].has_value() ? query_layout.data_type : desc->output_data_types[0].value();+ return {layout{out_shape, out_dt, query_layout.format}};+}++template std::vector<layout> sparse_pa_inst::calc_output_layouts<ov::PartialShape>(const sparse_pa_node& node, const kernel_impl_params& impl_param);++std::string sparse_pa_inst::to_string(const sparse_pa_node& node) {+ auto node_info = node.desc_to_json();+ auto desc = node.get_primitive();++ std::stringstream primitive_description;+ json_composite info;+ info.add("num_heads", desc->num_heads);+ info.add("num_kv_heads", desc->num_kv_heads);+ info.add("num_selection_heads", desc->num_selection_heads);+ info.add("k_head_size", desc->k_head_size);+ info.add("v_head_size", desc->v_head_size);+ info.add("key_block_size", desc->key_block_size);+ info.add("scale", desc->scale);+ info.add("causal", desc->causal);+ node_info->add("sparse_pa_info", info);+ node_info->dump(primitive_description);++ return primitive_description.str();+}++sparse_pa_inst::typed_primitive_inst(network& network, const sparse_pa_node& node) : parent(network, node) {+ std::string reason;+ OPENVINO_ASSERT(sparse_pa::validate_config(node.get_primitive()->get_config(), reason), "[GPU] Invalid sparse_pa primitive: ", reason);+}++} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::sparse_pa)diff --git a/src/plugins/intel_gpu/src/graph/sparse_sdpa.cpp b/src/plugins/intel_gpu/src/graph/sparse_sdpa.cppnew file mode 100644index 00000000000..0f5df995426--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/sparse_sdpa.cpp@@ -0,0 +1,70 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <sstream>+#include <string>+#include <vector>++#include "json_object.h"+#include "primitive_type_base.h"+#include "sparse_sdpa_inst.h"+#include "to_string_utils.h"++namespace cldnn {++GPU_DEFINE_PRIMITIVE_TYPE_ID(sparse_sdpa)++layout sparse_sdpa_inst::calc_output_layout(const sparse_sdpa_node& node, const kernel_impl_params& impl_param) {+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[0];+}++template <typename ShapeType>+std::vector<layout> sparse_sdpa_inst::calc_output_layouts(const sparse_sdpa_node& node, const kernel_impl_params& impl_param) {+ const auto& desc = impl_param.typed_desc<sparse_sdpa>();+ const auto query_layout = impl_param.get_input_layout(sparse_sdpa::InputIdx::QUERY);+ auto query_shape = query_layout.get<ShapeType>();+ OPENVINO_ASSERT(query_shape.rank().is_static() && query_shape.size() == 4, "[GPU] sparse_sdpa expects a rank-4 [B, Hq, L, Dh] query input");++ ShapeType out_shape{query_shape[0],+ ov::Dimension(static_cast<int64_t>(desc->num_heads)),+ query_shape[2],+ ov::Dimension(static_cast<int64_t>(desc->v_head_size))};++ const auto out_dt =+ desc->output_data_types.empty() || !desc->output_data_types[0].has_value() ? query_layout.data_type : desc->output_data_types[0].value();+ return {layout{out_shape, out_dt, query_layout.format}};+}++template std::vector<layout> sparse_sdpa_inst::calc_output_layouts<ov::PartialShape>(const sparse_sdpa_node& node, const kernel_impl_params& impl_param);++std::string sparse_sdpa_inst::to_string(const sparse_sdpa_node& node) {+ auto node_info = node.desc_to_json();+ auto desc = node.get_primitive();++ std::stringstream primitive_description;+ json_composite info;+ info.add("num_heads", desc->num_heads);+ info.add("num_kv_heads", desc->num_kv_heads);+ info.add("num_selection_heads", desc->num_selection_heads);+ info.add("k_head_size", desc->k_head_size);+ info.add("v_head_size", desc->v_head_size);+ info.add("key_block_size", desc->key_block_size);+ info.add("causal", desc->causal);+ info.add("scale", desc->scale);+ node_info->add("sparse_sdpa_info", info);+ node_info->dump(primitive_description);++ return primitive_description.str();+}++sparse_sdpa_inst::typed_primitive_inst(network& network, const sparse_sdpa_node& node) : parent(network, node) {+ std::string reason;+ OPENVINO_ASSERT(ov::intel_gpu::op::SparseSDPA::validate_config(node.get_primitive()->get_config(), reason),+ "[GPU] Invalid sparse_sdpa primitive: ",+ reason);+}++} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::sparse_sdpa)diff --git a/src/plugins/intel_gpu/src/plugin/ops/paged_qsa_indexer.cpp b/src/plugins/intel_gpu/src/plugin/ops/paged_qsa_indexer.cppnew file mode 100644index 00000000000..7f68a4de151--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/paged_qsa_indexer.cpp@@ -0,0 +1,61 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/paged_qsa_indexer.hpp"++#include "intel_gpu/plugin/common_utils.hpp"+#include "intel_gpu/plugin/program_builder.hpp"+#include "intel_gpu/primitives/paged_qsa_indexer.hpp"++namespace ov::op::internal {+// The core ov::op::internal::PagedQSAIndexer already owns the plain name; like MLIR/MLIROp, the alias differs.+using PagedQSAIndexerGPU = ov::intel_gpu::op::PagedQSAIndexer;+} // namespace ov::op::internal++namespace ov::intel_gpu {++static void CreatePagedQSAIndexerGPUOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::PagedQSAIndexerGPU>& op) {+ using In = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;+ validate_inputs_count(op, {In::COUNT});+ const auto inputs = p.GetInputInfo(op);+ const auto layer_name = layer_type_name_ID(op);++ std::string reason;+ OPENVINO_ASSERT(ov::intel_gpu::op::PagedQSAIndexer::validate_config(op->get_config(), reason),+ "[GPU] Cannot lower PagedQSAIndexer op '",+ layer_name,+ "': ",+ reason);++ OPENVINO_ASSERT(op->get_config().num_selection_heads == 1,+ "[GPU] PagedQSAIndexer '",+ layer_name,+ "': only num_selection_heads == 1 is supported, got ",+ op->get_config().num_selection_heads);+ OPENVINO_ASSERT(op->get_index_key_heads() == 1, "[GPU] PagedQSAIndexer '", layer_name, "': only H_ik == 1 is supported, got ", op->get_index_key_heads());+ for (size_t idx : {In::INDEX_QUERY,+ In::RAW_INDEX_KEYS,+ In::ROPE_COS,+ In::ROPE_SIN,+ In::BLOCK_INDEX_KEYS_CACHE,+ In::INDEX_KEY_CACHE,+ In::Q_NORM_WEIGHT,+ In::K_NORM_WEIGHT,+ In::INDEX_BLOCK_ROPE_CACHE}) {+ OPENVINO_ASSERT(op->get_input_element_type(idx) == ov::element::f16,+ "[GPU] PagedQSAIndexer '",+ layer_name,+ "': input ",+ idx,+ " must be f16, got ",+ op->get_input_element_type(idx));+ }++ cldnn::paged_qsa_indexer prim(layer_name, inputs, op->get_config());+ p.add_primitive(*op, prim);+}++REGISTER_FACTORY_IMPL(internal, PagedQSAIndexerGPU);++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/ops/qsa_indexer.cpp b/src/plugins/intel_gpu/src/plugin/ops/qsa_indexer.cppnew file mode 100644index 00000000000..5764008302a--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/qsa_indexer.cpp@@ -0,0 +1,57 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/qsa_indexer.hpp"++#include "intel_gpu/plugin/common_utils.hpp"+#include "intel_gpu/plugin/program_builder.hpp"+#include "intel_gpu/primitives/qsa_indexer.hpp"++namespace ov::op::internal {+using QSAIndexer = ov::intel_gpu::op::QSAIndexer;+} // namespace ov::op::internal++namespace ov::intel_gpu {++static void CreateQSAIndexerOp(ProgramBuilder& p, const std::shared_ptr<ov::intel_gpu::op::QSAIndexer>& op) {+ validate_inputs_count(op, {ov::intel_gpu::op::QSAIndexer::InputIdx::COUNT});+ const auto inputs = p.GetInputInfo(op);+ const auto layer_name = layer_type_name_ID(op);++ std::string reason;+ OPENVINO_ASSERT(ov::intel_gpu::op::QSAIndexer::validate_config(op->get_config(), reason), "[GPU] Cannot lower QSAIndexer op '", layer_name, "': ", reason);++ using In = ov::intel_gpu::op::QSAIndexer::InputIdx;+ OPENVINO_ASSERT(op->get_config().num_selection_heads == 1,+ "[GPU] QSAIndexer '",+ layer_name,+ "': only num_selection_heads == 1 is supported, got ",+ op->get_config().num_selection_heads);+ OPENVINO_ASSERT(op->get_index_key_heads() == 1, "[GPU] QSAIndexer '", layer_name, "': only H_ik == 1 is supported, got ", op->get_index_key_heads());+ for (size_t idx : {In::INDEX_QUERY,+ In::RAW_INDEX_KEYS,+ In::ROPE_COS,+ In::ROPE_SIN,+ In::Q_NORM_WEIGHT,+ In::K_NORM_WEIGHT,+ In::BLOCK_INDEX_KEYS_CACHE,+ In::PAST_INCOMPLETE_RAW_K,+ In::PAST_INCOMPLETE_ROPE}) {+ OPENVINO_ASSERT(op->get_input_element_type(idx) == ov::element::f16,+ "[GPU] QSAIndexer '",+ layer_name,+ "': input ",+ idx,+ " must be f16, got ",+ op->get_input_element_type(idx));+ }++ cldnn::qsa_indexer prim(layer_name, inputs, op->get_config());+ prim.output_data_types = get_output_data_types(op);+ p.add_primitive(*op, prim);+}++REGISTER_FACTORY_IMPL(internal, QSAIndexer);++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/ops/sparse_pa.cpp b/src/plugins/intel_gpu/src/plugin/ops/sparse_pa.cppnew file mode 100644index 00000000000..a991fa59b14--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/sparse_pa.cpp@@ -0,0 +1,73 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/sparse_pa.hpp"++#include "intel_gpu/plugin/common_utils.hpp"+#include "intel_gpu/plugin/program_builder.hpp"+#include "intel_gpu/primitives/sparse_pa.hpp"+#include "openvino/op/constant.hpp"++namespace ov::op::internal {+using SparsePA = ov::intel_gpu::op::SparsePA;+} // namespace ov::op::internal++namespace ov::intel_gpu {++static void CreateSparsePAOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::SparsePA>& op) {+ using In = ov::intel_gpu::op::SparsePA::InputIdx;++ validate_inputs_count(op, {In::COUNT});+ const auto layer_name = layer_type_name_ID(op);++ std::string reason;+ OPENVINO_ASSERT(ov::intel_gpu::op::SparsePA::validate_config(op->get_config(), reason), "[GPU] Cannot lower SparsePA op '", layer_name, "': ", reason);+ OPENVINO_ASSERT(op->get_config().num_selection_heads == 1,+ "[GPU] SparsePA '",+ layer_name,+ "': only num_selection_heads == 1 is supported, got ",+ op->get_config().num_selection_heads);+ for (size_t idx : {In::QUERY, In::KEY, In::VALUE}) {+ OPENVINO_ASSERT(op->get_input_element_type(idx) == ov::element::f16,+ "[GPU] SparsePA '",+ layer_name,+ "': input ",+ idx,+ " must be f16, got ",+ op->get_input_element_type(idx));+ }+ for (auto [idx, quant] : {std::pair{In::KEY_CACHE, op->get_config().key_quant}, std::pair{In::VALUE_CACHE, op->get_config().value_quant}}) {+ const auto expected = quant.enabled() ? ov::element::u8 : ov::element::f16;+ OPENVINO_ASSERT(op->get_input_element_type(idx) == expected,+ "[GPU] SparsePA '",+ layer_name,+ "': input ",+ idx,+ " must be ",+ expected,+ ", got ",+ op->get_input_element_type(idx));+ }++ // Attention sinks are not supported by the GPU kernels (explicit rejection, not a silent fallback).+ OPENVINO_ASSERT(!op->has_sinks(), "[GPU] SparsePA '", layer_name, "': the sinks input is not supported by the GPU implementation");++ // The scale input is folded into the primitive, so it must be a Constant.+ auto scale_const = ov::as_type_ptr<ov::op::v0::Constant>(op->get_input_node_shared_ptr(In::SCALE));+ OPENVINO_ASSERT(scale_const != nullptr, "[GPU] SparsePA '", layer_name, "': scale input must be a Constant in this lowering pass");+ const float scale = scale_const->cast_vector<float>().at(0);++ // Only QUERY..SELECTED_BLOCK_COUNT are consumed by the kernels; scale and sinks are not primitive inputs.+ const auto full_inputs = p.GetInputInfo(op);+ const std::vector<cldnn::input_info> inputs(full_inputs.begin(), full_inputs.begin() + cldnn::sparse_pa::InputIdx::COUNT);++ cldnn::sparse_pa prim(layer_name, inputs, op->get_config(), scale);+ prim.num_outputs = op->get_output_size();+ prim.output_data_types = get_output_data_types(op);+ p.add_primitive(*op, prim);+}++REGISTER_FACTORY_IMPL(internal, SparsePA);++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/ops/sparse_sdpa.cpp b/src/plugins/intel_gpu/src/plugin/ops/sparse_sdpa.cppnew file mode 100644index 00000000000..cfef9daefff--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/sparse_sdpa.cpp@@ -0,0 +1,67 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/sparse_sdpa.hpp"++#include "intel_gpu/plugin/common_utils.hpp"+#include "intel_gpu/plugin/program_builder.hpp"+#include "intel_gpu/primitives/sparse_sdpa.hpp"+#include "openvino/op/constant.hpp"++// Only the selected_block_indices/selected_block_count plan form is lowered. A SCALE input must be a Constant so+// its value can be folded into the primitive's scale field, and attention sinks are not+// supported by the GPU kernels (explicit rejection, not a silent fallback).++namespace ov::op::internal {+using SparseSDPA = ov::intel_gpu::op::SparseSDPA;+} // namespace ov::op::internal++namespace ov::intel_gpu {++static void CreateSparseSDPAOp(ProgramBuilder& p, const std::shared_ptr<ov::intel_gpu::op::SparseSDPA>& op) {+ using In = ov::intel_gpu::op::SparseSDPA::InputIdx;+ const auto layer_name = layer_type_name_ID(op);++ OPENVINO_ASSERT(!op->has_sinks(), "[GPU] SparseSDPA '", layer_name, "': the sinks input is not supported by the GPU implementation");++ std::string reason;+ OPENVINO_ASSERT(ov::intel_gpu::op::SparseSDPA::validate_config(op->get_config(), reason), "[GPU] Cannot lower SparseSDPA op '", layer_name, "': ", reason);+ OPENVINO_ASSERT(op->get_config().num_selection_heads == 1,+ "[GPU] SparseSDPA '",+ layer_name,+ "': only num_selection_heads == 1 is supported, got ",+ op->get_config().num_selection_heads);+ const bool compressed = op->get_config().kv_compressed();+ for (size_t idx : {In::QUERY, In::KEY, In::VALUE}) {+ const auto expected = compressed && idx != In::QUERY ? ov::element::i8 : ov::element::f16;+ OPENVINO_ASSERT(op->get_input_element_type(idx) == expected,+ "[GPU] SparseSDPA '",+ layer_name,+ "': input ",+ idx,+ " must be ",+ expected,+ ", got ",+ op->get_input_element_type(idx));+ }++ float resolved_scale = 1.0f / std::sqrt(static_cast<float>(op->get_config().k_head_size));+ if (op->has_scale_input()) {+ auto scale_const = ov::as_type_ptr<ov::op::v0::Constant>(op->get_input_node_shared_ptr(op->get_config().scale_input_idx()));+ OPENVINO_ASSERT(scale_const != nullptr, "[GPU] SparseSDPA '", layer_name, "': scale input must be a Constant in this lowering pass");+ resolved_scale = scale_const->cast_vector<float>().at(0);+ }++ auto full_inputs = p.GetInputInfo(op);+ // The primitive takes the core and parameter inputs; the scale is folded into its scale field.+ std::vector<cldnn::input_info> inputs(full_inputs.begin(), full_inputs.begin() + op->get_config().scale_input_idx());++ cldnn::sparse_sdpa prim(layer_name, inputs, op->get_config(), resolved_scale);+ prim.output_data_types = get_output_data_types(op);+ p.add_primitive(*op, prim);+}++REGISTER_FACTORY_IMPL(internal, SparseSDPA);++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/paged_qsa_indexer.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/paged_qsa_indexer.cppnew file mode 100644index 00000000000..69f4d075003--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/paged_qsa_indexer.cpp@@ -0,0 +1,14 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/paged_qsa_indexer.hpp"++namespace ov::intel_gpu::op {++std::shared_ptr<Node> PagedQSAIndexer::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<PagedQSAIndexer>(new_args, get_config());+}++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_indexer.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_indexer.cppnew file mode 100644index 00000000000..bf12dc2ba1d--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_indexer.cpp@@ -0,0 +1,153 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/qsa_indexer.hpp"++#include <cmath>+#include <initializer_list>+#include <string>+#include <utility>++#include "qsa_op_utils.hpp"++namespace ov::intel_gpu::op {++using namespace qsa_util;++QSAIndexer::QSAIndexer(const ov::OutputVector& args, const Config& config) : Op(args), m_config(config) {+ constructor_validate_and_infer_types();+}++bool QSAIndexer::validate_config(const Config& c, std::string& reason) {+ auto fail = [&reason](const char* msg) {+ reason = msg;+ return false;+ };+ if (c.key_block_size == 0) {+ return fail("key_block_size must be positive");+ }+ if (c.block_topk == 0) {+ return fail("block_topk must be positive");+ }+ if (c.num_selection_heads == 0) {+ return fail("num_selection_heads must be positive");+ }+ if (c.indexer_head_dim == 0) {+ return fail("indexer_head_dim must be positive");+ }+ if (c.indexer_rotary_dim % 2 != 0 || c.indexer_rotary_dim > c.indexer_head_dim) {+ return fail("indexer_rotary_dim must be even and not exceed indexer_head_dim");+ }+ if (!std::isfinite(c.scale) || c.scale < 0.0f) {+ return fail("scale must be positive (0 selects the default 1 / sqrt(indexer_head_dim))");+ }+ return true;+}++float QSAIndexer::effective_scale(const Config& c) {+ return c.scale > 0.0f ? c.scale : 1.0f / std::sqrt(static_cast<float>(c.indexer_head_dim));+}++size_t QSAIndexer::get_index_query_heads() const {+ const auto& ps = get_input_partial_shape(InputIdx::INDEX_QUERY);+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() == 4 && ps[2].is_static(), "QSAIndexer: index_query shape is not static");+ return static_cast<size_t>(ps[2].get_length());+}++size_t QSAIndexer::get_index_key_heads() const {+ const auto& ps = get_input_partial_shape(InputIdx::RAW_INDEX_KEYS);+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() == 4 && ps[2].is_static(), "QSAIndexer: raw_index_keys shape is not static");+ return static_cast<size_t>(ps[2].get_length());+}++bool QSAIndexer::visit_attributes(ov::AttributeVisitor& visitor) {+ visitor.on_attribute("key_block_size", m_config.key_block_size);+ visitor.on_attribute("block_topk", m_config.block_topk);+ visitor.on_attribute("num_selection_heads", m_config.num_selection_heads);+ visitor.on_attribute("indexer_rotary_dim", m_config.indexer_rotary_dim);+ visitor.on_attribute("indexer_head_dim", m_config.indexer_head_dim);+ visitor.on_attribute("epsilon", m_config.epsilon);+ visitor.on_attribute("scale", m_config.scale);+ return true;+}++void QSAIndexer::validate_and_infer_types() {+ NODE_VALIDATION_CHECK(this, get_input_size() == InputIdx::COUNT, "QSAIndexer expects ", InputIdx::COUNT, " inputs, got ", get_input_size());++ std::string reason;+ NODE_VALIDATION_CHECK(this, validate_config(m_config, reason), "QSAIndexer configuration is invalid: ", reason);++ const auto& index_query_ps = get_input_partial_shape(InputIdx::INDEX_QUERY);+ const auto& raw_index_keys_ps = get_input_partial_shape(InputIdx::RAW_INDEX_KEYS);+ NODE_VALIDATION_CHECK(this,+ index_query_ps.rank().is_dynamic() || index_query_ps.size() == 4,+ "QSAIndexer expects a rank-4 [B, L, H_iq, D_idx] index_query input, got ",+ index_query_ps);+ NODE_VALIDATION_CHECK(this,+ raw_index_keys_ps.rank().is_dynamic() || raw_index_keys_ps.size() == 4,+ "QSAIndexer expects a rank-4 [B, L, H_ik, D_idx] raw_index_keys input, got ",+ raw_index_keys_ps);+ check_float_inputs(this,+ {InputIdx::INDEX_QUERY,+ InputIdx::RAW_INDEX_KEYS,+ InputIdx::ROPE_COS,+ InputIdx::ROPE_SIN,+ InputIdx::Q_NORM_WEIGHT,+ InputIdx::K_NORM_WEIGHT,+ InputIdx::BLOCK_INDEX_KEYS_CACHE,+ InputIdx::PAST_INCOMPLETE_RAW_K,+ InputIdx::PAST_INCOMPLETE_ROPE});++ const auto r = static_cast<int64_t>(m_config.key_block_size);+ const ov::Dimension di(static_cast<int64_t>(m_config.indexer_head_dim));+ const ov::Dimension rot(static_cast<int64_t>(m_config.indexer_rotary_dim));+ const ov::Dimension rope_row(static_cast<int64_t>(2 * m_config.indexer_rotary_dim));+ const auto batch = dim_at(index_query_ps, 0);+ const auto length = dim_at(index_query_ps, 1);+ const auto h_ik = dim_at(raw_index_keys_ps, 2);++ check_shape(this, InputIdx::INDEX_QUERY, "index_query", ov::PartialShape{batch, length, -1, di});+ check_shape(this, InputIdx::RAW_INDEX_KEYS, "raw_index_keys", ov::PartialShape{batch, length, h_ik, di});+ check_shape(this, InputIdx::ROPE_COS, "rope_cos", ov::PartialShape{batch, length, rot});+ check_shape(this, InputIdx::ROPE_SIN, "rope_sin", ov::PartialShape{batch, length, rot});+ check_shape(this, InputIdx::Q_NORM_WEIGHT, "q_norm_weight", ov::PartialShape{di});+ check_shape(this, InputIdx::K_NORM_WEIGHT, "k_norm_weight", ov::PartialShape{di});+ check_shape(this, InputIdx::BLOCK_INDEX_KEYS_CACHE, "block_index_keys_cache", ov::PartialShape{batch, h_ik, -1, di});+ check_shape(this, InputIdx::PAST_INCOMPLETE_RAW_K, "past_incomplete_raw_k", ov::PartialShape{batch, h_ik, r - 1, di});+ check_shape(this, InputIdx::PAST_INCOMPLETE_ROPE, "past_incomplete_rope", ov::PartialShape{batch, rope_row});++ check_i32_input(this, InputIdx::KEY_LENGTH, "key_length", 1);+ check_shape(this, InputIdx::KEY_LENGTH, "key_length", ov::PartialShape{batch});++ if (index_query_ps.rank().is_static() && index_query_ps.size() == 4 && index_query_ps[2].is_static() && h_ik.is_static()) {+ const auto h_iq = static_cast<size_t>(index_query_ps[2].get_length());+ const auto h_ik_value = static_cast<size_t>(h_ik.get_length());+ NODE_VALIDATION_CHECK(this, h_ik_value != 0 && h_iq % h_ik_value == 0, "QSAIndexer: H_iq must be a positive multiple of H_ik.");+ NODE_VALIDATION_CHECK(this,+ m_config.num_selection_heads == 1 || m_config.num_selection_heads == h_ik_value,+ "QSAIndexer: num_selection_heads must be 1 or H_ik.");+ }++ const ov::PartialShape selected_block_indices_ps{batch,+ ov::Dimension(static_cast<int64_t>(m_config.num_selection_heads)),+ length,+ ov::Dimension(static_cast<int64_t>(m_config.block_topk))};+ const ov::PartialShape selected_block_count_ps{batch, ov::Dimension(static_cast<int64_t>(m_config.num_selection_heads)), length};++ set_output_size(OutputIdx::COUNT);+ set_output_type(OutputIdx::SELECTED_BLOCK_INDICES, element::i32, selected_block_indices_ps);+ set_output_type(OutputIdx::SELECTED_BLOCK_COUNT, element::i32, selected_block_count_ps);+ for (auto [out, in] : {std::pair{OutputIdx::BLOCK_INDEX_KEYS_CACHE, InputIdx::BLOCK_INDEX_KEYS_CACHE},+ std::pair{OutputIdx::PAST_INCOMPLETE_RAW_K, InputIdx::PAST_INCOMPLETE_RAW_K},+ std::pair{OutputIdx::PAST_INCOMPLETE_ROPE, InputIdx::PAST_INCOMPLETE_ROPE}}) {+ set_output_type(out, get_input_element_type(in), get_input_partial_shape(in));+ }+}++std::shared_ptr<Node> QSAIndexer::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<QSAIndexer>(new_args, m_config);+}++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_op_utils.hpp b/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_op_utils.hppnew file mode 100644index 00000000000..ca5dd38b170--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_op_utils.hpp@@ -0,0 +1,89 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Validation helpers shared by the QSA indexer / sparse-attention ops (GPU plugin).++#pragma once++#include <cstddef>+#include <initializer_list>+#include <string>++#include "openvino/core/attribute_visitor.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/partial_shape.hpp"+#include "openvino/core/validation_util.hpp"++namespace ov::intel_gpu::op::qsa_util {++// The kernels read every integer input as int32_t.+inline void check_i32_input(const ov::Node* node, size_t idx, const char* name, int64_t rank) {+ const auto& et = node->get_input_element_type(idx);+ const auto& ps = node->get_input_partial_shape(idx);+ NODE_VALIDATION_CHECK(node, et.is_dynamic() || et == element::i32, node->get_type_name(), " expects an i32 ", name, " input, got ", et);+ NODE_VALIDATION_CHECK(node, ps.rank().compatible(rank), node->get_type_name(), " expects a rank-", rank, " ", name, " input, got ", ps);+}++inline void check_shape(const ov::Node* node, size_t idx, const char* name, const ov::PartialShape& expected) {+ const auto& ps = node->get_input_partial_shape(idx);+ NODE_VALIDATION_CHECK(node, ps.compatible(expected), node->get_type_name(), " expects ", name, " shaped ", expected, ", got ", ps);+}++inline void check_float_inputs(const ov::Node* node, std::initializer_list<size_t> indices) {+ element::Type et = element::dynamic;+ for (auto idx : indices) {+ const auto& in_et = node->get_input_element_type(idx);+ NODE_VALIDATION_CHECK(node,+ element::Type::merge(et, et, in_et),+ node->get_type_name(),+ " expects all floating-point inputs to share one element type; input ",+ idx,+ " is ",+ in_et);+ }+ NODE_VALIDATION_CHECK(node, et.is_dynamic() || et.is_real(), node->get_type_name(), " expects floating-point inputs, got ", et);+}++inline ov::Dimension dim_at(const ov::PartialShape& ps, size_t axis) {+ return ps.rank().is_static() && ps.size() > axis ? ps[axis] : ov::Dimension::dynamic();+}++/// Config rules for SparseSDPA::Config.+template <class Config>+bool validate_sparse_attention_config(const Config& c, std::string& reason) {+ auto fail = [&reason](const char* msg) {+ reason = msg;+ return false;+ };+ if (c.num_heads == 0 || c.num_kv_heads == 0 || c.num_heads % c.num_kv_heads != 0) {+ return fail("num_heads must be a positive multiple of num_kv_heads");+ }+ if (c.num_selection_heads != 1 && c.num_selection_heads != c.num_kv_heads && c.num_selection_heads != c.num_heads) {+ return fail("num_selection_heads must be 1, num_kv_heads, or num_heads");+ }+ if (c.k_head_size == 0 || c.k_head_size % 16 != 0 || c.v_head_size == 0 || c.v_head_size % 16 != 0) {+ return fail("k_head_size / v_head_size must be positive multiples of 16");+ }+ if (c.key_block_size == 0) {+ return fail("key_block_size must be positive");+ }+ if (c.query_block_size != 1) {+ return fail("query_block_size != 1 is not implemented in this pass");+ }+ return true;+}++template <class Config>+void visit_sparse_attention_config(ov::AttributeVisitor& visitor, Config& c) {+ visitor.on_attribute("num_heads", c.num_heads);+ visitor.on_attribute("num_kv_heads", c.num_kv_heads);+ visitor.on_attribute("num_selection_heads", c.num_selection_heads);+ visitor.on_attribute("k_head_size", c.k_head_size);+ visitor.on_attribute("v_head_size", c.v_head_size);+ visitor.on_attribute("key_block_size", c.key_block_size);+ visitor.on_attribute("query_block_size", c.query_block_size);+ visitor.on_attribute("causal", c.causal);+}++} // namespace ov::intel_gpu::op::qsa_utildiff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_pa.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_pa.cppnew file mode 100644index 00000000000..2298af3440d--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_pa.cpp@@ -0,0 +1,127 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/sparse_pa.hpp"++#include <string>+#include <utility>++#include "qsa_op_utils.hpp"++namespace ov::intel_gpu::op {++using namespace qsa_util;++namespace {++void visit_kv_quant(ov::AttributeVisitor& visitor, const std::string& prefix, KVQuant& quant) {+ auto mode = static_cast<int32_t>(quant.mode);+ auto bits = static_cast<int32_t>(quant.bits);+ auto group_size = static_cast<int32_t>(quant.group_size);+ visitor.on_attribute(prefix + "quant_mode", mode);+ visitor.on_attribute(prefix + "quant_bits", bits);+ visitor.on_attribute(prefix + "quant_symmetric", quant.symmetric);+ visitor.on_attribute(prefix + "quant_group_size", group_size);+ quant.mode = static_cast<KVQuant::Mode>(mode);+ quant.bits = static_cast<uint8_t>(bits);+ quant.group_size = static_cast<uint16_t>(group_size);+}++} // namespace++SparsePA::SparsePA(const ov::OutputVector& args, const Config& config) : Base(args, static_cast<int64_t>(config.key_block_size)), m_config(config) {+ constructor_validate_and_infer_types();+}++bool SparsePA::validate_config(const Config& c, std::string& reason) {+ if (!validate_sparse_attention_config(c, reason)) {+ return false;+ }+ if (c.page_size != 0 && c.page_size % c.key_block_size != 0) {+ reason = "key_block_size must divide the page size";+ return false;+ }+ if (c.kv_quantized()) {+ if (!validate_kv_quant(c.key_quant, true, c.page_size, c.k_head_size, c.key_block_size, reason) ||+ !validate_kv_quant(c.value_quant, false, c.page_size, c.v_head_size, c.key_block_size, reason)) {+ return false;+ }+ }+ return true;+}++bool SparsePA::has_sinks() const {+ const auto& ps = get_input_partial_shape(InputIdx::SINKS);+ return !ps.rank().is_static() || ps.size() != 1 || !ps[0].is_static() || ps[0].get_length() != 0;+}++bool SparsePA::visit_attributes(ov::AttributeVisitor& visitor) {+ Base::visit_attributes(visitor);+ visitor.on_attribute("num_heads", m_config.num_heads);+ visitor.on_attribute("num_kv_heads", m_config.num_kv_heads);+ visitor.on_attribute("num_selection_heads", m_config.num_selection_heads);+ visitor.on_attribute("k_head_size", m_config.k_head_size);+ visitor.on_attribute("v_head_size", m_config.v_head_size);+ visitor.on_attribute("query_block_size", m_config.query_block_size);+ visitor.on_attribute("causal", m_config.causal);+ visitor.on_attribute("page_size", m_config.page_size);+ visit_kv_quant(visitor, "key_", m_config.key_quant);+ visit_kv_quant(visitor, "value_", m_config.value_quant);+ return true;+}++void SparsePA::validate_and_infer_types() {+ Base::validate_and_infer_types();+ if (m_config.num_heads == 0) {+ return; // default-constructed; the config is not set yet+ }+ std::string reason;+ NODE_VALIDATION_CHECK(this, validate_config(m_config, reason), "SparsePA configuration is invalid: ", reason);+ NODE_VALIDATION_CHECK(this,+ m_config.key_block_size == static_cast<size_t>(get_key_block_size()),+ "SparsePA key_block_size must match the PagedSparseAttention attribute");++ // The core op leaves the head geometry to the backend: tie the projections and caches to the config.+ auto width_matches = [this](size_t input, size_t expected) {+ const auto& ps = get_input_partial_shape(input);+ return ps.rank().is_dynamic() || ps.size() != 2 || ps[1].compatible(static_cast<int64_t>(expected));+ };+ NODE_VALIDATION_CHECK(this,+ width_matches(InputIdx::QUERY, m_config.num_heads * m_config.k_head_size) &&+ width_matches(InputIdx::KEY, m_config.num_kv_heads * m_config.k_head_size) &&+ width_matches(InputIdx::VALUE, m_config.num_kv_heads * m_config.v_head_size),+ "SparsePA query/key/value widths do not match num_heads, num_kv_heads and the head sizes");+ const auto& key_cache = get_input_partial_shape(InputIdx::KEY_CACHE);+ const auto& value_cache = get_input_partial_shape(InputIdx::VALUE_CACHE);+ // Quantized caches are u8 pages [blocks, Hkv, page_size + parameter rows, bytes per row].+ auto cache_matches = [this](const ov::PartialShape& ps, const KVQuant& quant, size_t head_size) {+ if (ps.rank().is_dynamic()) {+ return true;+ }+ if (ps.size() != 4 || !ps[1].compatible(static_cast<int64_t>(m_config.num_kv_heads))) {+ return false;+ }+ if (!quant.enabled()) {+ return ps[3].compatible(static_cast<int64_t>(head_size)) && (m_config.page_size == 0 || ps[2].compatible(static_cast<int64_t>(m_config.page_size)));+ }+ const auto layout = kv_page_layout(quant, m_config.page_size, head_size);+ return ps[2].compatible(static_cast<int64_t>(layout.total_rows)) && ps[3].compatible(static_cast<int64_t>(layout.row_bytes));+ };+ NODE_VALIDATION_CHECK(+ this,+ cache_matches(key_cache, m_config.key_quant, m_config.k_head_size) && cache_matches(value_cache, m_config.value_quant, m_config.v_head_size),+ "SparsePA caches must be [blocks, num_kv_heads, page_size, head_size] (quantized: [blocks, num_kv_heads, page_size + parameter rows, "+ "bytes per row])");+ for (auto [idx, quant] : {std::pair{InputIdx::KEY_CACHE, &m_config.key_quant}, std::pair{InputIdx::VALUE_CACHE, &m_config.value_quant}}) {+ const auto& type = get_input_element_type(idx);+ NODE_VALIDATION_CHECK(this, !quant->enabled() || type.is_dynamic() || type == ov::element::u8, "A quantized SparsePA cache must be u8, got ", type);+ }+}++std::shared_ptr<Node> SparsePA::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<SparsePA>(new_args, m_config);+}++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_sdpa.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_sdpa.cppnew file mode 100644index 00000000000..4907f337465--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_sdpa.cpp@@ -0,0 +1,175 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/sparse_sdpa.hpp"++#include <string>+#include <utility>++#include "qsa_op_utils.hpp"++namespace ov::intel_gpu::op {++using namespace qsa_util;++SparseSDPA::SparseSDPA(const ov::OutputVector& args, const Config& config, const ov::element::Type output_type)+ : Op(args),+ m_config(config),+ m_output_type(output_type) {+ constructor_validate_and_infer_types();+}++bool SparseSDPA::validate_config(const Config& c, std::string& reason) {+ if (!validate_sparse_attention_config(c, reason)) {+ return false;+ }+ if (!c.kv_compressed()) {+ return true;+ }+ if (!c.key_quant.enabled() || !c.value_quant.enabled()) {+ reason = "the key and value histories are quantized together";+ return false;+ }+ if (c.key_quant.bits != c.value_quant.bits || c.key_quant.symmetric != c.value_quant.symmetric) {+ reason = "the key and value histories must share bits and symmetry";+ return false;+ }+ return validate_dense_kv_quant(c.key_quant, c.k_head_size, reason) && validate_dense_kv_quant(c.value_quant, c.v_head_size, reason);+}++namespace {++void visit_kv_quant(ov::AttributeVisitor& visitor, const std::string& prefix, KVQuant& quant) {+ auto mode = static_cast<int32_t>(quant.mode);+ auto bits = static_cast<int32_t>(quant.bits);+ auto group_size = static_cast<int32_t>(quant.group_size);+ visitor.on_attribute(prefix + "quant_mode", mode);+ visitor.on_attribute(prefix + "quant_bits", bits);+ visitor.on_attribute(prefix + "quant_symmetric", quant.symmetric);+ visitor.on_attribute(prefix + "quant_group_size", group_size);+ quant.mode = static_cast<KVQuant::Mode>(mode);+ quant.bits = static_cast<uint8_t>(bits);+ quant.group_size = static_cast<uint16_t>(group_size);+}++} // namespace++bool SparseSDPA::visit_attributes(ov::AttributeVisitor& visitor) {+ visit_sparse_attention_config(visitor, m_config);+ visit_kv_quant(visitor, "key_", m_config.key_quant);+ visit_kv_quant(visitor, "value_", m_config.value_quant);+ visitor.on_attribute("output_type", m_output_type);+ return true;+}++void SparseSDPA::validate_and_infer_types() {+ // The optional SCALE (and SINKS, unless compressed) follow the core and parameter inputs.+ const size_t scale_idx = m_config.scale_input_idx();+ const size_t max_inputs = m_config.kv_compressed() ? scale_idx + 1 : m_config.sinks_input_idx() + 1;+ NODE_VALIDATION_CHECK(this,+ get_input_size() >= scale_idx && get_input_size() <= max_inputs,+ "SparseSDPA expects ",+ scale_idx,+ "..",+ max_inputs,+ " inputs, got ",+ get_input_size());++ std::string reason;+ NODE_VALIDATION_CHECK(this, validate_config(m_config, reason), "SparseSDPA configuration is invalid: ", reason);++ const auto& query_ps = get_input_partial_shape(InputIdx::QUERY);+ NODE_VALIDATION_CHECK(this, query_ps.rank().is_dynamic() || query_ps.size() == 4, "SparseSDPA expects a rank-4 [B, Hq, L, Dh] query input, got ", query_ps);++ // The kernels read the selection plan and key_length as int32_t.+ const std::pair<size_t, int64_t> int_inputs[] = {{InputIdx::SELECTED_BLOCK_INDICES, 4}, {InputIdx::SELECTED_BLOCK_COUNT, 3}, {InputIdx::KEY_LENGTH, 1}};+ for (const auto& [idx, rank] : int_inputs) {+ const auto& et = get_input_element_type(idx);+ const auto& ps = get_input_partial_shape(idx);+ NODE_VALIDATION_CHECK(this, et.is_dynamic() || et == element::i32, "SparseSDPA expects an i32 input ", idx, ", got ", et);+ NODE_VALIDATION_CHECK(this, ps.rank().compatible(rank), "SparseSDPA expects a rank-", rank, " input ", idx, ", got ", ps);+ }+ const auto batch = query_ps.rank().is_static() ? query_ps[0] : ov::Dimension::dynamic();+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::KEY_LENGTH).compatible(ov::PartialShape{batch}),+ "SparseSDPA expects a [B] key_length input, got ",+ get_input_partial_shape(InputIdx::KEY_LENGTH));++ // Q/K/V geometry must agree with the config the kernels are specialized for.+ const auto hkv = static_cast<int64_t>(m_config.num_kv_heads);+ const auto sel = static_cast<int64_t>(m_config.num_selection_heads);+ check_shape(this,+ InputIdx::QUERY,+ "query",+ ov::PartialShape{batch, static_cast<int64_t>(m_config.num_heads), dim_at(query_ps, 2), static_cast<int64_t>(m_config.k_head_size)});+ const auto seq = dim_at(get_input_partial_shape(InputIdx::KEY), 2);+ check_shape(this, InputIdx::KEY, "key", ov::PartialShape{batch, hkv, seq, static_cast<int64_t>(m_config.k_head_size)});+ check_shape(this, InputIdx::VALUE, "value", ov::PartialShape{batch, hkv, seq, static_cast<int64_t>(m_config.v_head_size)});+ const auto q_len = dim_at(query_ps, 2);+ const auto k_max = dim_at(get_input_partial_shape(InputIdx::SELECTED_BLOCK_INDICES), 3);+ check_shape(this, InputIdx::SELECTED_BLOCK_INDICES, "selected_block_indices", ov::PartialShape{batch, sel, q_len, k_max});+ check_shape(this, InputIdx::SELECTED_BLOCK_COUNT, "selected_block_count", ov::PartialShape{batch, sel, q_len});+ check_float_inputs(this,+ m_config.kv_compressed() ? std::initializer_list<size_t>{InputIdx::QUERY}+ : std::initializer_list<size_t>{InputIdx::QUERY, InputIdx::KEY, InputIdx::VALUE});+ if (m_config.kv_compressed()) {+ for (size_t idx : {InputIdx::KEY, InputIdx::VALUE}) {+ const auto& et = get_input_element_type(idx);+ NODE_VALIDATION_CHECK(this, et.is_dynamic() || et == element::i8, "A compressed SparseSDPA expects i8 key/value inputs, got ", et);+ }+ // Per-token parameters [B, Hkv, S, 1], see sparse_kv_quant.hpp.+ auto check_params = [&](const KVQuant& quant, size_t scale_idx, size_t zp_idx) {+ const ov::PartialShape shape{batch, hkv, seq, 1};+ const auto& scale_et = get_input_element_type(scale_idx);+ NODE_VALIDATION_CHECK(this, scale_et.is_dynamic() || scale_et == element::f16, "A compressed SparseSDPA expects f16 scale inputs, got ", scale_et);+ check_shape(this, scale_idx, "scale", shape);+ if (quant.symmetric) {+ return;+ }+ const auto expected_zp = dense_zp_is_f16(quant) ? element::f16 : element::i8;+ const auto& zp_et = get_input_element_type(zp_idx);+ NODE_VALIDATION_CHECK(this,+ zp_et.is_dynamic() || zp_et == expected_zp,+ "A compressed SparseSDPA expects ",+ expected_zp,+ " zero-point inputs, got ",+ zp_et);+ check_shape(this, zp_idx, "zero point", shape);+ };+ check_params(m_config.key_quant, InputIdx::KEY_SCALE, InputIdx::KEY_ZP);+ check_params(m_config.value_quant, InputIdx::VALUE_SCALE, InputIdx::VALUE_ZP);+ }+ if (has_scale_input()) {+ const auto& scale_ps = get_input_partial_shape(m_config.scale_input_idx());+ NODE_VALIDATION_CHECK(this,+ scale_ps.is_dynamic() || ov::shape_size(scale_ps.to_shape()) == 1,+ "SparseSDPA expects a scalar or 1-element scale input, got ",+ scale_ps);+ }+ if (has_sinks()) {+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(m_config.sinks_input_idx()).compatible(ov::PartialShape{static_cast<int64_t>(m_config.num_heads)}),+ "SparseSDPA expects a [num_heads] sinks input, got ",+ get_input_partial_shape(m_config.sinks_input_idx()));+ }++ auto out_ps = ov::PartialShape::dynamic(4);+ if (query_ps.rank().is_static()) {+ out_ps[0] = query_ps[0];+ out_ps[2] = query_ps[2];+ }+ out_ps[1] = ov::Dimension(static_cast<int64_t>(m_config.num_heads));+ out_ps[3] = ov::Dimension(static_cast<int64_t>(m_config.v_head_size));++ const auto out_et = m_output_type == ov::element::dynamic ? get_input_element_type(InputIdx::QUERY) : m_output_type;+ set_output_size(1);+ set_output_type(0, out_et, out_ps);+}++std::shared_ptr<Node> SparseSDPA::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<SparseSDPA>(new_args, m_config, m_output_type);+}++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmakeindex 337e15508b4..518e032a426 100644--- a/src/plugins/intel_gpu/tests/unit/sources.cmake+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake@@ -249,6 +249,8 @@ set(GPU_UNIT_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/test_cases/propagate_constants_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/proposal_cpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/proposal_test_data.cpp+ ${CMAKE_CURRENT_LIST_DIR}/test_cases/qsa_ops_gpu_test.cpp+ ${CMAKE_CURRENT_LIST_DIR}/test_cases/sparse_pa_kvq_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/quantize_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/random_uniform_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/range_gpu_test.cpp@@ -506,9 +508,13 @@ set(GPU_UNIT_TESTS_TRANSFORMATIONS_SRCS${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/kv_cache.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/lora_subgraph_fused.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/moe_router_fused.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/paged_qsa_indexer.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/placeholder.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_indexer.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/read_value.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_pa.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/sparse_sdpa.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/stateless_kv.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/swoosh.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/swiglu_with_clamp.cppdiff --git a/src/plugins/intel_gpu/tests/unit/test_cases/qsa_ops_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/qsa_ops_gpu_test.cppnew file mode 100644index 00000000000..c367cc59621--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/qsa_ops_gpu_test.cpp@@ -0,0 +1,2881 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Unit tests for the split PagedQSAIndexer/SparsePA and QSAIndexer/SparseSDPA primitives.+// Topologies are built directly at the cldnn primitive level.+//+// Covered:+// - Paged and dense indexer + attention pairs against a CPU reference, both with toy+// dims and with the Qwen3.8-Flash-Next shape (config.json): H_iq=4, D_idx=128,+// H_ik=1, r=4, budget 2048 tokens (block_topk=512), rotary 64, Hq=24, Hkv=2, Dh=256,+// page 16. The GPU's top-k selection is validated against the reference scores with+// an fp16 tolerance, and the attention output is then compared using that selection,+// so near-tied top-k boundaries cannot make the test flaky.+// - Non-sequential (mRoPE-like) positions, which exercise index_block_rope_cache.+// - Dedicated precision/numerical-stability stress tests: large-magnitude activations,+// a single dominant-outlier channel (stresses RMSNorm's sum-of-squares reduction),+// and long-context accumulation (many blocks/softmax terms). The CPU reference+// quantizes every input through the SAME f16 round-trip the GPU sees (`make_f16`),+// so the measured error reflects kernel compute precision, not input quantization+// noise; every comparison asserts finiteness and prints a `QSA_PRECISION` line+// (max/mean absolute and relative error) for inspection.+// - Host-level op validation and plugin-level rejection of unsupported configs.+// - DISABLED_ performance tests that print per-op timings, run with:+// ov_gpu_unit_tests --gtest_also_run_disabled_tests --gtest_filter='*qsa_ops_perf*'++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstddef>+#include <cstdlib>+#include <fstream>+#include <intel_gpu/primitives/data.hpp>+#include <intel_gpu/primitives/input_layout.hpp>+#include <intel_gpu/primitives/paged_qsa_indexer.hpp>+#include <intel_gpu/primitives/qsa_indexer.hpp>+#include <intel_gpu/primitives/sparse_pa.hpp>+#include <intel_gpu/primitives/sparse_sdpa.hpp>+#include <iomanip>+#include <iostream>+#include <limits>+#include <map>+#include <memory>+#include <numeric>+#include <openvino/op/assign.hpp>+#include <openvino/op/concat.hpp>+#include <openvino/op/constant.hpp>+#include <openvino/op/paged_sparse_attention.hpp>+#include <openvino/op/parameter.hpp>+#include <openvino/op/read_value.hpp>+#include <openvino/op/result.hpp>+#include <openvino/op/util/variable.hpp>+#include <set>+#include <sstream>+#include <string>+#include <tuple>+#include <vector>++#include "openvino/runtime/core.hpp"+#include "primitive_inst.h"+#include "random_generator.hpp"+#include "test_utils.h"++using namespace cldnn;+using namespace ::tests;++namespace {++using PagedIn = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;+using DenseIdxIn = ov::intel_gpu::op::QSAIndexer::InputIdx;+using SparsePAIn = cldnn::sparse_pa::InputIdx;+using SparseSDPAIn = ov::intel_gpu::op::SparseSDPA::InputIdx;++/// The QSA ops run on the OpenCL implementation, which needs the Intel subgroup extensions.+bool qsa_ops_available() {+ auto& engine = get_test_engine();+ const auto& info = engine.get_device_info();+ return info.supports_intel_subgroups && info.supports_intel_subgroups_short;+}++int64_t I(size_t v) {+ return static_cast<int64_t>(v);+}++struct split_dims {+ size_t Hiq = 2; // index-query heads (H_ik == 1 fixed in v1)+ size_t Di = 16; // indexer head dim+ size_t rotary = 8;+ size_t r = 4; // key_block_size+ size_t block_topk = 2;+ size_t page_size = 16;+ size_t max_positions = 64;+ float eps = 1e-6f;++ size_t Hq = 2;+ size_t Hkv = 1;+ size_t Dh = 16;+ size_t Dv = 16;+};++/// Qwen3.8-Flash-Next (config.json text_config). The indexer reuses the attention RoPE, so+/// rotary = head_dim (256) * partial_rotary_factor (0.25); block_topk = indexer_budget / r.+split_dims qwen38_dims() {+ split_dims d;+ d.Hiq = 4;+ d.Di = 128;+ d.rotary = 64;+ d.r = 4;+ d.block_topk = 2048 / 4;+ d.page_size = 16;+ d.eps = 1e-6f;+ d.Hq = 24;+ d.Hkv = 2;+ d.Dh = 256;+ d.Dv = 256;+ return d;+}++/// Plain DPAS attention with one worker and 4 heads per tile; GQA-DPAS needs Dh % 128 == 0.+split_dims non_gqa_dpas_dims() {+ auto d = qwen38_dims();+ d.Dh = 64;+ d.Dv = 64;+ return d;+}++/// n_rep = 32 exceeds GQA-DPAS's limit of 16; plain DPAS needs 4 workers and 8 heads per tile.+split_dims wide_group_dims() {+ auto d = qwen38_dims();+ d.Hq = 32;+ d.Hkv = 1;+ return d;+}++/// n_rep = 1: plain DPAS with one head per tile.+split_dims mha_dpas_dims() {+ auto d = non_gqa_dpas_dims();+ d.Hq = 4;+ d.Hkv = 4;+ return d;+}++std::vector<ov::float16> to_f16(const std::vector<float>& src) {+ std::vector<ov::float16> dst(src.size());+ for (size_t i = 0; i < src.size(); i++) {+ dst[i] = ov::float16(src[i]);+ }+ return dst;+}++/// Rounds every element through f16, in place: used so the CPU reference computes from+/// the EXACT same values the GPU reads back (every f16 input below goes through this+/// same round-trip via `make_f16`), isolating kernel compute error from input-quantization+/// noise in the precision comparisons.+void quantize_f16(std::vector<float>& v) {+ for (auto& x : v) {+ x = static_cast<float>(ov::float16(x));+ }+}++/// Device-resident like real model tensors; the default lockable allocation is usm_shared on dGPU.+template <typename T>+memory::ptr make_device(engine& eng, const ov::PartialShape& shape, data_types dt, const std::vector<T>& data) {+ auto mem = eng.allocate_memory(layout{shape, dt, format::bfyx}, allocation_type::usm_device);+ if (!data.empty()) {+ mem->copy_from(get_test_stream(), data.data(), true);+ }+ return mem;+}++memory::ptr make_f16(engine& eng, const ov::PartialShape& shape, const std::vector<float>& data) {+ return make_device(eng, shape, data_types::f16, to_f16(data));+}++memory::ptr make_i32(engine& eng, const ov::PartialShape& shape, const std::vector<int32_t>& data) {+ return make_device(eng, shape, data_types::i32, data);+}++std::vector<int32_t> read_i32(const memory::ptr& mem) {+ mem_lock<int32_t, mem_lock_type::read> lock(mem, get_test_stream());+ return {lock.begin(), lock.end()};+}++std::vector<float> read_f16(const memory::ptr& mem) {+ mem_lock<ov::float16, mem_lock_type::read> lock(mem, get_test_stream());+ std::vector<float> out(lock.size());+ for (size_t i = 0; i < lock.size(); i++) {+ out[i] = static_cast<float>(lock[i]);+ }+ return out;+}++std::vector<float> random_vec(tests::random_generator& rg, size_t count, float scale, float bias = 0.0f) {+ auto v = rg.generate_random_1d<float>(count, -1, 1, 16);+ std::vector<float> out(v.begin(), v.end());+ for (auto& x : out) {+ x = x * scale + bias;+ }+ return out;+}++/// Cheap deterministic filler for the large perf buffers.+std::vector<float> lcg_vec(size_t count, uint32_t seed, float scale = 1.0f) {+ std::vector<float> out(count);+ uint32_t s = seed * 2654435761u + 1u;+ for (auto& x : out) {+ s = s * 1664525u + 1013904223u;+ x = (static_cast<float>(s >> 8) / static_cast<float>(1u << 24) * 2.0f - 1.0f) * scale;+ }+ return out;+}++void rms_norm(std::vector<float>& v, const std::vector<float>& gain, float eps) {+ double sumsq = 0.0;+ for (float x : v) {+ sumsq += static_cast<double>(x) * x;+ }+ const float inv = 1.0f / std::sqrt(static_cast<float>(sumsq / v.size()) + eps);+ for (size_t i = 0; i < v.size(); i++) {+ v[i] = v[i] * inv * gain[i];+ }+}++/// NEOX (rotate-half) partial RoPE using the kernel's interleaved (cos_j, sin_j) table.+void apply_rope(std::vector<float>& v, const std::vector<float>& table, size_t rotary, size_t position) {+ const size_t half = rotary / 2;+ for (size_t j = 0; j < half; j++) {+ const float c = table[position * rotary + 2 * j];+ const float s = table[position * rotary + 2 * j + 1];+ const float x0 = v[j];+ const float x1 = v[j + half];+ v[j] = x0 * c - x1 * s;+ v[j + half] = x1 * c + x0 * s;+ }+}++std::vector<float> make_rotary_table(size_t max_positions, size_t rotary) {+ std::vector<float> table(max_positions * rotary, 0.0f);+ for (size_t p = 0; p < max_positions; p++) {+ for (size_t j = 0; j < rotary / 2; j++) {+ const float freq = 1.0f / std::pow(10000.0f, static_cast<float>(2 * j) / static_cast<float>(rotary));+ const float angle = static_cast<float>(p) * freq;+ table[p * rotary + 2 * j] = std::cos(angle);+ table[p * rotary + 2 * j + 1] = std::sin(angle);+ }+ }+ return table;+}++/// The op's per-token `rope_cos`/`rope_sin` rows ([n, rotary] each, Hugging Face+/// `cat(freqs, freqs)` layout): what the producer gathers from the interleaved `table` at+/// each token's `positions` entry.+std::pair<std::vector<float>, std::vector<float>> rope_rows(const std::vector<float>& table, size_t rotary, const std::vector<int32_t>& positions) {+ const size_t half = rotary / 2;+ std::vector<float> cos(positions.size() * rotary), sin(positions.size() * rotary);+ for (size_t t = 0; t < positions.size(); t++) {+ const size_t row = static_cast<size_t>(positions[t]) * rotary;+ for (size_t j = 0; j < rotary; j++) {+ cos[t * rotary + j] = table[row + 2 * (j % half)];+ sin[t * rotary + j] = table[row + 2 * (j % half) + 1];+ }+ }+ return {cos, sin};+}++/// One RoPE state/cache row: the full-width cos/sin rows of `position` interleaved as+/// (cos_0, sin_0, cos_1, sin_1, ...), 2 * rotary values.+std::vector<float> rope_state_row(const std::vector<float>& table, size_t rotary, int32_t position) {+ const auto [cos, sin] = rope_rows(table, rotary, {position});+ std::vector<float> row(2 * rotary);+ for (size_t j = 0; j < rotary; j++) {+ row[2 * j] = cos[j];+ row[2 * j + 1] = sin[j];+ }+ return row;+}++/// `index_block_rope_cache` content: each block slot holds the interleaved row of its first+/// token, i.e. rope_state_row() of the slot's recorded position.+std::vector<float> rope_cache_rows(const std::vector<float>& table, size_t rotary, const std::vector<int32_t>& slot_positions) {+ std::vector<float> rows;+ rows.reserve(slot_positions.size() * 2 * rotary);+ for (int32_t position : slot_positions) {+ const auto row = rope_state_row(table, rotary, position);+ rows.insert(rows.end(), row.begin(), row.end());+ }+ return rows;+}++/// CPU reference for the split Indexer + Attention pair (H_ik == 1, num_selection_heads == 1,+/// query_block_size == 1). `positions[p]` is the RoPE position of absolute token p: query+/// RoPE uses its own position, a block summary uses the position of the block's first+/// token, whose row is what index_block_rope_cache records.+struct split_reference {+ split_dims d;+ size_t past_len = 0;+ size_t q_len = 0;++ std::vector<int32_t> positions; // [total_len]+ std::vector<float> raw_index_keys_all; // [total_len, Di]+ std::vector<float> index_query_cur; // [q_len, Hiq, Di]+ std::vector<float> key_all; // [total_len, Hkv*Dh]+ std::vector<float> value_all; // [total_len, Hkv*Dv]+ std::vector<float> query_cur; // [q_len, Hq*Dh]+ std::vector<float> q_norm, k_norm;+ std::vector<float> rotary; // [max_positions, rotary], interleaved (cos_j, sin_j)++ mutable std::map<size_t, std::vector<float>> summary_memo;++ size_t total_len() const {+ return past_len + q_len;+ }++ std::vector<float> summary(size_t block_id) const {+ const auto it = summary_memo.find(block_id);+ if (it != summary_memo.end()) {+ return it->second;+ }+ std::vector<float> pooled(d.Di, 0.0f);+ for (size_t s = 0; s < d.r; s++) {+ const size_t p = block_id * d.r + s;+ for (size_t k = 0; k < d.Di; k++) {+ pooled[k] += raw_index_keys_all[p * d.Di + k];+ }+ }+ for (float& x : pooled) {+ // The pooled mean is rounded to T before RMSNorm (qsa-indexer.rst numerics).+ x = static_cast<float>(ov::float16(x / static_cast<float>(d.r)));+ }+ rms_norm(pooled, k_norm, d.eps);+ apply_rope(pooled, rotary, d.rotary, static_cast<size_t>(positions[block_id * d.r]));+ summary_memo.emplace(block_id, pooled);+ return pooled;+ }++ /// (score, block) pairs of every complete block visible to query `t`, best first.+ std::vector<std::pair<float, size_t>> scored_blocks(size_t t) const {+ const size_t abs_pos = past_len + t;+ const size_t n_complete = (abs_pos + 1) / d.r;++ std::vector<std::vector<float>> heads(d.Hiq);+ for (size_t h = 0; h < d.Hiq; h++) {+ heads[h].assign(index_query_cur.begin() + (t * d.Hiq + h) * d.Di, index_query_cur.begin() + (t * d.Hiq + h + 1) * d.Di);+ rms_norm(heads[h], q_norm, d.eps);+ apply_rope(heads[h], rotary, d.rotary, static_cast<size_t>(positions[abs_pos]));+ }++ std::vector<std::pair<float, size_t>> scored;+ scored.reserve(n_complete);+ for (size_t b = 0; b < n_complete; b++) {+ const auto k = summary(b);+ float total = 0.0f;+ for (size_t h = 0; h < d.Hiq; h++) {+ double dot = 0.0;+ for (size_t j = 0; j < d.Di; j++) {+ dot += static_cast<double>(heads[h][j]) * k[j];+ }+ total += std::max(0.0f, static_cast<float>(dot));+ }+ scored.emplace_back(total / std::sqrt(static_cast<float>(d.Di)), b);+ }+ std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) {+ if (a.first != b.first) {+ return a.first > b.first;+ }+ return a.second < b.second;+ });+ return scored;+ }++ /// Selected-block attention plus the causal tail, token-major [q_len, Hq*Dv].+ std::vector<float> attention(const std::vector<std::vector<size_t>>& selections) const {+ std::vector<float> out(q_len * d.Hq * d.Dv, 0.0f);+ const size_t group = d.Hq / d.Hkv;+ for (size_t t = 0; t < q_len; t++) {+ const size_t abs_pos = past_len + t;+ std::vector<size_t> tokens;+ for (size_t b : selections[t]) {+ for (size_t s = 0; s < d.r; s++) {+ tokens.push_back(b * d.r + s);+ }+ }+ for (size_t p = ((abs_pos + 1) / d.r) * d.r; p <= abs_pos; p++) {+ tokens.push_back(p);+ }++ for (size_t h = 0; h < d.Hq; h++) {+ const size_t kv_head = h / group;+ const size_t q_base = t * d.Hq * d.Dh + h * d.Dh;++ std::vector<float> logits;+ logits.reserve(tokens.size());+ for (size_t p : tokens) {+ double dot = 0.0;+ for (size_t j = 0; j < d.Dh; j++) {+ dot += static_cast<double>(query_cur[q_base + j]) * key_all[p * d.Hkv * d.Dh + kv_head * d.Dh + j];+ }+ logits.push_back(static_cast<float>(dot) / std::sqrt(static_cast<float>(d.Dh)));+ }+ const float m = *std::max_element(logits.begin(), logits.end());+ double sum = 0.0;+ for (float& x : logits) {+ x = std::exp(x - m);+ sum += x;+ }+ for (size_t j = 0; j < d.Dv; j++) {+ double acc = 0.0;+ for (size_t i = 0; i < tokens.size(); i++) {+ acc += static_cast<double>(logits[i]) * value_all[tokens[i] * d.Hkv * d.Dv + kv_head * d.Dv + j];+ }+ out[(t * d.Hq + h) * d.Dv + j] = static_cast<float>(acc / sum);+ }+ }+ }+ return out;+ }+};++enum class Positions { Sequential, MRoPELike };++std::vector<int32_t> make_positions(size_t total, Positions kind) {+ std::vector<int32_t> pos(total);+ for (size_t p = 0; p < total; p++) {+ // Non-monotonic with duplicates, as an image span under mRoPE would produce.+ pos[p] = kind == Positions::Sequential ? static_cast<int32_t>(p) : static_cast<int32_t>(p / 2 + (p % 3 == 0 ? 3 : 0));+ }+ return pos;+}++split_reference make_split_reference(tests::random_generator& rg, const split_dims& dims, size_t past_len, size_t q_len, Positions kind, float scale = 1.0f) {+ split_reference ref;+ ref.d = dims;+ ref.past_len = past_len;+ ref.q_len = q_len;+ const size_t total = past_len + q_len;++ ref.positions = make_positions(total, kind);+ ref.d.max_positions = static_cast<size_t>(*std::max_element(ref.positions.begin(), ref.positions.end())) + 1;+ const auto& d = ref.d;++ ref.raw_index_keys_all = random_vec(rg, total * d.Di, scale);+ ref.index_query_cur = random_vec(rg, q_len * d.Hiq * d.Di, scale);+ ref.key_all = random_vec(rg, total * d.Hkv * d.Dh, scale);+ ref.value_all = random_vec(rg, total * d.Hkv * d.Dv, scale);+ ref.query_cur = random_vec(rg, q_len * d.Hq * d.Dh, scale);+ ref.q_norm = random_vec(rg, d.Di, 0.5f, 1.0f);+ ref.k_norm = random_vec(rg, d.Di, 0.5f, 1.0f);+ ref.rotary = make_rotary_table(d.max_positions, d.rotary);+ // Quantize every GPU-bound buffer through the same f16 round-trip `make_f16` applies,+ // so the reference and the GPU start from identical values (see quantize_f16's doc).+ for (auto* v : {&ref.raw_index_keys_all, &ref.index_query_cur, &ref.key_all, &ref.value_all, &ref.query_cur, &ref.q_norm, &ref.k_norm, &ref.rotary}) {+ quantize_f16(*v);+ }+ return ref;+}++/// Flat selection plan shared by both address modes: sel [q_len, K], count [q_len].+struct selection_plan {+ std::vector<int32_t> sel;+ std::vector<int32_t> count;+};++/// Synthetic plan for perf runs: `min(K, n_complete)` evenly spread complete blocks.+selection_plan synthetic_plan(const split_dims& d, size_t past_len, size_t q_len) {+ selection_plan plan;+ plan.sel.assign(q_len * d.block_topk, 0);+ plan.count.assign(q_len, 0);+ for (size_t t = 0; t < q_len; t++) {+ const size_t n_complete = (past_len + t + 1) / d.r;+ const size_t count = std::min(d.block_topk, n_complete);+ for (size_t i = 0; i < count; i++) {+ plan.sel[t * d.block_topk + i] = static_cast<int32_t>(i * n_complete / count);+ }+ plan.count[t] = static_cast<int32_t>(count);+ }+ return plan;+}++// ---------------------------------------------------------------------------+// Paged pair (PagedQSAIndexer + SparsePA)+// ---------------------------------------------------------------------------++struct paged_inputs {+ split_dims d;+ size_t past_len = 0;+ size_t q_len = 0;+ size_t num_pages = 0;+ size_t spp = 0; // summaries per page++ std::vector<float> index_query, raw_index_keys, query, key, value, rotary, q_norm, k_norm;+ std::vector<float> key_cache, value_cache, raw_k_cache, block_index_keys_cache;+ std::vector<int32_t> position_ids, position_cache, block_indices, block_indices_begins, subsequence_begins, past_lens, qb_start;+ selection_plan plan; // only used when the attention runs without the indexer+};++void init_paged_metadata(paged_inputs& in, const split_dims& d, size_t past_len, size_t q_len) {+ in.d = d;+ in.past_len = past_len;+ in.q_len = q_len;+ const size_t total = past_len + q_len;+ in.num_pages = (total + d.page_size - 1) / d.page_size;+ in.spp = d.page_size / d.r;+ in.block_indices.resize(in.num_pages);+ std::iota(in.block_indices.begin(), in.block_indices.end(), 0);+ in.block_indices_begins = {0, static_cast<int32_t>(in.num_pages)};+ in.past_lens = {static_cast<int32_t>(past_len)};+ in.subsequence_begins = {0, static_cast<int32_t>(q_len)};+ in.qb_start = {0, static_cast<int32_t>(q_len)};+}++paged_inputs paged_inputs_from_reference(const split_reference& ref) {+ const auto& d = ref.d;+ paged_inputs in;+ init_paged_metadata(in, d, ref.past_len, ref.q_len);+ const size_t past_len = ref.past_len;++ in.key_cache.assign(in.num_pages * d.Hkv * d.page_size * d.Dh, 0.0f);+ in.value_cache.assign(in.num_pages * d.Hkv * d.page_size * d.Dv, 0.0f);+ in.raw_k_cache.assign(in.num_pages * d.page_size * d.Di, 0.0f);+ in.block_index_keys_cache.assign(in.num_pages * in.spp * d.Di, 0.0f);+ in.position_cache.assign(in.num_pages * in.spp, 0);++ for (size_t p = 0; p < past_len; p++) {+ const size_t page = p / d.page_size;+ const size_t slot = p % d.page_size;+ for (size_t h = 0; h < d.Hkv; h++) {+ for (size_t j = 0; j < d.Dh; j++) {+ in.key_cache[((page * d.Hkv + h) * d.page_size + slot) * d.Dh + j] = ref.key_all[p * d.Hkv * d.Dh + h * d.Dh + j];+ }+ for (size_t j = 0; j < d.Dv; j++) {+ in.value_cache[((page * d.Hkv + h) * d.page_size + slot) * d.Dv + j] = ref.value_all[p * d.Hkv * d.Dv + h * d.Dv + j];+ }+ }+ for (size_t j = 0; j < d.Di; j++) {+ in.raw_k_cache[(page * d.page_size + slot) * d.Di + j] = ref.raw_index_keys_all[p * d.Di + j];+ }+ }+ // Every block whose first token is history has its position recorded, including a+ // partial block that this call completes.+ for (size_t b = 0; b * d.r < past_len; b++) {+ const size_t page = b / in.spp;+ const size_t slot = b % in.spp;+ in.position_cache[page * in.spp + slot] = ref.positions[b * d.r];+ if (b * d.r + d.r <= past_len) {+ const auto s = ref.summary(b);+ std::copy(s.begin(), s.end(), in.block_index_keys_cache.begin() + (page * in.spp + slot) * d.Di);+ }+ }++ in.position_ids.assign(ref.positions.begin() + past_len, ref.positions.end());+ in.index_query = ref.index_query_cur;+ in.raw_index_keys.assign(ref.raw_index_keys_all.begin() + past_len * d.Di, ref.raw_index_keys_all.end());+ in.query = ref.query_cur;+ in.key.assign(ref.key_all.begin() + past_len * d.Hkv * d.Dh, ref.key_all.end());+ in.value.assign(ref.value_all.begin() + past_len * d.Hkv * d.Dv, ref.value_all.end());+ in.rotary = ref.rotary;+ in.q_norm = ref.q_norm;+ in.k_norm = ref.k_norm;+ return in;+}++paged_inputs paged_inputs_synthetic(const split_dims& dims, size_t past_len, size_t q_len, size_t batch = 1) {+ paged_inputs in;+ split_dims d = dims;+ d.max_positions = past_len + q_len;+ init_paged_metadata(in, d, past_len, q_len);+ in.key_cache = lcg_vec(in.num_pages * d.Hkv * d.page_size * d.Dh, 1);+ in.value_cache = lcg_vec(in.num_pages * d.Hkv * d.page_size * d.Dv, 2);+ in.raw_k_cache = lcg_vec(in.num_pages * d.page_size * d.Di, 3);+ in.block_index_keys_cache = lcg_vec(in.num_pages * in.spp * d.Di, 4);+ in.position_cache.resize(in.num_pages * in.spp);+ for (size_t b = 0; b < in.position_cache.size(); b++) {+ in.position_cache[b] = static_cast<int32_t>(std::min(b * d.r, d.max_positions - 1));+ }+ in.position_ids.resize(q_len);+ std::iota(in.position_ids.begin(), in.position_ids.end(), static_cast<int32_t>(past_len));+ in.index_query = lcg_vec(q_len * d.Hiq * d.Di, 5);+ in.raw_index_keys = lcg_vec(q_len * d.Di, 6);+ in.query = lcg_vec(q_len * d.Hq * d.Dh, 7);+ in.key = lcg_vec(q_len * d.Hkv * d.Dh, 8);+ in.value = lcg_vec(q_len * d.Hkv * d.Dv, 9);+ in.rotary = make_rotary_table(d.max_positions, d.rotary);+ in.q_norm = lcg_vec(d.Di, 10, 0.5f);+ in.k_norm = lcg_vec(d.Di, 11, 0.5f);+ in.plan = synthetic_plan(d, past_len, q_len);+ // `batch` sequences, each with its own copy of the pages and a contiguous page run.+ const size_t pages = in.num_pages;+ auto tile = [batch](auto& v) {+ const auto one = v;+ v.reserve(one.size() * batch);+ for (size_t b = 1; b < batch; b++) {+ v.insert(v.end(), one.begin(), one.end());+ }+ };+ tile(in.key_cache);+ tile(in.value_cache);+ tile(in.raw_k_cache);+ tile(in.block_index_keys_cache);+ tile(in.index_query);+ tile(in.raw_index_keys);+ tile(in.query);+ tile(in.key);+ tile(in.value);+ tile(in.position_cache);+ tile(in.position_ids);+ tile(in.plan.sel);+ tile(in.plan.count);+ in.block_indices.resize(pages * batch);+ std::iota(in.block_indices.begin(), in.block_indices.end(), 0);+ in.block_indices_begins.assign(batch + 1, 0);+ in.subsequence_begins.assign(batch + 1, 0);+ in.past_lens.assign(batch, static_cast<int32_t>(past_len));+ for (size_t b = 0; b < batch; b++) {+ in.block_indices_begins[b + 1] = static_cast<int32_t>((b + 1) * pages);+ in.subsequence_begins[b + 1] = static_cast<int32_t>((b + 1) * q_len);+ }+ in.qb_start = in.subsequence_begins;+ in.num_pages = pages * batch;+ in.q_len = q_len * batch;+ return in;+}++enum class Stage { Pair, IndexerOnly, AttentionOnly };++ExecutionConfig make_config(engine& engine) {+ ExecutionConfig cfg = get_test_default_config(engine);+ cfg.set_property(ov::intel_gpu::optimize_data(true));+ cfg.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ return cfg;+}++/// Adds a per-call tensor: a constant in a static topology, a network input (with the given+/// dynamic shape) in a dynamic one, where set_*_inputs() feeds it on every call.+void add_call_tensor(topology& topo, bool dynamic, const primitive_id& id, const ov::PartialShape& dyn_shape, const memory::ptr& mem) {+ if (dynamic) {+ topo.add(input_layout(id, layout{dyn_shape, mem->get_layout().data_type, format::bfyx}));+ } else {+ topo.add(data(id, mem));+ }+}++void set_paged_inputs(engine& engine, network& net, const paged_inputs& in, Stage stage, bool dynamic) {+ const auto& d = in.d;+ const auto q = I(in.q_len);+ const auto np = I(in.num_pages);+ if (dynamic) {+ net.set_input_data("block_indices", make_i32(engine, {np}, in.block_indices));+ net.set_input_data("block_indices_begins", make_i32(engine, {I(in.block_indices_begins.size())}, in.block_indices_begins));+ net.set_input_data("subsequence_begins", make_i32(engine, {I(in.subsequence_begins.size())}, in.subsequence_begins));+ net.set_input_data("past_lens", make_i32(engine, {I(in.past_lens.size())}, in.past_lens));+ }+ if (stage != Stage::AttentionOnly) {+ if (dynamic) {+ net.set_input_data("q_norm", make_f16(engine, {I(d.Di)}, in.q_norm));+ net.set_input_data("k_norm", make_f16(engine, {I(d.Di)}, in.k_norm));+ }+ const auto [rope_cos, rope_sin] = rope_rows(in.rotary, d.rotary, in.position_ids);+ net.set_input_data("index_query", make_f16(engine, {q, I(d.Hiq * d.Di)}, in.index_query));+ net.set_input_data("raw_index_keys", make_f16(engine, {q, I(d.Di)}, in.raw_index_keys));+ net.set_input_data("rope_cos", make_f16(engine, {q, I(d.rotary)}, rope_cos));+ net.set_input_data("rope_sin", make_f16(engine, {q, I(d.rotary)}, rope_sin));+ net.set_input_data("block_index_keys_cache", make_f16(engine, {np, 1, I(in.spp), I(d.Di)}, in.block_index_keys_cache));+ net.set_input_data("raw_k_cache", make_f16(engine, {np, 1, I(d.page_size), I(d.Di)}, in.raw_k_cache));+ net.set_input_data("rope_cache", make_f16(engine, {np, I(in.spp), I(2 * d.rotary)}, rope_cache_rows(in.rotary, d.rotary, in.position_cache)));+ }+ if (stage != Stage::IndexerOnly) {+ net.set_input_data("query", make_f16(engine, {q, I(d.Hq * d.Dh)}, in.query));+ net.set_input_data("key", make_f16(engine, {q, I(d.Hkv * d.Dh)}, in.key));+ net.set_input_data("value", make_f16(engine, {q, I(d.Hkv * d.Dv)}, in.value));+ net.set_input_data("key_cache", make_f16(engine, {np, I(d.Hkv), I(d.page_size), I(d.Dh)}, in.key_cache));+ net.set_input_data("value_cache", make_f16(engine, {np, I(d.Hkv), I(d.page_size), I(d.Dv)}, in.value_cache));+ }+}++/// `dynamic`: token/page/sequence extents are dynamic and every per-call tensor is an input,+/// so ONE network serves any (past_len, q_len) through the shape-agnostic impls.+std::unique_ptr<network> build_paged_network(engine& engine, const paged_inputs& in, Stage stage, bool dynamic = false) {+ const auto& d = in.d;+ const auto dyn = [dynamic](int64_t v) {+ return dynamic ? int64_t{-1} : v;+ };+ const auto q = dyn(I(in.q_len));+ const auto np = dyn(I(in.num_pages));+ topology topo;+ add_call_tensor(topo, dynamic, "block_indices", {-1}, make_i32(engine, {I(in.num_pages)}, in.block_indices));+ add_call_tensor(topo, dynamic, "block_indices_begins", {-1}, make_i32(engine, {I(in.block_indices_begins.size())}, in.block_indices_begins));+ add_call_tensor(topo, dynamic, "subsequence_begins", {-1}, make_i32(engine, {I(in.subsequence_begins.size())}, in.subsequence_begins));+ add_call_tensor(topo, dynamic, "past_lens", {-1}, make_i32(engine, {I(in.past_lens.size())}, in.past_lens));++ if (stage != Stage::AttentionOnly) {+ ov::intel_gpu::op::PagedQSAIndexer::Config cfg;+ cfg.key_block_size = d.r;+ cfg.block_topk = d.block_topk;+ cfg.num_selection_heads = 1;+ cfg.indexer_rotary_dim = d.rotary;+ cfg.indexer_head_dim = d.Di;+ cfg.epsilon = d.eps;+ cfg.scale = 1.0f / std::sqrt(static_cast<float>(d.Di));++ topo.add(input_layout("index_query", layout{{q, I(d.Hiq * d.Di)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("raw_index_keys", layout{{q, I(d.Di)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("rope_cos", layout{{q, I(d.rotary)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("rope_sin", layout{{q, I(d.rotary)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("block_index_keys_cache", layout{{np, 1, I(in.spp), I(d.Di)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("raw_k_cache", layout{{np, 1, I(d.page_size), I(d.Di)}, data_types::f16, format::bfyx}));+ add_call_tensor(topo, dynamic, "q_norm", {I(d.Di)}, make_f16(engine, {I(d.Di)}, in.q_norm));+ add_call_tensor(topo, dynamic, "k_norm", {I(d.Di)}, make_f16(engine, {I(d.Di)}, in.k_norm));+ topo.add(input_layout("rope_cache", layout{{np, I(in.spp), I(2 * d.rotary)}, data_types::f16, format::bfyx}));+ static_assert(PagedIn::COUNT == 13, "keep the test input order in sync with PagedQSAIndexer::InputIdx");+ topo.add(paged_qsa_indexer("indexer",+ {input_info("index_query"),+ input_info("raw_index_keys"),+ input_info("rope_cos"),+ input_info("rope_sin"),+ input_info("q_norm"),+ input_info("k_norm"),+ input_info("past_lens"),+ input_info("subsequence_begins"),+ input_info("block_indices"),+ input_info("block_indices_begins"),+ input_info("raw_k_cache"),+ input_info("rope_cache"),+ input_info("block_index_keys_cache")},+ cfg));+ }++ if (stage != Stage::IndexerOnly) {+ cldnn::sparse_pa::Config cfg;+ cfg.num_heads = d.Hq;+ cfg.num_kv_heads = d.Hkv;+ cfg.num_selection_heads = 1;+ cfg.k_head_size = d.Dh;+ cfg.v_head_size = d.Dv;+ cfg.key_block_size = d.r;+ cfg.query_block_size = 1;+ cfg.causal = true;+ const float scale = 1.0f / std::sqrt(static_cast<float>(d.Dh));++ topo.add(input_layout("query", layout{{q, I(d.Hq * d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("key", layout{{q, I(d.Hkv * d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("value", layout{{q, I(d.Hkv * d.Dv)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("key_cache", layout{{np, I(d.Hkv), I(d.page_size), I(d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("value_cache", layout{{np, I(d.Hkv), I(d.page_size), I(d.Dv)}, data_types::f16, format::bfyx}));+ input_info sel("indexer", 0), count("indexer", 1);+ if (stage == Stage::AttentionOnly) {+ topo.add(data("sel", make_i32(engine, {I(in.q_len), 1, I(d.block_topk)}, in.plan.sel)));+ topo.add(data("count", make_i32(engine, {I(in.q_len), 1}, in.plan.count)));+ sel = input_info("sel");+ count = input_info("count");+ }+ // The primitive takes QUERY..SELECTED_BLOCK_COUNT only: scale is folded in, sinks are unsupported, qb_start is unused.+ static_assert(SparsePAIn::SELECTED_BLOCK_COUNT == 10 && SparsePAIn::PAST_LENS == 5, "keep the test input order in sync with PagedSparseAttention");+ topo.add(sparse_pa("attn",+ {input_info("query"),+ input_info("key"),+ input_info("value"),+ input_info("key_cache"),+ input_info("value_cache"),+ input_info("past_lens"),+ input_info("subsequence_begins"),+ input_info("block_indices"),+ input_info("block_indices_begins"),+ sel,+ count},+ cfg,+ scale));+ }++ auto net = std::make_unique<network>(engine, topo, make_config(engine));+ set_paged_inputs(engine, *net, in, stage, dynamic);+ return net;+}++// ---------------------------------------------------------------------------+// Dense pair (QSAIndexer + SparseSDPA). Every batch row has its own reference; a row+// shorter than the shared query length L is a fresh sequence, left-padded to L, and its+// K/V are left-padded to the longest row's length S (SparseSDPA's key_length contract).+// ---------------------------------------------------------------------------++template <typename T>+void append(std::vector<T>& dst, const std::vector<T>& src) {+ dst.insert(dst.end(), src.begin(), src.end());+}++/// Storage the ops must never read (left padding, unused state slots): any read poisons+/// the output with NaN.+const float poison = std::numeric_limits<float>::quiet_NaN();++struct dense_inputs {+ split_dims d;+ size_t batch = 0;+ size_t q_len = 0; // L, shared by every row+ size_t kv_len = 0; // S, the longest row; shorter rows are left-padded+ size_t summary_cap = 1; // floor(S_cap / r) summary entries, uniform across rows++ std::vector<int32_t> key_length; // [B], valid tokens after the call+ std::vector<float> index_query, raw_index_keys, rope_cos, rope_sin, q_norm, k_norm;+ std::vector<float> block_index_keys_cache; // [B, 1, summary_cap, Di]+ std::vector<float> raw_state; // [B, 1, r - 1, Di], slot p % r of the incomplete block+ std::vector<float> rope_state; // [B, 2 * rotary], first-token row of the incomplete block+ std::vector<float> query_bhld, key_bhsd, value_bhsd;+ selection_plan plan; // only used when the attention runs without the indexer+};++/// Left-padding rows of batch row `b`.+size_t dense_pad(const dense_inputs& in, size_t b) {+ return in.q_len - std::min(in.q_len, static_cast<size_t>(in.key_length[b]));+}++/// Appends batch row `ref`: inputs left-padded to `in.q_len`, K/V left-padded to `in.kv_len`,+/// and the state a previous call would have returned after `ref.past_len` tokens.+void append_dense_row(dense_inputs& in, const split_reference& ref) {+ const auto& d = in.d;+ const size_t L = in.q_len;+ const size_t S = in.kv_len;+ const size_t past = ref.past_len;+ const size_t total = ref.total_len();+ ASSERT_TRUE(ref.q_len <= L && total <= S && (ref.q_len == L || past == 0)) << "only a new sequence can be left-padded";+ const size_t pad = L - ref.q_len;+ const size_t pad_k = S - total;+ in.key_length.push_back(static_cast<int32_t>(total));++ auto left_padded = [pad](const std::vector<float>& rows, size_t width) {+ std::vector<float> out(pad * width, poison);+ append(out, rows);+ return out;+ };+ append(in.index_query, left_padded(ref.index_query_cur, d.Hiq * d.Di));+ append(in.raw_index_keys, left_padded(std::vector<float>(ref.raw_index_keys_all.begin() + past * d.Di, ref.raw_index_keys_all.end()), d.Di));+ const auto [cos, sin] = rope_rows(ref.rotary, d.rotary, std::vector<int32_t>(ref.positions.begin() + past, ref.positions.end()));+ append(in.rope_cos, left_padded(cos, d.rotary));+ append(in.rope_sin, left_padded(sin, d.rotary));++ std::vector<float> summary(in.summary_cap * d.Di, 0.0f);+ for (size_t b = 0; b < past / d.r; b++) {+ const auto s = ref.summary(b);+ std::copy(s.begin(), s.end(), summary.begin() + b * d.Di);+ }+ append(in.block_index_keys_cache, summary);+ const size_t staged = past % d.r;+ const size_t first = past - staged;+ std::vector<float> raw((d.r - 1) * d.Di, poison);+ std::copy(ref.raw_index_keys_all.begin() + first * d.Di, ref.raw_index_keys_all.begin() + past * d.Di, raw.begin());+ append(in.raw_state, raw);+ append(in.rope_state, staged ? rope_state_row(ref.rotary, d.rotary, ref.positions[first]) : std::vector<float>(2 * d.rotary, poison));++ std::vector<float> query(d.Hq * L * d.Dh, poison);+ for (size_t t = 0; t < ref.q_len; t++) {+ for (size_t h = 0; h < d.Hq; h++) {+ for (size_t j = 0; j < d.Dh; j++) {+ query[(h * L + pad + t) * d.Dh + j] = ref.query_cur[(t * d.Hq + h) * d.Dh + j];+ }+ }+ }+ append(in.query_bhld, query);+ std::vector<float> key(d.Hkv * S * d.Dh, poison);+ std::vector<float> value(d.Hkv * S * d.Dv, poison);+ for (size_t p = 0; p < total; p++) {+ for (size_t h = 0; h < d.Hkv; h++) {+ for (size_t j = 0; j < d.Dh; j++) {+ key[(h * S + pad_k + p) * d.Dh + j] = ref.key_all[p * d.Hkv * d.Dh + h * d.Dh + j];+ }+ for (size_t j = 0; j < d.Dv; j++) {+ value[(h * S + pad_k + p) * d.Dv + j] = ref.value_all[p * d.Hkv * d.Dv + h * d.Dv + j];+ }+ }+ }+ append(in.key_bhsd, key);+ append(in.value_bhsd, value);+}++dense_inputs dense_inputs_from_references(const std::vector<split_reference>& refs) {+ dense_inputs in;+ in.d = refs.front().d;+ in.batch = refs.size();+ size_t blocks = 0;+ for (const auto& ref : refs) {+ in.q_len = std::max(in.q_len, ref.q_len);+ in.kv_len = std::max(in.kv_len, ref.total_len());+ blocks = std::max(blocks, ref.total_len() / in.d.r);+ }+ in.summary_cap = std::max<size_t>(1, blocks);+ in.q_norm = refs.front().q_norm;+ in.k_norm = refs.front().k_norm;+ for (const auto& ref : refs) {+ append_dense_row(in, ref);+ }+ return in;+}++dense_inputs dense_inputs_from_reference(const split_reference& ref) {+ return dense_inputs_from_references({ref});+}++dense_inputs dense_inputs_synthetic(const split_dims& dims, size_t past_len, size_t q_len, size_t batch = 1) {+ dense_inputs in;+ in.d = dims;+ const auto& d = in.d;+ const size_t total = past_len + q_len;+ in.batch = 1;+ in.q_len = q_len;+ in.kv_len = total;+ in.summary_cap = std::max<size_t>(1, total / d.r);+ in.key_length = {static_cast<int32_t>(total)};+ const auto rotary = make_rotary_table(total, d.rotary);+ std::vector<int32_t> positions(q_len);+ std::iota(positions.begin(), positions.end(), static_cast<int32_t>(past_len));+ std::tie(in.rope_cos, in.rope_sin) = rope_rows(rotary, d.rotary, positions);+ in.block_index_keys_cache = lcg_vec(in.summary_cap * d.Di, 4);+ in.raw_state = lcg_vec((d.r - 1) * d.Di, 3);+ in.rope_state = rope_state_row(rotary, d.rotary, static_cast<int32_t>(past_len - past_len % d.r));+ in.index_query = lcg_vec(q_len * d.Hiq * d.Di, 5);+ in.raw_index_keys = lcg_vec(q_len * d.Di, 6);+ in.query_bhld = lcg_vec(d.Hq * q_len * d.Dh, 7);+ in.key_bhsd = lcg_vec(d.Hkv * total * d.Dh, 8);+ in.value_bhsd = lcg_vec(d.Hkv * total * d.Dv, 9);+ in.q_norm = lcg_vec(d.Di, 10, 0.5f);+ in.k_norm = lcg_vec(d.Di, 11, 0.5f);+ in.plan = synthetic_plan(d, past_len, q_len);+ // Every batch row repeats row 0's content (all tensors are batch-major).+ in.batch = batch;+ for (auto* v : {&in.index_query,+ &in.raw_index_keys,+ &in.rope_cos,+ &in.rope_sin,+ &in.block_index_keys_cache,+ &in.raw_state,+ &in.rope_state,+ &in.query_bhld,+ &in.key_bhsd,+ &in.value_bhsd}) {+ const auto row = *v;+ v->reserve(row.size() * batch);+ for (size_t b = 1; b < batch; b++) {+ append(*v, row);+ }+ }+ in.key_length.assign(batch, static_cast<int32_t>(total));+ return in;+}++void set_dense_inputs(engine& engine, network& net, const dense_inputs& in, Stage stage, bool dynamic) {+ const auto& d = in.d;+ const auto B = I(in.batch);+ const auto q = I(in.q_len);+ const auto S = I(in.kv_len);+ if (dynamic) {+ net.set_input_data("key_length", make_i32(engine, {B}, in.key_length));+ }+ if (stage != Stage::AttentionOnly) {+ if (dynamic) {+ net.set_input_data("q_norm", make_f16(engine, {I(d.Di)}, in.q_norm));+ net.set_input_data("k_norm", make_f16(engine, {I(d.Di)}, in.k_norm));+ }+ net.set_input_data("index_query", make_f16(engine, {B, q, I(d.Hiq), I(d.Di)}, in.index_query));+ net.set_input_data("raw_index_keys", make_f16(engine, {B, q, 1, I(d.Di)}, in.raw_index_keys));+ net.set_input_data("rope_cos", make_f16(engine, {B, q, I(d.rotary)}, in.rope_cos));+ net.set_input_data("rope_sin", make_f16(engine, {B, q, I(d.rotary)}, in.rope_sin));+ net.set_input_data("block_index_keys_cache", make_f16(engine, {B, 1, I(in.summary_cap), I(d.Di)}, in.block_index_keys_cache));+ net.set_input_data("raw_state", make_f16(engine, {B, 1, I(d.r - 1), I(d.Di)}, in.raw_state));+ net.set_input_data("rope_state", make_f16(engine, {B, I(2 * d.rotary)}, in.rope_state));+ }+ if (stage != Stage::IndexerOnly) {+ net.set_input_data("query", make_f16(engine, {B, I(d.Hq), q, I(d.Dh)}, in.query_bhld));+ net.set_input_data("key", make_f16(engine, {B, I(d.Hkv), S, I(d.Dh)}, in.key_bhsd));+ net.set_input_data("value", make_f16(engine, {B, I(d.Hkv), S, I(d.Dv)}, in.value_bhsd));+ }+}++/// `dynamic`: B/L/S and the summary capacity are dynamic and every per-call tensor is an+/// input, so ONE network serves any (batch, key_length, q_len) through the shape-agnostic impls.+std::unique_ptr<network> build_dense_network(engine& engine, const dense_inputs& in, Stage stage, bool dynamic = false) {+ const auto& d = in.d;+ const auto dyn = [dynamic](int64_t v) {+ return dynamic ? int64_t{-1} : v;+ };+ const auto B = dyn(I(in.batch));+ const auto q = dyn(I(in.q_len));+ const auto S = dyn(I(in.kv_len));+ const auto summary_cap = dyn(I(in.summary_cap));+ topology topo;+ add_call_tensor(topo, dynamic, "key_length", {-1}, make_i32(engine, {I(in.batch)}, in.key_length));++ if (stage != Stage::AttentionOnly) {+ ov::intel_gpu::op::QSAIndexer::Config cfg;+ cfg.key_block_size = d.r;+ cfg.block_topk = d.block_topk;+ cfg.num_selection_heads = 1;+ cfg.indexer_rotary_dim = d.rotary;+ cfg.indexer_head_dim = d.Di;+ cfg.epsilon = d.eps;+ cfg.scale = 1.0f / std::sqrt(static_cast<float>(d.Di));++ topo.add(input_layout("index_query", layout{{B, q, I(d.Hiq), I(d.Di)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("raw_index_keys", layout{{B, q, 1, I(d.Di)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("rope_cos", layout{{B, q, I(d.rotary)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("rope_sin", layout{{B, q, I(d.rotary)}, data_types::f16, format::bfyx}));+ add_call_tensor(topo, dynamic, "q_norm", {I(d.Di)}, make_f16(engine, {I(d.Di)}, in.q_norm));+ add_call_tensor(topo, dynamic, "k_norm", {I(d.Di)}, make_f16(engine, {I(d.Di)}, in.k_norm));+ topo.add(input_layout("block_index_keys_cache", layout{{B, 1, summary_cap, I(d.Di)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("raw_state", layout{{B, 1, I(d.r - 1), I(d.Di)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("rope_state", layout{{B, I(2 * d.rotary)}, data_types::f16, format::bfyx}));+ static_assert(DenseIdxIn::COUNT == 10, "keep the test input order in sync with QSAIndexer::InputIdx");+ topo.add(qsa_indexer("indexer",+ {input_info("index_query"),+ input_info("raw_index_keys"),+ input_info("rope_cos"),+ input_info("rope_sin"),+ input_info("key_length"),+ input_info("q_norm"),+ input_info("k_norm"),+ input_info("block_index_keys_cache"),+ input_info("raw_state"),+ input_info("rope_state")},+ cfg));+ }++ if (stage != Stage::IndexerOnly) {+ ov::intel_gpu::op::SparseSDPA::Config cfg;+ cfg.num_heads = d.Hq;+ cfg.num_kv_heads = d.Hkv;+ cfg.num_selection_heads = 1;+ cfg.k_head_size = d.Dh;+ cfg.v_head_size = d.Dv;+ cfg.key_block_size = d.r;+ cfg.query_block_size = 1;+ cfg.causal = true;++ topo.add(input_layout("query", layout{{B, I(d.Hq), q, I(d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("key", layout{{B, I(d.Hkv), S, I(d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("value", layout{{B, I(d.Hkv), S, I(d.Dv)}, data_types::f16, format::bfyx}));+ input_info sel("indexer", 0), count("indexer", 1);+ if (stage == Stage::AttentionOnly) {+ topo.add(data("sel", make_i32(engine, {1, 1, I(in.q_len), I(d.block_topk)}, in.plan.sel)));+ topo.add(data("count", make_i32(engine, {1, 1, I(in.q_len)}, in.plan.count)));+ sel = input_info("sel");+ count = input_info("count");+ }+ static_assert(SparseSDPAIn::COUNT_CORE == 6, "keep the test input order in sync with SparseSDPA::InputIdx");+ topo.add(sparse_sdpa("attn",+ {input_info("query"), input_info("key"), input_info("value"), sel, count, input_info("key_length")},+ cfg,+ 1.0f / std::sqrt(static_cast<float>(d.Dh))));+ }++ auto net = std::make_unique<network>(engine, topo, make_config(engine));+ set_dense_inputs(engine, *net, in, stage, dynamic);+ return net;+}++// ---------------------------------------------------------------------------+// Validation+// ---------------------------------------------------------------------------++struct pair_outputs {+ selection_plan plan; // GPU indexer outputs, flat+ std::vector<float> attn; // token-major [q_len, Hq*Dv]+ std::vector<std::string> indexer_kernels, attention_kernels;+};++/// Kernels the primitive's last execute() enqueued, in order, without the `_ocl_<hash>` suffix.+std::vector<std::string> executed_kernels(network& net, const primitive_id& id) {+ auto inst = net.get_primitive(id);+ std::istringstream entries(inst->get_impl()->get_kernels_dump_info(*inst->get_impl_params()).get_entries());+ std::vector<std::string> names;+ for (std::string entry; entries >> entry;) {+ names.push_back(entry.substr(0, entry.rfind("_ocl_")));+ }+ return names;+}++void read_pair_outputs(network& net, pair_outputs& out) {+ auto indexer = net.get_primitive("indexer");+ out.plan.sel = read_i32(indexer->output_memory_ptr(0));+ out.plan.count = read_i32(indexer->output_memory_ptr(1));+ // Dynamic networks may keep a larger buffer from an earlier call.+ out.plan.sel.resize(indexer->get_output_layout(0).count());+ out.plan.count.resize(indexer->get_output_layout(1).count());+ out.indexer_kernels = executed_kernels(net, "indexer");+ out.attention_kernels = executed_kernels(net, "attn");+}++enum class IndexerPath { Decode, Dpas, Fused };+enum class AttnPath { Scalar, Dpas, GqaDpas, GqaSplit, Split };++/// Expected kernel routing of one pair execution; `decode_chunks` counts BLOCK_SCORES row chunks.+struct route {+ IndexerPath indexer;+ AttnPath attention;+ size_t decode_chunks = 1;+};++std::vector<std::string> expected_indexer_kernels(bool paged, const route& r) {+ std::vector<std::string> k = {paged ? "qsa_indexer_prepare_paged" : "qsa_indexer_prepare_dense"};+ switch (r.indexer) {+ case IndexerPath::Decode:+ for (size_t i = 0; i < r.decode_chunks; i++) {+ k.insert(k.end(), {"qsa_indexer_score_partition", "qsa_indexer_topk_decode"});+ }+ break;+ case IndexerPath::Dpas:+ k.insert(k.end(), {"qsa_indexer_score_dpas", "qsa_indexer_topk"});+ break;+ case IndexerPath::Fused:+ // There is no single-thread fused kernel: partition scorer + prefill top-k.+ k.insert(k.end(), {"qsa_indexer_score_partition", "qsa_indexer_topk"});+ break;+ }+ return k;+}++std::vector<std::string> expected_attention_kernels(bool paged, const route& r) {+ const std::string base = paged ? "sparse_attention_paged" : "sparse_attention_dense";+ std::vector<std::string> k;+ if (paged) {+ k.push_back("sparse_attention_kv_write");+ }+ switch (r.attention) {+ case AttnPath::Scalar:+ k.push_back(base);+ break;+ case AttnPath::Dpas:+ k.push_back(base + "_dpas");+ break;+ case AttnPath::GqaDpas:+ k.push_back(base + "_gqa_dpas");+ break;+ case AttnPath::GqaSplit:+ k.insert(k.end(), {base + "_gqa_dpas_split", base + "_split_reduce"});+ break;+ case AttnPath::Split:+ k.insert(k.end(), {base + "_split", base + "_split_reduce"});+ break;+ }+ return k;+}++/// Mirrors qsa::xmx_allowed(): the systolic kernels are only routed on Xe2+ (so not on DG2) and can be switched off.+bool xmx_routes_enabled() {+ const char* v = std::getenv("OV_GPU_QSA_OCL_DISABLE_XMX");+ if (v != nullptr && std::string(v) == "1") {+ return false;+ }+ const auto& info = get_test_engine().get_device_info();+ return info.arch >= gpu_arch::xe2 && info.supports_immad;+}++/// Route the plugin takes without XMX; `kv_len` is the dense key length (SparseSDPA splits decode from 2048 on).+route resolve_route(const route& r, bool paged, size_t kv_len) {+ if (xmx_routes_enabled()) {+ return r;+ }+ constexpr size_t dense_split_min_kv = 2048;+ route out = r;+ if (out.indexer == IndexerPath::Dpas) {+ out.indexer = IndexerPath::Fused;+ }+ if (out.attention == AttnPath::Dpas || out.attention == AttnPath::GqaDpas) {+ out.attention = AttnPath::Scalar;+ } else if (out.attention == AttnPath::GqaSplit) {+ out.attention = (paged || kv_len >= dense_split_min_kv) ? AttnPath::Split : AttnPath::Scalar;+ }+ return out;+}++void expect_route(bool paged, const pair_outputs& gpu, const route& expected, size_t kv_len = 0) {+ const auto r = resolve_route(expected, paged, kv_len);+ EXPECT_EQ(gpu.indexer_kernels, expected_indexer_kernels(paged, r));+ EXPECT_EQ(gpu.attention_kernels, expected_attention_kernels(paged, r));+}++pair_outputs run_paged_pair(engine& engine, const split_reference& ref) {+ auto net = build_paged_network(engine, paged_inputs_from_reference(ref), Stage::Pair);+ auto outputs = net->execute();+ pair_outputs out;+ out.attn = read_f16(outputs.at("attn").get_memory());+ read_pair_outputs(*net, out);+ return out;+}++/// [Hq, L, Dv] (B == 1) -> token-major [L, Hq*Dv], the reference's layout.+std::vector<float> bhld_to_token_major(const std::vector<float>& bhld, const split_dims& d, size_t q_len) {+ std::vector<float> out(bhld.size());+ for (size_t t = 0; t < q_len; t++) {+ for (size_t h = 0; h < d.Hq; h++) {+ for (size_t j = 0; j < d.Dv; j++) {+ out[(t * d.Hq + h) * d.Dv + j] = bhld[(h * q_len + t) * d.Dv + j];+ }+ }+ }+ return out;+}++/// Combined absolute+relative error summary (numpy-`allclose`-style), plus a non-finite+/// count so a corrupted/overflowing kernel output fails loudly instead of silently+/// skewing the mean.+struct error_stats {+ double max_abs = 0.0;+ double max_rel = 0.0;+ double mean_abs = 0.0;+ size_t count = 0;+ size_t non_finite = 0;+};++error_stats compute_error_stats(const std::vector<float>& actual, const std::vector<float>& expected) {+ error_stats s;+ double sum_abs = 0.0;+ for (size_t i = 0; i < expected.size(); i++) {+ if (!std::isfinite(actual[i])) {+ s.non_finite++;+ continue;+ }+ const double err = std::fabs(static_cast<double>(actual[i]) - static_cast<double>(expected[i]));+ sum_abs += err;+ s.max_abs = std::max(s.max_abs, err);+ s.max_rel = std::max(s.max_rel, err / std::max(1e-6, std::fabs(static_cast<double>(expected[i]))));+ s.count++;+ }+ s.mean_abs = s.count ? sum_abs / static_cast<double>(s.count) : 0.0;+ return s;+}++void print_error_stats(const char* label, const error_stats& s) {+ std::cout << "QSA_PRECISION " << label << " n=" << s.count << " non_finite=" << s.non_finite << " max_abs=" << s.max_abs << " mean_abs=" << s.mean_abs+ << " max_rel=" << s.max_rel << std::endl;+}++/// With QSA_DUMP_DIR set, writes the GPU attention output and selection plan of every validated pair so that two runs+/// can be diffed directly.+void dump_pair_outputs(const pair_outputs& gpu) {+ const char* dir = std::getenv("QSA_DUMP_DIR");+ if (dir == nullptr) {+ return;+ }+ static int counter = 0;+ const std::string base = std::string(dir) + "/" + ::testing::UnitTest::GetInstance()->current_test_info()->name() + "_" + std::to_string(counter++);+ auto write = [&](const std::string& suffix, const auto& v) {+ std::ofstream f(base + suffix, std::ios::binary);+ f.write(reinterpret_cast<const char*>(v.data()), static_cast<std::streamsize>(v.size() * sizeof(v[0])));+ };+ write(".attn.f32", gpu.attn);+ write(".sel.i32", gpu.plan.sel);+ write(".count.i32", gpu.plan.count);+}++/// Checks the GPU plan against the reference scores (count exact; every selected block+/// complete, unique, and scoring within fp16 tolerance of the k-th best), then compares+/// attention computed by the reference over that same plan using a combined+/// absolute+relative tolerance (`atol + rtol * |ref|`), after asserting every output+/// element is finite.+void validate_pair(const split_reference& ref, const pair_outputs& gpu, float atol, float rtol) {+ dump_pair_outputs(gpu);+ const auto& d = ref.d;+ ASSERT_EQ(gpu.plan.count.size(), ref.q_len);+ ASSERT_EQ(gpu.plan.sel.size(), ref.q_len * d.block_topk);+ std::vector<std::vector<size_t>> selections(ref.q_len);+ for (size_t t = 0; t < ref.q_len; t++) {+ const auto scored = ref.scored_blocks(t);+ const size_t expected_count = std::min(d.block_topk, scored.size());+ ASSERT_EQ(static_cast<size_t>(gpu.plan.count[t]), expected_count) << "t=" << t;+ if (expected_count == 0) {+ continue;+ }+ std::vector<float> score_of(scored.size());+ for (const auto& [score, block] : scored) {+ score_of[block] = score;+ }+ const float kth = scored[expected_count - 1].first;+ const float tol = 1e-2f * std::max(1.0f, std::fabs(kth));+ std::set<size_t> seen;+ for (size_t i = 0; i < expected_count; i++) {+ const int32_t b = gpu.plan.sel[t * d.block_topk + i];+ ASSERT_GE(b, 0) << "t=" << t << " i=" << i;+ ASSERT_LT(static_cast<size_t>(b), scored.size()) << "t=" << t << " selected an incomplete block";+ ASSERT_TRUE(seen.insert(static_cast<size_t>(b)).second) << "t=" << t << " selected block " << b << " twice";+ EXPECT_GE(score_of[b], kth - tol) << "t=" << t << " block " << b << " is not in the top-" << expected_count;+ }+ selections[t].assign(seen.begin(), seen.end());+ }++ const auto expected = ref.attention(selections);+ ASSERT_EQ(gpu.attn.size(), expected.size());+ const auto stats = compute_error_stats(gpu.attn, expected);+ print_error_stats("attention", stats);+ EXPECT_EQ(stats.non_finite, 0u) << "attention output contains non-finite values";++ size_t mismatches = 0;+ for (size_t i = 0; i < expected.size(); i++) {+ const float tol = atol + rtol * std::fabs(expected[i]);+ if (std::isfinite(gpu.attn[i]) && std::fabs(gpu.attn[i] - expected[i]) > tol && mismatches++ < 8) {+ ADD_FAILURE() << "attn[" << i << "] (t=" << i / (d.Hq * d.Dv) << ") gpu=" << gpu.attn[i] << " ref=" << expected[i] << " tol=" << tol;+ }+ }+ EXPECT_EQ(mismatches, 0u);+}++/// Checks the dense state outputs against `refs`: the summary of every complete block, and+/// the staged raw keys and first-token RoPE row of the new incomplete block.+void validate_dense_state(network& net, const dense_inputs& in, const std::vector<split_reference>& refs) {+ using Out = ov::intel_gpu::op::QSAIndexer::OutputIdx;+ const auto& d = in.d;+ auto indexer = net.get_primitive("indexer");+ const auto summary = read_f16(indexer->output_memory_ptr(Out::BLOCK_INDEX_KEYS_CACHE));+ const auto raw = read_f16(indexer->output_memory_ptr(Out::PAST_INCOMPLETE_RAW_K));+ const auto rope = read_f16(indexer->output_memory_ptr(Out::PAST_INCOMPLETE_ROPE));+ ASSERT_EQ(indexer->get_output_layout(Out::BLOCK_INDEX_KEYS_CACHE).count(), in.batch * in.summary_cap * d.Di);+ ASSERT_EQ(indexer->get_output_layout(Out::PAST_INCOMPLETE_RAW_K).count(), in.batch * (d.r - 1) * d.Di);+ ASSERT_EQ(indexer->get_output_layout(Out::PAST_INCOMPLETE_ROPE).count(), in.batch * 2 * d.rotary);+ for (size_t b = 0; b < refs.size(); b++) {+ const auto& ref = refs[b];+ const size_t total = ref.total_len();+ SCOPED_TRACE("state of row " + std::to_string(b) + " key_length=" + std::to_string(total));+ size_t mismatches = 0;+ for (size_t blk = 0; blk < total / d.r; blk++) {+ const auto expected = ref.summary(blk);+ for (size_t j = 0; j < d.Di; j++) {+ const float got = summary[(b * in.summary_cap + blk) * d.Di + j];+ if (!(std::fabs(got - expected[j]) <= 1e-2f + 1e-2f * std::fabs(expected[j])) && mismatches++ < 8) {+ ADD_FAILURE() << "summary[" << blk << "][" << j << "] gpu=" << got << " ref=" << expected[j];+ }+ }+ }+ const size_t staged = total % d.r;+ const size_t first = total - staged;+ for (size_t i = 0; i < staged * d.Di; i++) {+ if (raw[b * (d.r - 1) * d.Di + i] != ref.raw_index_keys_all[first * d.Di + i] && mismatches++ < 8) {+ ADD_FAILURE() << "staged key " << i / d.Di << "[" << i % d.Di << "] gpu=" << raw[b * (d.r - 1) * d.Di + i]+ << " ref=" << ref.raw_index_keys_all[first * d.Di + i];+ }+ }+ if (staged != 0) {+ const auto expected = rope_state_row(ref.rotary, d.rotary, ref.positions[first]);+ for (size_t j = 0; j < expected.size(); j++) {+ if (rope[b * 2 * d.rotary + j] != static_cast<float>(ov::float16(expected[j])) && mismatches++ < 8) {+ ADD_FAILURE() << "rope state[" << j << "] gpu=" << rope[b * 2 * d.rotary + j] << " ref=" << expected[j];+ }+ }+ }+ EXPECT_EQ(mismatches, 0u);+ }+}++/// Validates a dense network execution row by row: the real rows of each batch row against+/// its reference, the left-padding rows (no selection, zero attention), and the state.+void validate_dense_outputs(network& net, const dense_inputs& in, const std::vector<split_reference>& refs, const route* r, float atol, float rtol) {+ const auto& d = in.d;+ const size_t L = in.q_len;+ const size_t K = d.block_topk;+ // The test config may use an out-of-order queue: wait for every kernel before reading back.+ net.get_stream().finish();+ pair_outputs all;+ auto attn_inst = net.get_primitive("attn");+ auto attn = read_f16(attn_inst->output_memory_ptr(0));+ attn.resize(attn_inst->get_output_layout().count());+ read_pair_outputs(net, all);+ if (r != nullptr) {+ expect_route(false, all, *r, in.kv_len);+ }+ ASSERT_EQ(all.plan.count.size(), in.batch * L);+ ASSERT_EQ(attn.size(), in.batch * d.Hq * L * d.Dv);+ for (size_t b = 0; b < refs.size(); b++) {+ const auto& ref = refs[b];+ const size_t pad = dense_pad(in, b);+ SCOPED_TRACE("row " + std::to_string(b) + " past_len=" + std::to_string(ref.past_len) + " q_len=" + std::to_string(ref.q_len));+ size_t bad_padding = 0;+ for (size_t l = 0; l < pad; l++) {+ bad_padding += static_cast<size_t>(all.plan.count[b * L + l] != 0);+ for (size_t i = 0; i < K; i++) {+ bad_padding += static_cast<size_t>(all.plan.sel[(b * L + l) * K + i] != -1);+ }+ for (size_t h = 0; h < d.Hq; h++) {+ for (size_t j = 0; j < d.Dv; j++) {+ bad_padding += static_cast<size_t>(attn[((b * d.Hq + h) * L + l) * d.Dv + j] != 0.0f);+ }+ }+ }+ EXPECT_EQ(bad_padding, 0u) << "left-padding rows must select nothing and output zeros";++ pair_outputs one;+ one.plan.sel.assign(all.plan.sel.begin() + (b * L + pad) * K, all.plan.sel.begin() + (b + 1) * L * K);+ one.plan.count.assign(all.plan.count.begin() + b * L + pad, all.plan.count.begin() + (b + 1) * L);+ one.attn.resize(ref.q_len * d.Hq * d.Dv);+ for (size_t t = 0; t < ref.q_len; t++) {+ for (size_t h = 0; h < d.Hq; h++) {+ for (size_t j = 0; j < d.Dv; j++) {+ one.attn[(t * d.Hq + h) * d.Dv + j] = attn[((b * d.Hq + h) * L + pad + t) * d.Dv + j];+ }+ }+ }+ validate_pair(ref, one, atol, rtol);+ }+ validate_dense_state(net, in, refs);+}++/// One static dense network over `refs` (one batch row each), validated row by row.+void run_dense_rows(engine& engine, const std::vector<split_reference>& refs, const route& r, float atol, float rtol) {+ const auto in = dense_inputs_from_references(refs);+ auto net = build_dense_network(engine, in, Stage::Pair);+ net->execute();+ validate_dense_outputs(*net, in, refs, &r, atol, rtol);+}++void validate_and_run_pair(bool paged, engine& engine, const split_reference& ref, const route& r, float atol, float rtol) {+ if (!paged) {+ run_dense_rows(engine, {ref}, r, atol, rtol);+ return;+ }+ const auto gpu = run_paged_pair(engine, ref);+ expect_route(paged, gpu, r);+ validate_pair(ref, gpu, atol, rtol);+}++void run_pair_case(bool paged, const split_dims& d, size_t past_len, size_t q_len, Positions kind, const route& r, float rtol, float atol, float scale) {+ auto& engine = get_test_engine();+ tests::random_generator rg(GET_SUITE_NAME);+ const auto ref = make_split_reference(rg, d, past_len, q_len, kind, scale);+ validate_and_run_pair(paged, engine, ref, r, atol, rtol);+}++void run_pair_test(bool paged,+ const split_dims& d,+ size_t past_len,+ size_t q_len,+ Positions kind,+ const route& r,+ float rtol,+ float atol = 2e-3f,+ float scale = 1.0f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ ASSERT_GT((past_len + q_len) / d.r, d.block_topk) << "the selection must drop some complete blocks to be meaningful";+ run_pair_case(paged, d, past_len, q_len, kind, r, rtol, atol, scale);+}++/// Short context: every query sees at most block_topk complete blocks, so top-k selects all of them.+void run_full_selection_pair_test(bool paged, const split_dims& d, size_t past_len, size_t q_len, const route& r, float rtol, float atol = 2e-3f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ ASSERT_LE((past_len + q_len) / d.r, d.block_topk);+ run_pair_case(paged, d, past_len, q_len, Positions::Sequential, r, rtol, atol, 1.0f);+}++/// Independent references sharing the norm gains the network takes as single constants.+std::vector<split_reference> make_batch_references(const split_dims& d, const std::vector<std::pair<size_t, size_t>>& seqs) {+ tests::random_generator rg(GET_SUITE_NAME);+ std::vector<split_reference> refs;+ for (const auto& [past_len, q_len] : seqs) {+ refs.push_back(make_split_reference(rg, d, past_len, q_len, Positions::Sequential));+ refs.back().q_norm = refs.front().q_norm;+ refs.back().k_norm = refs.front().k_norm;+ }+ return refs;+}++/// One paged batch: each sequence gets its own contiguous run of pages.+paged_inputs pack_paged_inputs(const std::vector<split_reference>& refs) {+ paged_inputs in;+ in.block_indices_begins = {0};+ in.subsequence_begins = {0};+ for (size_t i = 0; i < refs.size(); i++) {+ auto one = paged_inputs_from_reference(refs[i]);+ if (i == 0 || one.d.max_positions > in.d.max_positions) {+ in.d = one.d; // sequential positions: a longer rotary table is a superset+ in.rotary = one.rotary;+ }+ in.spp = one.spp;+ for (int32_t page : one.block_indices) {+ in.block_indices.push_back(page + static_cast<int32_t>(in.num_pages));+ }+ in.num_pages += one.num_pages;+ in.block_indices_begins.push_back(static_cast<int32_t>(in.num_pages));+ in.q_len += one.q_len;+ in.subsequence_begins.push_back(static_cast<int32_t>(in.q_len));+ in.past_lens.push_back(one.past_lens[0]);+ in.q_norm = one.q_norm;+ in.k_norm = one.k_norm;+ for (auto [dst, src] : {std::pair{&in.index_query, &one.index_query},+ {&in.raw_index_keys, &one.raw_index_keys},+ {&in.query, &one.query},+ {&in.key, &one.key},+ {&in.value, &one.value},+ {&in.key_cache, &one.key_cache},+ {&in.value_cache, &one.value_cache},+ {&in.raw_k_cache, &one.raw_k_cache},+ {&in.block_index_keys_cache, &one.block_index_keys_cache}}) {+ append(*dst, *src);+ }+ append(in.position_ids, one.position_ids);+ append(in.position_cache, one.position_cache);+ }+ in.qb_start = in.subsequence_begins;+ return in;+}++void validate_slices(bool paged, const std::vector<split_reference>& refs, const pair_outputs& all, const route& r, float atol, float rtol) {+ expect_route(paged, all, r);+ const auto& d = refs.front().d;+ size_t t0 = 0;+ for (const auto& ref : refs) {+ pair_outputs one;+ one.plan.sel.assign(all.plan.sel.begin() + t0 * d.block_topk, all.plan.sel.begin() + (t0 + ref.q_len) * d.block_topk);+ one.plan.count.assign(all.plan.count.begin() + t0, all.plan.count.begin() + t0 + ref.q_len);+ one.attn.assign(all.attn.begin() + t0 * d.Hq * d.Dv, all.attn.begin() + (t0 + ref.q_len) * d.Hq * d.Dv);+ SCOPED_TRACE("sequence past_len=" + std::to_string(ref.past_len) + " q_len=" + std::to_string(ref.q_len));+ validate_pair(ref, one, atol, rtol);+ t0 += ref.q_len;+ }+}++/// Multi-sequence paged batch: all decode (q_len == 1 each) or mixed decode/prefill.+void run_paged_batch_test(const split_dims& d, const std::vector<std::pair<size_t, size_t>>& seqs, const route& r, float rtol, float atol = 2e-3f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ auto& engine = get_test_engine();+ const auto refs = make_batch_references(d, seqs);+ auto net = build_paged_network(engine, pack_paged_inputs(refs), Stage::Pair);+ auto outputs = net->execute();+ pair_outputs all;+ all.attn = read_f16(outputs.at("attn").get_memory());+ read_pair_outputs(*net, all);+ validate_slices(true, refs, all, r, atol, rtol);+}++/// Dense batch, one row per (past_len, q_len). Rows may differ in key length (their K/V+/// are left-padded to the longest row); a row with q_len below the longest q_len must have+/// past_len == 0 and is left-padded.+void run_dense_batch_test(const split_dims& d, const std::vector<std::pair<size_t, size_t>>& rows, const route& r, float rtol, float atol = 2e-3f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ run_dense_rows(get_test_engine(), make_batch_references(d, rows), r, atol, rtol);+}++/// Dense batch of `batch` identical-length rows.+void run_dense_batch_test(const split_dims& d, size_t batch, size_t past_len, size_t q_len, const route& r, float rtol, float atol = 2e-3f) {+ run_dense_batch_test(d, std::vector<std::pair<size_t, size_t>>(batch, {past_len, q_len}), r, rtol, atol);+}++/// `full` restricted to its first `past_len + q_len` tokens, the last `q_len` being queries.+/// `full` must have been built with past_len == 0, so it holds every token's query.+split_reference slice_reference(const split_reference& full, size_t past_len, size_t q_len) {+ const auto& d = full.d;+ const size_t total = past_len + q_len;+ split_reference ref;+ ref.d = d;+ ref.past_len = past_len;+ ref.q_len = q_len;+ ref.positions.assign(full.positions.begin(), full.positions.begin() + total);+ ref.raw_index_keys_all.assign(full.raw_index_keys_all.begin(), full.raw_index_keys_all.begin() + total * d.Di);+ ref.index_query_cur.assign(full.index_query_cur.begin() + past_len * d.Hiq * d.Di, full.index_query_cur.begin() + total * d.Hiq * d.Di);+ ref.key_all.assign(full.key_all.begin(), full.key_all.begin() + total * d.Hkv * d.Dh);+ ref.value_all.assign(full.value_all.begin(), full.value_all.begin() + total * d.Hkv * d.Dv);+ ref.query_cur.assign(full.query_cur.begin() + past_len * d.Hq * d.Dh, full.query_cur.begin() + total * d.Hq * d.Dh);+ ref.q_norm = full.q_norm;+ ref.k_norm = full.k_norm;+ ref.rotary = full.rotary;+ return ref;+}++/// Functional state across calls: ONE dynamic dense network runs a sequence chunk by chunk,+/// and every call after the first consumes the state outputs (block_index_keys_cache, staged raw keys,+/// RoPE row) the previous call returned, as ReadValue/Assign would carry them.+void run_dense_state_chain_test(const split_dims& d, const std::vector<size_t>& q_lens, float rtol, float atol = 2e-3f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ using Out = ov::intel_gpu::op::QSAIndexer::OutputIdx;+ auto& engine = get_test_engine();+ tests::random_generator rg(GET_SUITE_NAME);+ const auto full = make_split_reference(rg, d, 0, std::accumulate(q_lens.begin(), q_lens.end(), size_t{0}), Positions::MRoPELike);+ std::unique_ptr<network> net;+ std::vector<float> summary, raw, rope;+ size_t summary_cap = 0;+ size_t past_len = 0;+ for (size_t q_len : q_lens) {+ SCOPED_TRACE("past_len=" + std::to_string(past_len) + " q_len=" + std::to_string(q_len));+ const auto ref = slice_reference(full, past_len, q_len);+ auto in = dense_inputs_from_reference(ref);+ if (net) {+ // Previous state, summary grown to this call's capacity (zero-filled tail).+ in.block_index_keys_cache.assign(in.summary_cap * d.Di, 0.0f);+ std::copy_n(summary.begin(), summary_cap * d.Di, in.block_index_keys_cache.begin());+ in.raw_state = raw;+ in.rope_state = rope;+ set_dense_inputs(engine, *net, in, Stage::Pair, true);+ } else {+ net = build_dense_network(engine, in, Stage::Pair, true);+ }+ net->execute();+ validate_dense_outputs(*net, in, {ref}, nullptr, atol, rtol);++ auto indexer = net->get_primitive("indexer");+ auto read_state = [&](size_t out) {+ auto values = read_f16(indexer->output_memory_ptr(out));+ values.resize(indexer->get_output_layout(out).count());+ return values;+ };+ summary = read_state(Out::BLOCK_INDEX_KEYS_CACHE);+ raw = read_state(Out::PAST_INCOMPLETE_RAW_K);+ rope = read_state(Out::PAST_INCOMPLETE_ROPE);+ summary_cap = in.summary_cap;+ past_len += q_len;+ }+}++// setenv/unsetenv are POSIX-only; MSVC provides _putenv_s, where an empty value removes the variable.+void set_env_var(const char* name, const char* value) {+#ifdef _WIN32+ _putenv_s(name, value);+#else+ setenv(name, value, 1);+#endif+}++void unset_env_var(const char* name) {+#ifdef _WIN32+ _putenv_s(name, "");+#else+ unsetenv(name);+#endif+}++/// Caps the decode BLOCK_SCORES scratch so the Q2 chunk loop runs several times.+struct scoped_score_budget {+ explicit scoped_score_budget(const char* bytes) {+ set_env_var("OV_GPU_QSA_SCORE_BUDGET_BYTES", bytes);+ }+ ~scoped_score_budget() {+ unset_env_var("OV_GPU_QSA_SCORE_BUDGET_BYTES");+ }+};++const route decode_gqa{IndexerPath::Decode, AttnPath::GqaSplit};+const route dpas_gqa{IndexerPath::Dpas, AttnPath::GqaDpas};+const route dpas_dpas{IndexerPath::Dpas, AttnPath::Dpas};+const route decode_scalar{IndexerPath::Decode, AttnPath::Scalar};+const route decode_split{IndexerPath::Decode, AttnPath::Split};+const route fused_scalar{IndexerPath::Fused, AttnPath::Scalar};++// Decode batches: Q2 score_partition + top-k, Q3 GQA-DPAS (qwen38 dims).+TEST(qsa_ops_gpu_test, qwen38_paged_batch_decode_matches_reference) {+ run_paged_batch_test(qwen38_dims(), {{2100, 1}, {2600, 1}, {3071, 1}}, decode_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_matches_reference) {+ run_dense_batch_test(qwen38_dims(), 3, 3071, 1, decode_gqa, 3e-3f);+}++// Same, with a one-row BLOCK_SCORES budget. The paged scratch row is sized from the page table+// (past_lens stay in GPU memory), i.e. the whole 1948-block pool, so only one row fits per+// chunk: 3 chunks of one sequence each.+TEST(qsa_ops_gpu_test, qwen38_paged_batch_decode_chunked_scores_match_reference) {+ scoped_score_budget budget("1");+ run_paged_batch_test(qwen38_dims(), {{2100, 1}, {2600, 1}, {3071, 1}}, {IndexerPath::Decode, AttnPath::GqaSplit, 3}, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_chunked_scores_match_reference) {+ scoped_score_budget budget("1");+ run_dense_batch_test(qwen38_dims(), 3, 3071, 1, {IndexerPath::Decode, AttnPath::GqaSplit, 3}, 3e-3f);+}++// Budget of exactly two 768-block rows: a full chunk followed by a partial one.+TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_partial_last_chunk_matches_reference) {+ scoped_score_budget budget("6144");+ run_dense_batch_test(qwen38_dims(), 3, 3071, 1, {IndexerPath::Decode, AttnPath::GqaSplit, 2}, 3e-3f);+}++// Mixed batches (decode + prefill sequences in one call): dpas Q2 with qwen38 dims, the+// fused non-dpas Q2 with the toy dims (Di = 16 fails the dpas score gate).+TEST(qsa_ops_gpu_test, qwen38_paged_batch_mixed_matches_reference) {+ run_paged_batch_test(qwen38_dims(), {{2100, 1}, {1990, 64}, {2500, 1}}, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, paged_batch_mixed_fused_score_topk_matches_reference) {+ run_paged_batch_test(split_dims{}, {{20, 1}, {22, 42}, {30, 1}}, fused_scalar, 2e-2f);+}++TEST(qsa_ops_gpu_test, paged_batch_decode_toy_dims_matches_reference) {+ run_paged_batch_test(split_dims{}, {{20, 1}, {37, 1}, {63, 1}}, decode_split, 2e-2f);+}++// Toy dims have no GQA-DPAS, so long decode takes the split + reduce fallback.+TEST(qsa_ops_gpu_test, paged_batch_long_decode_split_fallback_matches_reference) {+ run_paged_batch_test(split_dims{}, {{2100, 1}, {2500, 1}}, decode_split, 2e-2f);+}++TEST(qsa_ops_gpu_test, dense_batch_long_decode_split_fallback_matches_reference) {+ run_dense_batch_test(split_dims{}, 2, 2100, 1, decode_split, 2e-2f);+}++// ---------------------------------------------------------------------------+// Multi-batch dense rows of different key lengths: K/V of shorter rows are left-padded+// (logical key j at S - key_length + j), and rows shorter than L are fresh, left-padded+// sequences whose padding queries select nothing and output zeros. Padding storage is+// NaN, so any read of it fails the comparison.+// ---------------------------------------------------------------------------++TEST(qsa_ops_gpu_test, dense_batch_left_padding_fused_scalar_matches_reference) {+ run_dense_batch_test(split_dims{}, {{20, 44}, {0, 30}, {0, 44}, {0, 3}}, fused_scalar, 2e-2f);+}++TEST(qsa_ops_gpu_test, dense_batch_ragged_decode_scalar_matches_reference) {+ run_dense_batch_test(split_dims{}, {{63, 1}, {20, 1}, {37, 1}}, decode_scalar, 2e-2f);+}++TEST(qsa_ops_gpu_test, dense_batch_ragged_long_decode_split_matches_reference) {+ run_dense_batch_test(split_dims{}, {{2100, 1}, {15, 1}}, decode_split, 2e-2f);+}++// Padding spans whole and partial 16-query tiles of the plain DPAS kernel.+TEST(qsa_ops_gpu_test, dense_batch_left_padding_plain_dpas_matches_reference) {+ run_dense_batch_test(non_gqa_dpas_dims(), {{2100, 33}, {0, 9}, {0, 20}}, dpas_dpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_batch_left_padding_prefill_matches_reference) {+ run_dense_batch_test(qwen38_dims(), {{4032, 64}, {0, 40}, {0, 64}}, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_batch_ragged_decode_matches_reference) {+ run_dense_batch_test(qwen38_dims(), {{3071, 1}, {15, 1}, {2050, 1}}, decode_gqa, 3e-3f);+}++// ---------------------------------------------------------------------------+// Functional state across calls: each call consumes the state the previous call returned,+// including staged keys of an incomplete block that a later call completes.+// ---------------------------------------------------------------------------++TEST(qsa_ops_gpu_test, dense_state_carries_across_calls) {+ run_dense_state_chain_test(split_dims{}, {37, 1, 1, 6, 1, 3, 2}, 2e-2f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_state_carries_across_calls) {+ run_dense_state_chain_test(qwen38_dims(), {2050, 1, 1, 17, 1}, 3e-3f);+}++// Toy Dh = 16 is below the 64-byte DPAS row minimum, so prefill takes the scalar Q3 kernel.+TEST(qsa_ops_gpu_test, paged_pair_matches_reference) {+ run_pair_test(true, split_dims{}, 20, 44, Positions::Sequential, fused_scalar, 2e-2f);+}++TEST(qsa_ops_gpu_test, dense_pair_matches_reference) {+ run_pair_test(false, split_dims{}, 20, 44, Positions::Sequential, fused_scalar, 2e-2f);+}++TEST(qsa_ops_gpu_test, paged_pair_mrope_positions_match_reference) {+ run_pair_test(true, split_dims{}, 22, 42, Positions::MRoPELike, fused_scalar, 2e-2f);+}++TEST(qsa_ops_gpu_test, dense_pair_mrope_positions_match_reference) {+ run_pair_test(false, split_dims{}, 22, 42, Positions::MRoPELike, fused_scalar, 2e-2f);+}++// Qwen3.8-Flash-Next shapes: decode one token over a long history (partial last block+// completed by this call), and a 64-token prefill chunk on top of a cached prefix.+TEST(qsa_ops_gpu_test, qwen38_paged_decode_matches_reference) {+ run_pair_test(true, qwen38_dims(), 8191, 1, Positions::Sequential, decode_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_paged_prefill_matches_reference) {+ run_pair_test(true, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_paged_prefill_mrope_matches_reference) {+ run_pair_test(true, qwen38_dims(), 4030, 66, Positions::MRoPELike, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_decode_matches_reference) {+ run_pair_test(false, qwen38_dims(), 8191, 1, Positions::Sequential, decode_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_prefill_matches_reference) {+ run_pair_test(false, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, 3e-3f);+}++// Prefill rows on both sides of the top-k boundary (510..514 complete blocks vs K = 512):+// one top-k dispatch mixes select-all rows with real selections.+TEST(qsa_ops_gpu_test, qwen38_paged_prefill_crossing_topk_boundary_matches_reference) {+ run_pair_test(true, qwen38_dims(), 2040, 17, Positions::Sequential, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_prefill_crossing_topk_boundary_matches_reference) {+ run_pair_test(false, qwen38_dims(), 2040, 17, Positions::Sequential, dpas_gqa, 3e-3f);+}++// ---------------------------------------------------------------------------+// Short context: at most block_topk complete blocks, so the top-k selects every block+// without reading scores and early tokens attend to the causal tail only.+// ---------------------------------------------------------------------------++TEST(qsa_ops_gpu_test, qwen38_paged_short_prefill_selects_every_block) {+ run_full_selection_pair_test(true, qwen38_dims(), 0, 17, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_short_prefill_selects_every_block) {+ run_full_selection_pair_test(false, qwen38_dims(), 0, 17, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_paged_short_decode_selects_every_block) {+ run_full_selection_pair_test(true, qwen38_dims(), 15, 1, decode_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_short_decode_selects_every_block) {+ run_full_selection_pair_test(false, qwen38_dims(), 15, 1, decode_gqa, 3e-3f);+}++// One decode batch with 4, exactly 512 (score bypass) and 513 (scored) complete blocks.+TEST(qsa_ops_gpu_test, qwen38_paged_batch_decode_around_topk_boundary_matches_reference) {+ run_paged_batch_test(qwen38_dims(), {{15, 1}, {2047, 1}, {2051, 1}}, decode_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_at_topk_boundary_matches_reference) {+ run_dense_batch_test(qwen38_dims(), 2, 2047, 1, decode_gqa, 3e-3f);+}++// Short decode, a long decode and a fresh prefill sequence in one call.+TEST(qsa_ops_gpu_test, qwen38_paged_batch_mixed_short_and_long_matches_reference) {+ run_paged_batch_test(qwen38_dims(), {{15, 1}, {2100, 1}, {0, 17}}, dpas_gqa, 3e-3f);+}++// ---------------------------------------------------------------------------+// Plain (non-GQA) DPAS attention: dims that fail the GQA-DPAS gate but fit plain DPAS.+// q_len = 17 leaves a one-token last query tile; q_len = 16 is exactly one tile.+// ---------------------------------------------------------------------------++TEST(qsa_ops_gpu_test, paged_pair_plain_dpas_attention_matches_reference) {+ run_pair_test(true, non_gqa_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, dense_pair_plain_dpas_attention_matches_reference) {+ run_pair_test(false, non_gqa_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, paged_pair_plain_dpas_four_workers_matches_reference) {+ run_pair_test(true, wide_group_dims(), 2100, 16, Positions::Sequential, dpas_dpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, dense_pair_plain_dpas_four_workers_matches_reference) {+ run_pair_test(false, wide_group_dims(), 2100, 16, Positions::Sequential, dpas_dpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, paged_pair_plain_dpas_one_head_per_tile_matches_reference) {+ run_pair_test(true, mha_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, dense_pair_plain_dpas_one_head_per_tile_matches_reference) {+ run_pair_test(false, mha_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);+}++// Per-sequence query tiles: two single-token decode tiles plus a 16 + 1 prefill.+TEST(qsa_ops_gpu_test, paged_batch_mixed_plain_dpas_attention_matches_reference) {+ run_paged_batch_test(non_gqa_dpas_dims(), {{15, 1}, {2100, 1}, {2040, 17}}, dpas_dpas, 3e-3f);+}++// ---------------------------------------------------------------------------+// Decode split-KV threshold for non-GQA dims. Paged past_lens are GPU-resident, so it always+// splits; dense compares the whole K length (past_len + 1) with 2048.+// ---------------------------------------------------------------------------++TEST(qsa_ops_gpu_test, paged_batch_short_decode_uses_split) {+ run_paged_batch_test(non_gqa_dpas_dims(), {{2047, 1}, {3000, 1}}, decode_split, 3e-3f);+}++TEST(qsa_ops_gpu_test, paged_batch_long_decode_uses_split) {+ run_paged_batch_test(non_gqa_dpas_dims(), {{2048, 1}, {3000, 1}}, decode_split, 3e-3f);+}++TEST(qsa_ops_gpu_test, dense_batch_decode_below_split_threshold_uses_scalar) {+ run_dense_batch_test(non_gqa_dpas_dims(), 2, 2046, 1, decode_scalar, 3e-3f);+}++TEST(qsa_ops_gpu_test, dense_batch_decode_at_split_threshold_uses_split) {+ run_dense_batch_test(non_gqa_dpas_dims(), 2, 2047, 1, decode_split, 3e-3f);+}++// ---------------------------------------------------------------------------+// Dedicated numerical-precision stress tests. `validate_pair()` always reports+// max_abs/max_rel error via a `QSA_PRECISION` log line (grep the test output) and+// asserts finiteness, in addition to the combined absolute+relative bound below.+// ---------------------------------------------------------------------------++TEST(qsa_ops_gpu_test, paged_pair_large_magnitude_inputs_stay_finite_and_accurate) {+ // Activations scaled to +-3 (vs. the usual +-1): dot products over Dh=256/Di=128+ // stay well inside the fp16 range (max 65504), exercising RMSNorm/RoPE/softmax at+ // several times the usual magnitude. The looser bound (vs. the other pair tests) is+ // deliberate: softmax is EXPONENTIALLY sensitive to logit differences, so at a larger+ // scale (bigger typical logits) the same small fp32-vs-double accumulation-order+ // difference between the GPU's DPAS reduction and this reference's summation gets+ // amplified into a visibly larger, but still small, output difference for a minority+ // of elements with closely competing logits -- this is expected floating-point+ // behavior, not a kernel bug, and a tighter bound here would be testing summation+ // order, not correctness.+ run_pair_test(true, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, /*rtol=*/1e-2f, /*atol=*/1e-2f, /*scale=*/3.0f);+}++TEST(qsa_ops_gpu_test, dense_pair_large_magnitude_inputs_stay_finite_and_accurate) {+ run_pair_test(false, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, /*rtol=*/1e-2f, /*atol=*/1e-2f, /*scale=*/3.0f);+}++TEST(qsa_ops_gpu_test, paged_pair_dominant_outlier_component_stays_accurate) {+ // One channel 40x the scale of the rest in both the first query token's index head+ // and the earliest historical index key: stresses RMSNorm's sum-of-squares reduction+ // (a single term dominating the accumulation) rather than merely scaling everything.+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ const auto d = qwen38_dims();+ auto& engine = get_test_engine();+ tests::random_generator rg(GET_SUITE_NAME);+ auto ref = make_split_reference(rg, d, 4032, 64, Positions::Sequential);+ ref.index_query_cur[0] = static_cast<float>(ov::float16(40.0f));+ ref.raw_index_keys_all[0] = static_cast<float>(ov::float16(40.0f));+ ref.summary_memo.clear();+ validate_and_run_pair(true, engine, ref, dpas_gqa, /*atol=*/4e-3f, /*rtol=*/5e-3f);+}++TEST(qsa_ops_gpu_test, dense_pair_dominant_outlier_component_stays_accurate) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ const auto d = qwen38_dims();+ auto& engine = get_test_engine();+ tests::random_generator rg(GET_SUITE_NAME);+ auto ref = make_split_reference(rg, d, 4032, 64, Positions::Sequential);+ ref.index_query_cur[0] = static_cast<float>(ov::float16(40.0f));+ ref.raw_index_keys_all[0] = static_cast<float>(ov::float16(40.0f));+ ref.summary_memo.clear();+ validate_and_run_pair(false, engine, ref, dpas_gqa, /*atol=*/4e-3f, /*rtol=*/5e-3f);+}++// Many more blocks than the prefill cases above: checks that per-block summary error and+// online-softmax accumulation error do not grow with the number of terms summed.+TEST(qsa_ops_gpu_test, qwen38_paged_long_context_accumulation_matches_reference) {+ run_pair_test(true, qwen38_dims(), 8192, 128, Positions::Sequential, dpas_gqa, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_long_context_accumulation_matches_reference) {+ run_pair_test(false, qwen38_dims(), 8192, 128, Positions::Sequential, dpas_gqa, 3e-3f);+}++// ---------------------------------------------------------------------------+// Dynamic shapes: ONE network built with dynamic layouts is executed for several+// (past_len, q_len). Every call must reuse the same shape-agnostic impls (no per-shape+// recompilation), pick its route at runtime and match the reference.+// ---------------------------------------------------------------------------++struct dynamic_step {+ size_t past_len;+ size_t q_len;+ route r;+};++void run_dynamic_pair_test(bool paged, const split_dims& d, const std::vector<dynamic_step>& steps, float rtol, float atol = 2e-3f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ auto& engine = get_test_engine();+ tests::random_generator rg(GET_SUITE_NAME);+ std::unique_ptr<network> net;+ const primitive_impl* indexer_impl = nullptr;+ const primitive_impl* attn_impl = nullptr;+ for (const auto& step : steps) {+ SCOPED_TRACE("past_len=" + std::to_string(step.past_len) + " q_len=" + std::to_string(step.q_len));+ const auto ref = make_split_reference(rg, d, step.past_len, step.q_len, Positions::Sequential);+ dense_inputs dense_in;+ if (paged) {+ const auto in = paged_inputs_from_reference(ref);+ if (net) {+ set_paged_inputs(engine, *net, in, Stage::Pair, true);+ } else {+ net = build_paged_network(engine, in, Stage::Pair, true);+ }+ } else {+ dense_in = dense_inputs_from_reference(ref);+ if (net) {+ set_dense_inputs(engine, *net, dense_in, Stage::Pair, true);+ } else {+ net = build_dense_network(engine, dense_in, Stage::Pair, true);+ }+ }+ auto outputs = net->execute();+ pair_outputs gpu;+ auto attn = read_f16(outputs.at("attn").get_memory());+ attn.resize(net->get_primitive("attn")->get_output_layout().count());+ gpu.attn = paged ? attn : bhld_to_token_major(attn, ref.d, ref.q_len);+ read_pair_outputs(*net, gpu);++ const auto* indexer = net->get_primitive("indexer")->get_impl();+ const auto* attention = net->get_primitive("attn")->get_impl();+ ASSERT_TRUE(indexer->is_dynamic());+ ASSERT_TRUE(attention->is_dynamic());+ if (indexer_impl == nullptr) {+ indexer_impl = indexer;+ attn_impl = attention;+ }+ EXPECT_EQ(indexer, indexer_impl) << "a new shape must reuse the shape-agnostic indexer impl";+ EXPECT_EQ(attention, attn_impl) << "a new shape must reuse the shape-agnostic attention impl";+ if (!paged) {+ validate_dense_outputs(*net, dense_in, {ref}, &step.r, atol, rtol);+ continue;+ }+ expect_route(paged, gpu, step.r);+ validate_pair(ref, gpu, atol, rtol);+ }+}++// Paged past_lens live in GPU memory, so its non-GQA decode always takes split + reduce;+// dense gates the split on the (shape-known) K length instead.+std::vector<dynamic_step> toy_dynamic_steps(bool paged) {+ const route decode = paged ? decode_split : decode_scalar;+ return {{0, 37, fused_scalar}, {37, 1, decode}, {38, 1, decode}, {39, 6, fused_scalar}, {45, 1, decode}};+}+const std::vector<dynamic_step> qwen38_dynamic_steps = {{2100, 17, dpas_gqa}, {2117, 1, decode_gqa}, {2118, 1, decode_gqa}, {40, 9, dpas_gqa}};++TEST(qsa_ops_gpu_test, paged_pair_dynamic_shapes_reuse_one_network) {+ run_dynamic_pair_test(true, split_dims{}, toy_dynamic_steps(true), 2e-3f);+}++TEST(qsa_ops_gpu_test, dense_pair_dynamic_shapes_reuse_one_network) {+ run_dynamic_pair_test(false, split_dims{}, toy_dynamic_steps(false), 2e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_paged_pair_dynamic_shapes_reuse_one_network) {+ run_dynamic_pair_test(true, qwen38_dims(), qwen38_dynamic_steps, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_pair_dynamic_shapes_reuse_one_network) {+ run_dynamic_pair_test(false, qwen38_dims(), qwen38_dynamic_steps, 3e-3f);+}++// ---------------------------------------------------------------------------+// SparseSDPA over K/V buffers whose sequence axis is padded past the logical history,+// as a KVCache producer hands them over: the kernels must step by the allocated pitch.+// ---------------------------------------------------------------------------++/// [1, Hkv, S + pad, D] f16 memory holding token-major `src` ([S, Hkv*D]); padded rows are NaN+/// so any read through the logical (unpadded) pitch poisons the output.+memory::ptr make_seq_padded_f16(engine& eng, const std::vector<float>& src, size_t hkv, size_t s, size_t dim, size_t pad) {+ const layout l{ov::PartialShape{1, I(hkv), I(s), I(dim)}, data_types::f16, format::bfyx, padding({0, 0, 0, 0}, {0, 0, static_cast<int32_t>(pad), 0})};+ std::vector<ov::float16> host(hkv * (s + pad) * dim, ov::float16(std::numeric_limits<float>::quiet_NaN()));+ for (size_t h = 0; h < hkv; h++) {+ for (size_t p = 0; p < s; p++) {+ for (size_t j = 0; j < dim; j++) {+ host[(h * (s + pad) + p) * dim + j] = ov::float16(src[p * hkv * dim + h * dim + j]);+ }+ }+ }+ auto mem = eng.allocate_memory(l, allocation_type::usm_device);+ mem->copy_from(get_test_stream(), host.data(), true);+ return mem;+}++std::vector<std::vector<size_t>> plan_selections(const selection_plan& plan, size_t q_len, size_t topk) {+ std::vector<std::vector<size_t>> out(q_len);+ for (size_t t = 0; t < q_len; t++) {+ for (int32_t i = 0; i < plan.count[t]; i++) {+ out[t].push_back(static_cast<size_t>(plan.sel[t * topk + i]));+ }+ }+ return out;+}++void run_padded_kv_attention_test(const split_dims& d,+ size_t past_len,+ size_t q_len,+ size_t k_pad,+ size_t v_pad,+ AttnPath path,+ float rtol,+ float atol = 2e-3f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ auto& engine = get_test_engine();+ tests::random_generator rg(GET_SUITE_NAME);+ const auto ref = make_split_reference(rg, d, past_len, q_len, Positions::Sequential);+ const auto total = ref.total_len();+ const auto plan = synthetic_plan(d, past_len, q_len);+ const auto in = dense_inputs_from_reference(ref);++ auto key = make_seq_padded_f16(engine, ref.key_all, d.Hkv, total, d.Dh, k_pad);+ auto value = make_seq_padded_f16(engine, ref.value_all, d.Hkv, total, d.Dv, v_pad);++ ov::intel_gpu::op::SparseSDPA::Config cfg;+ cfg.num_heads = d.Hq;+ cfg.num_kv_heads = d.Hkv;+ cfg.num_selection_heads = 1;+ cfg.k_head_size = d.Dh;+ cfg.v_head_size = d.Dv;+ cfg.key_block_size = d.r;+ cfg.query_block_size = 1;+ cfg.causal = true;++ topology topo;+ topo.add(input_layout("query", layout{{1, I(d.Hq), I(q_len), I(d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("key", key->get_layout()));+ topo.add(input_layout("value", value->get_layout()));+ topo.add(data("sel", make_i32(engine, {1, 1, I(q_len), I(d.block_topk)}, plan.sel)));+ topo.add(data("count", make_i32(engine, {1, 1, I(q_len)}, plan.count)));+ topo.add(data("key_length", make_i32(engine, {1}, {static_cast<int32_t>(total)})));+ topo.add(sparse_sdpa("attn",+ {input_info("query"), input_info("key"), input_info("value"), input_info("sel"), input_info("count"), input_info("key_length")},+ cfg,+ 1.0f / std::sqrt(static_cast<float>(d.Dh))));+ network net(engine, topo, make_config(engine));+ net.set_input_data("query", make_f16(engine, {1, I(d.Hq), I(q_len), I(d.Dh)}, in.query_bhld));+ net.set_input_data("key", key);+ net.set_input_data("value", value);+ auto outputs = net.execute();++ const auto* const attn_params = net.get_primitive("attn")->get_impl_params();+ ASSERT_TRUE(static_cast<bool>(attn_params->get_input_layout(SparseSDPAIn::KEY).data_padding)) << "SparseSDPA must see the padded key buffer";+ EXPECT_EQ(executed_kernels(net, "attn"), expected_attention_kernels(false, resolve_route(route{IndexerPath::Decode, path}, false, total)));+ const auto gpu = bhld_to_token_major(read_f16(outputs.at("attn").get_memory()), d, q_len);+ const auto expected = ref.attention(plan_selections(plan, q_len, d.block_topk));+ const auto stats = compute_error_stats(gpu, expected);+ print_error_stats("padded_kv_attention", stats);+ ASSERT_EQ(stats.non_finite, 0u) << "a padded K/V row was read: the kernel ignored the allocated sequence pitch";+ size_t mismatches = 0;+ for (size_t i = 0; i < expected.size(); i++) {+ if (std::fabs(gpu[i] - expected[i]) > atol + rtol * std::fabs(expected[i]) && mismatches++ < 8) {+ ADD_FAILURE() << "attn[" << i << "] gpu=" << gpu[i] << " ref=" << expected[i];+ }+ }+ EXPECT_EQ(mismatches, 0u);+}++/// Two KV heads, so a wrong per-head pitch lands in another head's (or padded) rows.+split_dims two_kv_head_dims() {+ split_dims d;+ d.Hq = 4;+ d.Hkv = 2;+ return d;+}++TEST(qsa_ops_gpu_test, dense_attention_scalar_reads_padded_kv) {+ run_padded_kv_attention_test(two_kv_head_dims(), 37, 5, 11, 7, AttnPath::Scalar, 2e-3f);+}++TEST(qsa_ops_gpu_test, dense_attention_split_reads_padded_kv) {+ run_padded_kv_attention_test(two_kv_head_dims(), 2050, 1, 128, 64, AttnPath::Split, 2e-3f);+}++TEST(qsa_ops_gpu_test, dense_attention_plain_dpas_reads_padded_kv) {+ auto d = non_gqa_dpas_dims();+ d.Hq = 8;+ d.Hkv = 2;+ run_padded_kv_attention_test(d, 37, 20, 13, 5, AttnPath::Dpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_attention_gqa_dpas_reads_padded_kv) {+ run_padded_kv_attention_test(qwen38_dims(), 37, 5, 9, 17, AttnPath::GqaDpas, 3e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_dense_attention_gqa_split_reads_padded_kv) {+ run_padded_kv_attention_test(qwen38_dims(), 40, 1, 9, 17, AttnPath::GqaSplit, 3e-3f);+}++// ---------------------------------------------------------------------------+// End to end through ov::Core: SparseSDPA reads K/V straight from KVCache nodes+// (ReadValue -> Concat -> Assign), one compiled model, several infer() calls with growing+// history. KVCache pre-allocates ahead on the sequence axis, i.e. hands over padded K/V.+// ---------------------------------------------------------------------------++void run_sparse_sdpa_kv_cache_model_test(const split_dims& d, const std::vector<size_t>& q_lens, float rtol, float atol = 2e-3f) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ ov::Core core;+ const auto f16 = ov::element::f16;+ auto query = std::make_shared<ov::op::v0::Parameter>(f16, ov::PartialShape{1, I(d.Hq), -1, I(d.Dh)});+ auto key_new = std::make_shared<ov::op::v0::Parameter>(f16, ov::PartialShape{1, I(d.Hkv), -1, I(d.Dh)});+ auto value_new = std::make_shared<ov::op::v0::Parameter>(f16, ov::PartialShape{1, I(d.Hkv), -1, I(d.Dv)});+ auto sel = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, -1, I(d.block_topk)});+ auto count = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, -1});+ auto key_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1});++ ov::SinkVector sinks;+ auto kv_cache = [&](const std::shared_ptr<ov::op::v0::Parameter>& fresh, size_t head_size, const std::string& name) {+ auto var = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{ov::PartialShape{1, I(d.Hkv), -1, I(head_size)}, f16, name});+ auto past = std::make_shared<ov::op::v6::ReadValue>(var);+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{past, fresh}, 2);+ sinks.push_back(std::make_shared<ov::op::v6::Assign>(concat, var));+ return concat;+ };++ ov::intel_gpu::op::SparseSDPA::Config cfg;+ cfg.num_heads = d.Hq;+ cfg.num_kv_heads = d.Hkv;+ cfg.num_selection_heads = 1;+ cfg.k_head_size = d.Dh;+ cfg.v_head_size = d.Dv;+ cfg.key_block_size = d.r;+ cfg.query_block_size = 1;+ cfg.causal = true;+ auto attn = std::make_shared<ov::intel_gpu::op::SparseSDPA>(+ ov::OutputVector{query, kv_cache(key_new, d.Dh, "k_cache"), kv_cache(value_new, d.Dv, "v_cache"), sel, count, key_length},+ cfg);+ auto model = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(attn)},+ sinks,+ ov::ParameterVector{query, key_new, value_new, sel, count, key_length});+ auto compiled = core.compile_model(model, "GPU", ov::hint::inference_precision(f16));+ auto request = compiled.create_infer_request();++ tests::random_generator rg(GET_SUITE_NAME);+ split_reference ref;+ ref.d = d;+ for (size_t q_len : q_lens) {+ SCOPED_TRACE("past_len=" + std::to_string(ref.total_len()) + " q_len=" + std::to_string(q_len));+ ref.past_len = ref.total_len();+ ref.q_len = q_len;+ ref.query_cur = random_vec(rg, q_len * d.Hq * d.Dh, 1.0f);+ auto key_cur = random_vec(rg, q_len * d.Hkv * d.Dh, 1.0f);+ auto value_cur = random_vec(rg, q_len * d.Hkv * d.Dv, 1.0f);+ for (auto* v : {&ref.query_cur, &key_cur, &value_cur}) {+ quantize_f16(*v);+ }+ append(ref.key_all, key_cur);+ append(ref.value_all, value_cur);+ const auto plan = synthetic_plan(d, ref.past_len, q_len);++ // Token-major [L, H*D] -> [1, H, L, D].+ auto to_bhld = [q_len](const std::vector<float>& src, size_t heads, size_t dim) {+ ov::Tensor t(ov::element::f16, ov::Shape{1, heads, q_len, dim});+ auto* dst = t.data<ov::float16>();+ for (size_t l = 0; l < q_len; l++) {+ for (size_t h = 0; h < heads; h++) {+ for (size_t j = 0; j < dim; j++) {+ dst[(h * q_len + l) * dim + j] = ov::float16(src[(l * heads + h) * dim + j]);+ }+ }+ }+ return t;+ };+ request.set_tensor(query, to_bhld(ref.query_cur, d.Hq, d.Dh));+ request.set_tensor(key_new, to_bhld(key_cur, d.Hkv, d.Dh));+ request.set_tensor(value_new, to_bhld(value_cur, d.Hkv, d.Dv));+ ov::Tensor sel_t(ov::element::i32, ov::Shape{1, 1, q_len, d.block_topk});+ std::copy(plan.sel.begin(), plan.sel.end(), sel_t.data<int32_t>());+ ov::Tensor count_t(ov::element::i32, ov::Shape{1, 1, q_len});+ std::copy(plan.count.begin(), plan.count.end(), count_t.data<int32_t>());+ request.set_tensor(sel, sel_t);+ request.set_tensor(count, count_t);+ ov::Tensor key_length_t(ov::element::i32, ov::Shape{1});+ key_length_t.data<int32_t>()[0] = static_cast<int32_t>(ref.total_len());+ request.set_tensor(key_length, key_length_t);+ request.infer();++ const auto out = request.get_output_tensor(0);+ ASSERT_EQ(out.get_shape(), (ov::Shape{1, d.Hq, q_len, d.Dv}));+ const auto* out_data = out.data<ov::float16>();+ const auto gpu = bhld_to_token_major(std::vector<float>(out_data, out_data + out.get_size()), d, q_len);+ const auto expected = ref.attention(plan_selections(plan, q_len, d.block_topk));+ const auto stats = compute_error_stats(gpu, expected);+ print_error_stats("kv_cache_model_attention", stats);+ ASSERT_EQ(stats.non_finite, 0u);+ size_t mismatches = 0;+ for (size_t i = 0; i < expected.size(); i++) {+ if (std::fabs(gpu[i] - expected[i]) > atol + rtol * std::fabs(expected[i]) && mismatches++ < 8) {+ ADD_FAILURE() << "attn[" << i << "] gpu=" << gpu[i] << " ref=" << expected[i];+ }+ }+ ASSERT_EQ(mismatches, 0u);+ }+}++TEST(qsa_ops_gpu_test, sparse_sdpa_reads_kv_cache_across_infer_calls) {+ run_sparse_sdpa_kv_cache_model_test(two_kv_head_dims(), {37, 1, 1, 6, 1, 2003, 1, 1}, 2e-3f);+}++TEST(qsa_ops_gpu_test, qwen38_sparse_sdpa_reads_kv_cache_across_infer_calls) {+ run_sparse_sdpa_kv_cache_model_test(qwen38_dims(), {37, 1, 1, 9, 1}, 3e-3f);+}++// ---------------------------------------------------------------------------+// Host-level op validation (no GPU required)+// ---------------------------------------------------------------------------++std::shared_ptr<ov::op::v0::Parameter> make_param(const ov::PartialShape& shape, ov::element::Type_t et = ov::element::f16) {+ return std::make_shared<ov::op::v0::Parameter>(et, shape);+}++ov::OutputVector make_paged_indexer_args(const split_dims& d, size_t num_pages, size_t summaries_per_page) {+ return {make_param({-1, I(d.Hiq * d.Di)}),+ make_param({-1, I(d.Di)}),+ make_param({-1, I(d.rotary)}),+ make_param({-1, I(d.rotary)}),+ make_param({I(d.Di)}),+ make_param({I(d.Di)}),+ make_param({-1}, ov::element::i32),+ make_param({-1}, ov::element::i32),+ make_param({-1}, ov::element::i32),+ make_param({-1}, ov::element::i32),+ make_param({I(num_pages), 1, I(d.page_size), I(d.Di)}),+ make_param({I(num_pages), I(summaries_per_page), I(2 * d.rotary)}),+ make_param({I(num_pages), 1, I(summaries_per_page), I(d.Di)})};+}++ov::OutputVector make_dense_indexer_args(const split_dims& d, size_t h_ik = 1) {+ return {make_param({1, -1, I(d.Hiq), I(d.Di)}),+ make_param({1, -1, I(h_ik), I(d.Di)}),+ make_param({1, -1, I(d.rotary)}),+ make_param({1, -1, I(d.rotary)}),+ make_param({1}, ov::element::i32),+ make_param({I(d.Di)}),+ make_param({I(d.Di)}),+ make_param({1, I(h_ik), -1, I(d.Di)}),+ make_param({1, I(h_ik), I(d.r - 1), I(d.Di)}),+ make_param({1, I(2 * d.rotary)})};+}++ov::intel_gpu::op::PagedQSAIndexer::Config make_paged_indexer_config(const split_dims& d) {+ ov::intel_gpu::op::PagedQSAIndexer::Config c;+ c.key_block_size = d.r;+ c.block_topk = d.block_topk;+ c.num_selection_heads = 1;+ c.indexer_rotary_dim = d.rotary;+ c.indexer_head_dim = d.Di;+ c.epsilon = d.eps;+ c.scale = 1.0f / std::sqrt(static_cast<float>(d.Di));+ return c;+}++ov::intel_gpu::op::QSAIndexer::Config make_dense_indexer_config(const split_dims& d) {+ ov::intel_gpu::op::QSAIndexer::Config c;+ c.key_block_size = d.r;+ c.block_topk = d.block_topk;+ c.num_selection_heads = 1;+ c.indexer_rotary_dim = d.rotary;+ c.indexer_head_dim = d.Di;+ c.epsilon = d.eps;+ c.scale = 1.0f / std::sqrt(static_cast<float>(d.Di));+ return c;+}++TEST(qsa_ops_gpu_test, paged_qsa_indexer_config_validation_rejects_illegal_attributes) {+ std::string reason;+ split_dims d;+ auto base = make_paged_indexer_config(d);+ ASSERT_TRUE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(base, reason)) << reason;++ auto c = base;+ c.key_block_size = 0;+ ASSERT_FALSE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(c, reason));++ c = base;+ c.block_topk = 0;+ ASSERT_FALSE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(c, reason));++ c = base;+ c.indexer_rotary_dim = c.indexer_head_dim + 2;+ ASSERT_FALSE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(c, reason));++ c = base;+ c.scale = -1.0f;+ ASSERT_FALSE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(c, reason));++ // scale == 0 selects the 1 / sqrt(indexer_head_dim) default.+ c = base;+ c.scale = 0.0f;+ ASSERT_TRUE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(c, reason)) << reason;+ EXPECT_FLOAT_EQ(ov::intel_gpu::op::PagedQSAIndexer::effective_scale(c), 1.0f / std::sqrt(static_cast<float>(d.Di)));+}++TEST(qsa_ops_gpu_test, paged_qsa_indexer_rejects_page_size_not_divisible_by_key_block_size) {+ split_dims d;+ using In = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;+ auto args = make_paged_indexer_args(d, 8, d.page_size / d.r);+ args[In::INDEX_KEY_CACHE] = make_param({8, 1, I(d.page_size + 1), I(d.Di)}); // page_size is read from this cache+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception);+}++TEST(qsa_ops_gpu_test, paged_qsa_indexer_output_shapes_and_clone) {+ split_dims d;+ const size_t num_pages = 8;+ const size_t summaries_per_page = d.page_size / d.r;+ auto node = std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(make_paged_indexer_args(d, num_pages, summaries_per_page), make_paged_indexer_config(d));++ ASSERT_EQ(node->get_output_size(), 2u);+ const auto& selected_block_indices_ps = node->get_output_partial_shape(0);+ ASSERT_EQ(selected_block_indices_ps.size(), 3u);+ ASSERT_EQ(selected_block_indices_ps[1].get_length(), 1); // num_selection_heads == 1+ ASSERT_EQ(selected_block_indices_ps[2].get_length(), I(d.block_topk));+ ASSERT_EQ(node->get_output_element_type(0), ov::element::i32);+ ASSERT_EQ(node->get_output_element_type(1), ov::element::i32);++ auto clone = node->clone_with_new_inputs(node->input_values());+ ASSERT_NE(std::dynamic_pointer_cast<ov::intel_gpu::op::PagedQSAIndexer>(clone), nullptr)+ << "clone_with_new_inputs() must not silently downgrade to the base ov::op::internal::PagedQSAIndexer type";+}++TEST(qsa_ops_gpu_test, paged_qsa_indexer_resolves_default_scale) {+ split_dims d;+ auto cfg = make_paged_indexer_config(d);+ cfg.scale = 0.0f;+ auto node = std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(make_paged_indexer_args(d, 8, d.page_size / d.r), cfg);+ EXPECT_FLOAT_EQ(node->get_config().scale, 0.0f); // sentinel stays in the IR; consumers resolve it+ EXPECT_FLOAT_EQ(ov::intel_gpu::op::PagedQSAIndexer::effective_scale(node->get_config()), 1.0f / std::sqrt(static_cast<float>(d.Di)));+}++TEST(qsa_ops_gpu_test, paged_qsa_indexer_rejects_wrong_input_count) {+ split_dims d;+ auto args = make_paged_indexer_args(d, 8, d.page_size / d.r);+ args.pop_back();+ ASSERT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception);+}++TEST(qsa_ops_gpu_test, paged_qsa_indexer_rejects_bad_rope_shapes) {+ split_dims d;+ using In = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;+ const size_t spp = d.page_size / d.r;+ auto args = make_paged_indexer_args(d, 8, spp);+ args[In::ROPE_COS] = make_param({-1, I(d.rotary / 2)}); // a half-width row, not rotary+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception) << "rope_cos width";++ args = make_paged_indexer_args(d, 8, spp);+ args[In::ROPE_SIN] = make_param({3, I(d.rotary)});+ args[In::INDEX_QUERY] = make_param({4, I(d.Hiq * d.Di)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception) << "rope_sin tokens";++ args = make_paged_indexer_args(d, 8, spp);+ args[In::INDEX_BLOCK_ROPE_CACHE] = make_param({8, I(spp), I(d.rotary)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception) << "rope cache row width";++ args = make_paged_indexer_args(d, 8, spp);+ args[In::INDEX_BLOCK_ROPE_CACHE] = make_param({9, I(spp), I(2 * d.rotary)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception) << "rope cache num_blocks";++ args = make_paged_indexer_args(d, 8, spp);+ args[In::INDEX_BLOCK_ROPE_CACHE] = make_param({8, I(spp), I(2 * d.rotary)}, ov::element::f32);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception) << "rope cache type";+}++TEST(qsa_ops_gpu_test, paged_qsa_indexer_requires_i32_integer_inputs) {+ split_dims d;+ using In = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;+ for (size_t idx : {In::BLOCK_INDICES, In::BLOCK_INDICES_BEGINS, In::SUBSEQUENCE_BEGINS, In::PAST_LENS}) {+ auto args = make_paged_indexer_args(d, 8, d.page_size / d.r);+ args[idx] = make_param({-1}, ov::element::i64);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::PagedQSAIndexer>(args, make_paged_indexer_config(d)), ov::Exception) << "input " << idx;+ }+}++TEST(qsa_ops_gpu_test, dense_qsa_indexer_validates_state_rope_and_key_length) {+ split_dims d;+ using In = ov::intel_gpu::op::QSAIndexer::InputIdx;+ using Out = ov::intel_gpu::op::QSAIndexer::OutputIdx;+ std::shared_ptr<ov::intel_gpu::op::QSAIndexer> node;+ ASSERT_NO_THROW(node = std::make_shared<ov::intel_gpu::op::QSAIndexer>(make_dense_indexer_args(d), make_dense_indexer_config(d)));+ // Outputs: selection plus the updated state, shaped and typed like the state inputs.+ ASSERT_EQ(node->get_output_size(), Out::COUNT);+ EXPECT_EQ(node->get_output_partial_shape(Out::SELECTED_BLOCK_INDICES), (ov::PartialShape{1, 1, -1, I(d.block_topk)}));+ for (auto [out, in] : {std::pair{Out::BLOCK_INDEX_KEYS_CACHE, In::BLOCK_INDEX_KEYS_CACHE},+ std::pair{Out::PAST_INCOMPLETE_RAW_K, In::PAST_INCOMPLETE_RAW_K},+ std::pair{Out::PAST_INCOMPLETE_ROPE, In::PAST_INCOMPLETE_ROPE}}) {+ EXPECT_EQ(node->get_output_partial_shape(out), node->get_input_partial_shape(in));+ EXPECT_EQ(node->get_output_element_type(out), ov::element::f16);+ }++ auto args = make_dense_indexer_args(d);+ args[In::ROPE_COS] = make_param({1, -1, I(d.rotary)}, ov::element::f32);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "rope_cos type";++ args = make_dense_indexer_args(d);+ args[In::ROPE_COS] = make_param({1, -1, I(d.rotary / 2)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "half-width rope_cos";++ args = make_dense_indexer_args(d);+ args[In::ROPE_COS] = make_param({-1, I(d.rotary)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "rank-2 rope_cos";++ args = make_dense_indexer_args(d);+ args[In::ROPE_SIN] = make_param({2, -1, I(d.rotary)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "batch mismatch";++ args = make_dense_indexer_args(d);+ args[In::KEY_LENGTH] = make_param({1}, ov::element::i64);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "i64 key_length";++ args = make_dense_indexer_args(d);+ args[In::PAST_INCOMPLETE_RAW_K] = make_param({1, 1, I(d.r), I(d.Di)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "r raw-key slots";++ args = make_dense_indexer_args(d);+ args[In::PAST_INCOMPLETE_ROPE] = make_param({1, I(d.rotary)});+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "non-interleaved rope state";++ args = make_dense_indexer_args(d);+ args[In::BLOCK_INDEX_KEYS_CACHE] = make_param({1, 1, -1, I(d.Di)}, ov::element::f32);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "summary type";+}++cldnn::sparse_pa::Config make_sparse_pa_config(const split_dims& d) {+ cldnn::sparse_pa::Config c;+ c.num_heads = d.Hq;+ c.num_kv_heads = d.Hkv;+ c.num_selection_heads = 1;+ c.k_head_size = d.Dh;+ c.v_head_size = d.Dv;+ c.key_block_size = d.r;+ c.query_block_size = 1;+ c.causal = true;+ return c;+}++TEST(qsa_ops_gpu_test, sparse_pa_config_validation_rejects_illegal_attributes) {+ std::string reason;+ split_dims d;+ auto base = make_sparse_pa_config(d);+ ASSERT_TRUE(cldnn::sparse_pa::validate_config(base, reason)) << reason;++ auto c = base;+ c.num_kv_heads = 2;+ c.num_heads = 3; // not a multiple of num_kv_heads+ ASSERT_FALSE(cldnn::sparse_pa::validate_config(c, reason));++ c = base;+ c.num_selection_heads = 3; // not 1, num_kv_heads, or num_heads+ ASSERT_FALSE(cldnn::sparse_pa::validate_config(c, reason));++ c = base;+ c.query_block_size = 2; // not implemented in this pass+ ASSERT_FALSE(cldnn::sparse_pa::validate_config(c, reason));+}++ov::intel_gpu::op::SparseSDPA::Config make_sparse_sdpa_config(const split_dims& d) {+ ov::intel_gpu::op::SparseSDPA::Config c;+ c.num_heads = d.Hq;+ c.num_kv_heads = d.Hkv;+ c.num_selection_heads = 1;+ c.k_head_size = d.Dh;+ c.v_head_size = d.Dv;+ c.key_block_size = d.r;+ c.query_block_size = 1;+ c.causal = true;+ return c;+}++TEST(qsa_ops_gpu_test, sparse_sdpa_config_validation_rejects_illegal_attributes) {+ std::string reason;+ split_dims d;+ auto base = make_sparse_sdpa_config(d);+ ASSERT_TRUE(ov::intel_gpu::op::SparseSDPA::validate_config(base, reason)) << reason;++ auto c = base;+ c.num_selection_heads = 3;+ ASSERT_FALSE(ov::intel_gpu::op::SparseSDPA::validate_config(c, reason));++ c = base;+ c.query_block_size = 2;+ ASSERT_FALSE(ov::intel_gpu::op::SparseSDPA::validate_config(c, reason));+}++ov::OutputVector make_sparse_sdpa_args(const split_dims& d, ov::element::Type_t et = ov::element::f16) {+ return {make_param({1, I(d.Hq), -1, I(d.Dh)}, et),+ make_param({1, I(d.Hkv), -1, I(d.Dh)}, et),+ make_param({1, I(d.Hkv), -1, I(d.Dv)}, et),+ make_param({1, 1, -1, I(d.block_topk)}, ov::element::i32),+ make_param({1, 1, -1}, ov::element::i32),+ make_param({1}, ov::element::i32)};+}++TEST(qsa_ops_gpu_test, sparse_sdpa_output_shape_and_optional_inputs) {+ split_dims d;+ auto args = make_sparse_sdpa_args(d);+ auto node = std::make_shared<ov::intel_gpu::op::SparseSDPA>(args, make_sparse_sdpa_config(d));+ ASSERT_FALSE(node->has_scale_input());+ ASSERT_FALSE(node->has_sinks());++ const auto& out_ps = node->get_output_partial_shape(0);+ ASSERT_EQ(out_ps.size(), 4u);+ ASSERT_EQ(out_ps[1].get_length(), I(d.Hq));+ ASSERT_EQ(out_ps[3].get_length(), I(d.Dv));++ args.push_back(make_param({})); // scale+ auto node_with_scale = std::make_shared<ov::intel_gpu::op::SparseSDPA>(args, make_sparse_sdpa_config(d));+ ASSERT_TRUE(node_with_scale->has_scale_input());+ ASSERT_FALSE(node_with_scale->has_sinks());++ args.push_back(make_param({I(d.Hq)})); // sinks+ auto node_with_sinks = std::make_shared<ov::intel_gpu::op::SparseSDPA>(args, make_sparse_sdpa_config(d));+ ASSERT_TRUE(node_with_sinks->has_sinks());++ auto clone = node->clone_with_new_inputs(node->input_values());+ ASSERT_NE(std::dynamic_pointer_cast<ov::intel_gpu::op::SparseSDPA>(clone), nullptr);++ args = make_sparse_sdpa_args(d);+ args[SparseSDPAIn::SELECTED_BLOCK_INDICES] = make_param({1, 1, -1, I(d.block_topk)}, ov::element::i64);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::SparseSDPA>(args, make_sparse_sdpa_config(d)), ov::Exception);++ args = make_sparse_sdpa_args(d);+ args[SparseSDPAIn::KEY_LENGTH] = make_param({1}, ov::element::i64);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::SparseSDPA>(args, make_sparse_sdpa_config(d)), ov::Exception) << "i64 key_length";++ args = make_sparse_sdpa_args(d);+ args[SparseSDPAIn::KEY_LENGTH] = make_param({2}, ov::element::i32);+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::SparseSDPA>(args, make_sparse_sdpa_config(d)), ov::Exception) << "key_length batch";++ args = make_sparse_sdpa_args(d);+ args.pop_back();+ EXPECT_THROW((void)std::make_shared<ov::intel_gpu::op::SparseSDPA>(args, make_sparse_sdpa_config(d)), ov::Exception) << "key_length is required";+}++// ---------------------------------------------------------------------------+// Plugin-level rejection of configurations outside the v1 GPU scope+// (H_ik == 1, num_selection_heads == 1, f16 data). Goes through ov::Core so the ProgramBuilder+// factories are exercised; no device support is needed since lowering fails first.+// ---------------------------------------------------------------------------++bool gpu_in_core(ov::Core& core) {+ std::vector<std::string> devices;+ try {+ devices = core.get_available_devices();+ } catch (...) {+ }+ return std::any_of(devices.begin(), devices.end(), [](const std::string& dev) {+ return dev.rfind("GPU", 0) == 0;+ });+}++void expect_compile_error(ov::Core& core, const std::shared_ptr<ov::Node>& op, const ov::AnyMap& props, const std::string& needle) {+ ov::ParameterVector params;+ for (const auto& input : op->input_values()) {+ if (auto p = ov::as_type_ptr<ov::op::v0::Parameter>(input.get_node_shared_ptr())) {+ params.push_back(p);+ }+ }+ ov::ResultVector results;+ for (const auto& output : op->outputs()) {+ results.push_back(std::make_shared<ov::op::v0::Result>(output));+ }+ auto model = std::make_shared<ov::Model>(results, params);+ try {+ core.compile_model(model, "GPU", props);+ ADD_FAILURE() << "compile_model unexpectedly succeeded; expected an error containing '" << needle << "'";+ } catch (const ov::Exception& e) {+ EXPECT_NE(std::string(e.what()).find(needle), std::string::npos) << e.what();+ }+}++TEST(qsa_ops_gpu_test, plugin_rejects_unsupported_indexer_heads_and_precision) {+ ov::Core core;+ if (!gpu_in_core(core)) {+ GTEST_SKIP() << "GPU plugin is not available in ov::Core";+ }+ split_dims d;+ d.Hiq = 2;++ auto make_dense = [&](size_t h_ik, size_t num_selection_heads) {+ auto args = make_dense_indexer_args(d, h_ik);+ args[DenseIdxIn::Q_NORM_WEIGHT] = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{d.Di}, std::vector<float>(d.Di, 1.0f));+ args[DenseIdxIn::K_NORM_WEIGHT] = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{d.Di}, std::vector<float>(d.Di, 1.0f));+ auto cfg = make_dense_indexer_config(d);+ cfg.num_selection_heads = num_selection_heads;+ return std::make_shared<ov::intel_gpu::op::QSAIndexer>(args, cfg);+ };+ expect_compile_error(core, make_dense(2, 1), {}, "only H_ik == 1 is supported");+ expect_compile_error(core, make_dense(2, 2), {}, "only num_selection_heads == 1 is supported");++ auto sdpa = std::make_shared<ov::intel_gpu::op::SparseSDPA>(make_sparse_sdpa_args(d, ov::element::f32), make_sparse_sdpa_config(d));+ expect_compile_error(core, sdpa, {ov::hint::inference_precision(ov::element::f32)}, "must be f16");++ auto sink_args = make_sparse_sdpa_args(d);+ sink_args.push_back(ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {0.25f}));+ sink_args.push_back(make_param({I(d.Hq)}));+ auto sdpa_sinks = std::make_shared<ov::intel_gpu::op::SparseSDPA>(sink_args, make_sparse_sdpa_config(d));+ expect_compile_error(core, sdpa_sinks, {}, "sinks input is not supported");+}++} // namespace++// ---------------------------------------------------------------------------+// Performance (DISABLED_ by default). Wall-clock per synchronous execute(), which+// includes host dispatch and plan uploads, with Qwen3.8-Flash-Next shapes. The traffic+// estimate assumes no cache reuse across query tokens, so prefill GB/s is an upper bound.+// ---------------------------------------------------------------------------++namespace {++struct perf_case {+ bool paged;+ size_t past_len;+ size_t q_len;+ bool no_dpas_score = false; // Di=16 fails the Q2 dpas gate, forcing the non-dpas Q2 path+};++struct perf_timing {+ double avg_ms = 0.0;+ double min_ms = 0.0;+};++perf_timing time_network(network& net, const primitive_id& out_id, int warmup, int iterations) {+ auto run_once = [&]() {+ auto outputs = net.execute();+ outputs.at(out_id).get_memory();+ net.get_stream().finish();+ };+ for (int i = 0; i < warmup; i++) {+ run_once();+ }+ perf_timing t;+ t.min_ms = std::numeric_limits<double>::max();+ double total = 0.0;+ for (int i = 0; i < iterations; i++) {+ const auto start = std::chrono::steady_clock::now();+ run_once();+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();+ total += ms;+ t.min_ms = std::min(t.min_ms, ms);+ }+ t.avg_ms = total / iterations;+ return t;+}++double indexer_bytes(const split_dims& d, size_t past_len, size_t q_len) {+ const double n_blocks = static_cast<double>((past_len + q_len) / d.r);+ const double tiles = static_cast<double>((q_len + 15) / 16);+ return q_len * (d.Hiq + 1) * d.Di * 2.0 + tiles * n_blocks * d.Di * 2.0 + q_len * n_blocks * 4.0 * 2.0 + q_len * d.block_topk * 4.0;+}++double attention_bytes(const split_dims& d, size_t past_len, size_t q_len) {+ double bytes = q_len * d.Hq * (d.Dh + d.Dv) * 2.0;+ for (size_t t = 0; t < q_len; t++) {+ const size_t n_complete = (past_len + t + 1) / d.r;+ const double tokens = static_cast<double>(std::min(d.block_topk, n_complete) * d.r + d.r);+ bytes += tokens * d.Hkv * (d.Dh + d.Dv) * 2.0;+ }+ return bytes;+}++void print_perf(const char* op, const perf_case& c, const perf_timing& t, double bytes) {+ const double gbps = bytes / (t.avg_ms * 1e-3) / 1e9;+ std::cout << "QSA_PERF " << std::left << std::setw(16) << op << " mode=" << std::setw(7) << (c.q_len == 1 ? "decode" : "prefill") << " ctx=" << std::setw(6)+ << (c.past_len + c.q_len) << " q=" << std::setw(5) << c.q_len << std::right << std::fixed << std::setprecision(3) << " avg_ms=" << std::setw(8)+ << t.avg_ms << " min_ms=" << std::setw(8) << t.min_ms << std::setprecision(1) << " est_MB=" << std::setw(7) << bytes / 1e6+ << " eff_GB/s=" << std::setw(6) << gbps << " (BMG peak 456)" << std::endl;+}++class qsa_ops_perf : public ::testing::TestWithParam<perf_case> {};++TEST_P(qsa_ops_perf, qwen38) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ const auto c = GetParam();+ auto d = qwen38_dims();+ if (c.no_dpas_score) {+ d.Di = 16;+ d.rotary = 8;+ }+ auto& engine = get_test_engine();+ // Microsecond kernels never ramp the GPU clock in 3 warmups: QSA_PERF_WARMUP / QSA_PERF_ITERS settle it.+ auto env_int = [](const char* name, int fallback) {+ const char* v = std::getenv(name);+ return v ? static_cast<int>(std::strtol(v, nullptr, 10)) : fallback;+ };+ const int warmup = env_int("QSA_PERF_WARMUP", 3);+ const int iterations = env_int("QSA_PERF_ITERS", 20);++ const char* indexer_name = c.paged ? "PagedQSAIndexer" : "QSAIndexer";+ const char* attention_name = c.paged ? "SparsePA" : "SparseSDPA";+ const double idx_bytes = indexer_bytes(d, c.past_len, c.q_len);+ const double attn_bytes = attention_bytes(d, c.past_len, c.q_len);++ std::unique_ptr<network> idx_net, attn_net, pair_net;+ if (c.paged) {+ const auto in = paged_inputs_synthetic(d, c.past_len, c.q_len);+ idx_net = build_paged_network(engine, in, Stage::IndexerOnly);+ attn_net = build_paged_network(engine, in, Stage::AttentionOnly);+ pair_net = build_paged_network(engine, in, Stage::Pair);+ } else {+ const auto in = dense_inputs_synthetic(d, c.past_len, c.q_len);+ idx_net = build_dense_network(engine, in, Stage::IndexerOnly);+ attn_net = build_dense_network(engine, in, Stage::AttentionOnly);+ pair_net = build_dense_network(engine, in, Stage::Pair);+ }+ print_perf(indexer_name, c, time_network(*idx_net, "indexer", warmup, iterations), idx_bytes);+ print_perf(attention_name, c, time_network(*attn_net, "attn", warmup, iterations), attn_bytes);+ print_perf(c.paged ? "Paged pair" : "Dense pair", c, time_network(*pair_net, "attn", warmup, iterations), idx_bytes + attn_bytes);+}++INSTANTIATE_TEST_SUITE_P(DISABLED_qsa_ops_perf,+ qsa_ops_perf,+ ::testing::Values(perf_case{true, 511, 1},+ perf_case{true, 1023, 1},+ perf_case{true, 2047, 1},+ perf_case{true, 4095, 1},+ perf_case{true, 16383, 1},+ perf_case{true, 32767, 1},+ perf_case{true, 3072, 1024},+ perf_case{true, 0, 4096},+ perf_case{true, 3072, 1024, true},+ perf_case{true, 0, 4096, true},+ perf_case{false, 511, 1},+ perf_case{false, 1023, 1},+ perf_case{false, 2047, 1},+ perf_case{false, 4095, 1},+ perf_case{false, 16383, 1},+ perf_case{false, 32767, 1},+ perf_case{false, 3072, 1024},+ perf_case{false, 0, 4096},+ perf_case{false, 3072, 1024, true},+ perf_case{false, 0, 4096, true}),+ [](const ::testing::TestParamInfo<perf_case>& info) {+ const auto& c = info.param;+ return std::string(c.paged ? "paged" : "dense") + "_ctx" + std::to_string(c.past_len + c.q_len) + "_q" + std::to_string(c.q_len) ++ (c.no_dpas_score ? "_nodpasq2" : "");+ });++// Per-kernel sweep driver for external GPU tracing (e.g. onetrace -d): one dense (QSAIndexer ++// SparseSDPA) or paged (PagedQSAIndexer + SparsePA) pair with Qwen3.8 dims, configured via the+// environment: QSA_PERF_IMPL=dense|paged, QSA_PERF_PHASE=prefill|decode, QSA_PERF_B, QSA_PERF_LEN+// (prompt length / history length), QSA_PERF_ITERS, QSA_PERF_WARMUP, QSA_PERF_FLUSH_MB (writes+// that many MiB between iterations to evict L2), QSA_PERF_STAGES (comma list of pair|indexer|attention, default pair).+TEST(qsa_ops_perf_sweep, DISABLED_pair) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ auto env_size = [](const char* name, size_t fallback) {+ const char* v = std::getenv(name);+ return v ? static_cast<size_t>(std::strtoull(v, nullptr, 10)) : fallback;+ };+ const char* phase_env = std::getenv("QSA_PERF_PHASE");+ const std::string phase = phase_env ? phase_env : "prefill";+ ASSERT_TRUE(phase == "prefill" || phase == "decode") << phase;+ const size_t batch = env_size("QSA_PERF_B", 1);+ const size_t len = env_size("QSA_PERF_LEN", 1024);+ const int iterations = static_cast<int>(env_size("QSA_PERF_ITERS", 30));+ const size_t flush_mb = env_size("QSA_PERF_FLUSH_MB", 0);+ const int warmup = static_cast<int>(env_size("QSA_PERF_WARMUP", 5));++ auto& engine = get_test_engine();+ const char* impl_env = std::getenv("QSA_PERF_IMPL");+ const std::string impl = impl_env ? impl_env : "dense";+ ASSERT_TRUE(impl == "dense" || impl == "paged") << impl;+ const size_t past = phase == "prefill" ? 0 : len;+ const size_t q_len = phase == "prefill" ? len : 1;+ const char* stages_env = std::getenv("QSA_PERF_STAGES");+ std::stringstream stages(stages_env ? stages_env : "pair");+ memory::ptr flush;+ if (flush_mb != 0) {+ flush = engine.allocate_memory(layout{ov::PartialShape{I(flush_mb << 20)}, data_types::u8, format::bfyx}, allocation_type::usm_device);+ }+ std::string stage_name;+ while (std::getline(stages, stage_name, ',')) {+ ASSERT_TRUE(stage_name == "pair" || stage_name == "indexer" || stage_name == "attention") << stage_name;+ const Stage stage = stage_name == "pair" ? Stage::Pair : (stage_name == "indexer" ? Stage::IndexerOnly : Stage::AttentionOnly);+ const std::string out_id = stage == Stage::IndexerOnly ? "indexer" : "attn";+ std::unique_ptr<network> net;+ if (impl == "paged") {+ net = build_paged_network(engine, paged_inputs_synthetic(qwen38_dims(), past, q_len, batch), stage);+ } else {+ net = build_dense_network(engine, dense_inputs_synthetic(qwen38_dims(), past, q_len, batch), stage);+ }+ auto run_once = [&]() {+ if (flush) {+ flush->fill(get_test_stream(), static_cast<unsigned char>(0), {}, true);+ }+ const auto start = std::chrono::steady_clock::now();+ auto outputs = net->execute();+ outputs.at(out_id).get_memory();+ net->get_stream().finish();+ return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();+ };+ for (int i = 0; i < warmup; i++) {+ run_once();+ }+ double total = 0.0;+ double best = std::numeric_limits<double>::max();+ for (int i = 0; i < iterations; i++) {+ const double ms = run_once();+ total += ms;+ best = std::min(best, ms);+ }+ std::cout << "QSA_SWEEP impl=" << impl << " phase=" << phase << " B=" << batch << " len=" << len << " calls=" << warmup + iterations+ << " wall_avg_ms=" << total / iterations << " wall_min_ms=" << best << " flush_mb=" << flush_mb << " stage=" << stage_name << std::endl;+ }+}++} // namespacediff --git a/src/plugins/intel_gpu/tests/unit/test_cases/sparse_pa_kvq_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/sparse_pa_kvq_gpu_test.cppnew file mode 100644index 00000000000..ffdebbb6c23--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/sparse_pa_kvq_gpu_test.cpp@@ -0,0 +1,1282 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Tests for the quantized (u8 / u4, symmetric / asymmetric, BY_TOKEN / BY_CHANNEL) main KV caches of the paged+// SparsePA primitive. A CPU model of the page format (see intel_gpu/op/sparse_kv_quant.hpp) quantizes the history,+// predicts the cache after the kernel's write stage, and dequantizes the cache the GPU actually produced:+// 1. the GPU cache must match the predicted one up to rounding-edge code differences,+// 2. the attention output must match a reference that reads the GPU cache through the same dequantization+// (isolates the attention kernels' dequant-on-load from the write path),+// 3. the error against the unquantized f16 reference is reported (QSA_KVQ_ACCURACY).+// DISABLED_ benchmark: ov_gpu_unit_tests --gtest_also_run_disabled_tests --gtest_filter='*sparse_pa_kvq_perf*'++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdint>+#include <cstdlib>+#include <cstring>+#include <intel_gpu/op/sparse_kv_quant.hpp>+#include <intel_gpu/primitives/data.hpp>+#include <intel_gpu/primitives/input_layout.hpp>+#include <intel_gpu/primitives/sparse_pa.hpp>+#include <intel_gpu/primitives/sparse_sdpa.hpp>+#include <iomanip>+#include <iostream>+#include <limits>+#include <memory>+#include <numeric>+#include <sstream>+#include <string>+#include <vector>++#include "impls/ocl_v2/qsa_stage_events.hpp"+#include "primitive_inst.h"+#include "test_utils.h"++using namespace cldnn;+using namespace ::tests;++namespace {++using ov::intel_gpu::op::kv_page_layout;+using ov::intel_gpu::op::KVQuant;+using Mode = KVQuant::Mode;++/// The QSA ops run on the OpenCL implementation, which needs the Intel subgroup extensions.+bool ocl_available() {+ const auto& info = get_test_engine().get_device_info();+ return info.supports_intel_subgroups && info.supports_intel_subgroups_short;+}++int64_t I(size_t v) {+ return static_cast<int64_t>(v);+}++float f16r(float x) {+ return static_cast<float>(ov::float16(x));+}++uint16_t f16_bits(float x) {+ return ov::float16(x).to_bits();+}++float f16_from_bits(uint16_t bits) {+ return static_cast<float>(ov::float16::from_bits(bits));+}++constexpr float kMinScale = 1.0f / 16384.0f;++KVQuant token_quant(uint8_t bits, bool sym) {+ return {Mode::BY_TOKEN, bits, sym, 0};+}+KVQuant channel_quant(uint8_t bits, bool sym, uint16_t group) {+ return {Mode::BY_CHANNEL, bits, sym, group};+}++std::string quant_name(const KVQuant& q) {+ if (!q.enabled()) {+ return "f16";+ }+ std::string s = q.mode == Mode::BY_TOKEN ? "tok" : "ch" + std::to_string(q.group_size);+ return s + (q.bits == 8 ? "_i8" : "_u4") + (q.symmetric ? "_sym" : "_asym");+}++// ---------------------------------------------------------------------------+// CPU model of the quantized page format and of the kernels' write stage+// ---------------------------------------------------------------------------++struct quant_pages {+ KVQuant q;+ size_t heads = 0, page = 0, D = 0, pages = 0;+ ov::intel_gpu::op::KVPageLayout lay;+ std::vector<uint8_t> bytes;++ quant_pages() = default;+ quant_pages(const KVQuant& quant, size_t num_pages, size_t kv_heads, size_t page_size, size_t head_size)+ : q(quant),+ heads(kv_heads),+ page(page_size),+ D(head_size),+ pages(num_pages),+ lay(kv_page_layout(quant, page_size, head_size)),+ bytes(num_pages * kv_heads * lay.page_bytes, 0xFF) {} // NaN-patterned: unread-parameter bugs must show++ size_t base(size_t p, size_t h) const {+ return (p * heads + h) * lay.page_bytes;+ }+ float qmax() const {+ return q.bits == 8 ? 255.0f : 15.0f;+ }+ float zero_code() const {+ return q.bits == 8 ? 128.0f : 8.0f;+ }++ void get_params_token(size_t p, size_t h, size_t tok, float& scale, float& zp) const {+ const size_t off = base(p, h) + lay.param_offset + tok * 4;+ uint16_t s = 0, z = 0;+ std::memcpy(&s, &bytes[off], 2);+ std::memcpy(&z, &bytes[off + 2], 2);+ scale = f16_from_bits(s);+ zp = q.symmetric ? zero_code() : f16_from_bits(z);+ }+ size_t record_offset(size_t p, size_t h, size_t tok) const {+ return base(p, h) + lay.param_offset + (tok / q.group_size) * D * (q.symmetric ? 2 : 4);+ }+ void get_params_channel(size_t p, size_t h, size_t tok, std::vector<float>& scale, std::vector<float>& zp) const {+ const size_t rec = record_offset(p, h, tok);+ scale.resize(D);+ zp.resize(D);+ for (size_t c = 0; c < D; c++) {+ uint16_t s = 0, z = 0;+ std::memcpy(&s, &bytes[rec + c * 2], 2);+ scale[c] = f16_from_bits(s);+ if (q.symmetric) {+ zp[c] = zero_code();+ } else {+ std::memcpy(&z, &bytes[rec + D * 2 + c * 2], 2);+ zp[c] = f16_from_bits(z);+ }+ }+ }++ uint8_t code(size_t p, size_t h, size_t tok, size_t c) const {+ const size_t row = base(p, h) + tok * lay.row_bytes;+ if (q.bits == 8) {+ return bytes[row + c];+ }+ const uint8_t b = bytes[row + c / 2];+ return (c % 2 == 0) ? (b & 0xF) : (b >> 4);+ }+ void set_code(size_t p, size_t h, size_t tok, size_t c, uint8_t v) {+ const size_t row = base(p, h) + tok * lay.row_bytes;+ if (q.bits == 8) {+ bytes[row + c] = v;+ } else {+ uint8_t& b = bytes[row + c / 2];+ b = (c % 2 == 0) ? static_cast<uint8_t>((b & 0xF0) | v) : static_cast<uint8_t>((b & 0x0F) | (v << 4));+ }+ }++ /// x = (q - zp) * scale in the kernels' f16 arithmetic.+ static float dequant_one(uint8_t code, float zp, float scale) {+ return f16r(f16r(static_cast<float>(code) - zp) * scale);+ }++ std::vector<float> read_row(size_t p, size_t h, size_t tok) const {+ std::vector<float> out(D);+ if (q.mode == Mode::BY_TOKEN) {+ float s = 0, z = 0;+ get_params_token(p, h, tok, s, z);+ for (size_t c = 0; c < D; c++) {+ out[c] = dequant_one(code(p, h, tok, c), z, s);+ }+ } else {+ std::vector<float> s, z;+ get_params_channel(p, h, tok, s, z);+ for (size_t c = 0; c < D; c++) {+ out[c] = dequant_one(code(p, h, tok, c), z[c], s[c]);+ }+ }+ return out;+ }++ uint8_t quantize(float x, float inv, float zp) const {+ float y = x * inv + zp;+ y = std::min(std::max(y, 0.0f), qmax());+ return static_cast<uint8_t>(y + 0.5f);+ }++ /// BY_TOKEN: quantizes one f16 row.+ void write_token(size_t p, size_t h, size_t tok, const float* row) {+ float mn = row[0], mx = row[0];+ for (size_t c = 0; c < D; c++) {+ mn = std::min(mn, row[c]);+ mx = std::max(mx, row[c]);+ }+ float scale = 1.0f, zp = 0.0f;+ if (q.symmetric) {+ scale = std::max(mx, -mn) / (q.bits == 8 ? 127.0f : 7.0f);+ zp = zero_code();+ } else {+ mn = std::min(mn, 0.0f);+ mx = std::max(mx, 0.0f);+ scale = (mx - mn) / qmax();+ }+ scale = std::max(scale, kMinScale);+ if (!q.symmetric) {+ zp = -mn / scale;+ }+ const uint16_t scale_bits = f16_bits(scale), zp_bits = f16_bits(zp);+ const float inv = 1.0f / f16_from_bits(scale_bits);+ const float zpf = f16_from_bits(zp_bits);+ for (size_t c = 0; c < D; c++) {+ set_code(p, h, tok, c, quantize(row[c], inv, zpf));+ }+ const size_t off = base(p, h) + lay.param_offset + tok * 4;+ std::memcpy(&bytes[off], &scale_bits, 2);+ std::memcpy(&bytes[off + 2], &zp_bits, 2);+ }++ /// BY_CHANNEL: re-quantizes the group starting at page-local token `tok0` from `rows` (one f16 row per+ /// valid token of the group, already dequantized where they came from the cache).+ void write_group(size_t p, size_t h, size_t tok0, const std::vector<std::vector<float>>& rows) {+ std::vector<float> scale_h(D), zp_h(D), inv(D);+ std::vector<uint16_t> scale_bits(D), zp_bits(D);+ for (size_t c = 0; c < D; c++) {+ float mn = 0.0f, mx = 0.0f;+ for (const auto& r : rows) {+ mn = std::min(mn, r[c]);+ mx = std::max(mx, r[c]);+ }+ float scale = 1.0f, zp = 0.0f;+ if (q.symmetric) {+ scale = std::max(mx, -mn) / (q.bits == 8 ? 127.0f : 7.0f);+ zp = zero_code();+ } else {+ scale = (mx - mn) / qmax();+ }+ scale = std::max(scale, kMinScale);+ if (!q.symmetric) {+ zp = -mn / scale;+ }+ scale_bits[c] = f16_bits(scale);+ zp_bits[c] = f16_bits(zp);+ scale_h[c] = f16_from_bits(scale_bits[c]);+ zp_h[c] = f16_from_bits(zp_bits[c]);+ inv[c] = 1.0f / scale_h[c];+ }+ for (size_t t = 0; t < rows.size(); t++) {+ for (size_t c = 0; c < D; c++) {+ set_code(p, h, tok0 + t, c, quantize(rows[t][c], inv[c], zp_h[c]));+ }+ }+ const size_t rec = record_offset(p, h, tok0);+ std::memcpy(&bytes[rec], scale_bits.data(), D * 2);+ if (!q.symmetric) {+ std::memcpy(&bytes[rec + D * 2], zp_bits.data(), D * 2);+ }+ }+};++// ---------------------------------------------------------------------------+// Test data+// ---------------------------------------------------------------------------++struct dims {+ size_t Hq = 24, Hkv = 2, Dh = 256, Dv = 256, r = 4, page = 16, topk = 512;+};++dims qwen38() {+ return {};+}+dims toy() {+ dims d;+ d.Hq = 4;+ d.Hkv = 2;+ d.Dh = 64;+ d.Dv = 64;+ d.topk = 6;+ return d;+}++std::vector<float> make_values(size_t count, uint32_t seed, float scale, size_t channels) {+ std::vector<float> out(count);+ uint32_t s = seed * 2654435761u + 1u;+ for (size_t i = 0; i < count; i++) {+ s = s * 1664525u + 1013904223u;+ float x = (static_cast<float>(s >> 8) / static_cast<float>(1u << 24) * 2.0f - 1.0f);+ // Channels with different magnitudes plus a few outliers: stresses both per-token and per-channel scales.+ const size_t c = i % channels;+ x *= scale * (1.0f + static_cast<float>(c % 7) * 0.5f);+ if ((s >> 3) % 211 == 0) {+ x *= 4.0f;+ }+ out[i] = f16r(x);+ }+ return out;+}++struct seq_spec {+ size_t past, q_len;+};++struct case_data {+ dims d;+ KVQuant kq, vq;+ std::vector<seq_spec> seqs;+ size_t tokens = 0;+ std::vector<size_t> page_count; // per sequence+ std::vector<size_t> page_first; // first logical page of each sequence in the table+ std::vector<int32_t> block_indices, block_indices_begins, subsequence_begins, past_lens;+ std::vector<float> query; // [tokens, Hq*Dh]+ std::vector<std::vector<float>> key_hist, value_hist; // per sequence [total, Hkv, D]+ std::vector<int32_t> sel, count; // [tokens, topk], [tokens]+ size_t total_pages = 0;+};++case_data make_case(const dims& d, const KVQuant& kq, const KVQuant& vq, const std::vector<seq_spec>& seqs, uint32_t seed) {+ case_data c;+ c.d = d;+ c.kq = kq;+ c.vq = vq;+ c.seqs = seqs;+ size_t page_total = 0;+ c.block_indices_begins = {0};+ c.subsequence_begins = {0};+ for (const auto& s : seqs) {+ const size_t total = s.past + s.q_len;+ const size_t pages = (total + d.page - 1) / d.page;+ c.page_first.push_back(page_total);+ c.page_count.push_back(pages);+ page_total += pages;+ c.block_indices_begins.push_back(static_cast<int32_t>(page_total));+ c.subsequence_begins.push_back(static_cast<int32_t>(c.tokens + s.q_len));+ c.past_lens.push_back(static_cast<int32_t>(s.past));+ c.tokens += s.q_len;+ }+ c.total_pages = page_total;+ // A deterministic page permutation: logical order != physical order.+ c.block_indices.resize(page_total);+ for (size_t i = 0; i < page_total; i++) {+ c.block_indices[i] = static_cast<int32_t>((i * 7 + 3) % page_total);+ }+ if (page_total % 7 == 0) { // keep it a permutation+ std::iota(c.block_indices.begin(), c.block_indices.end(), 0);+ }+ c.query = make_values(c.tokens * d.Hq * d.Dh, seed + 1, 1.0f, d.Dh);+ for (size_t s = 0; s < seqs.size(); s++) {+ const size_t total = seqs[s].past + seqs[s].q_len;+ c.key_hist.push_back(make_values(total * d.Hkv * d.Dh, seed + 10 + static_cast<uint32_t>(s), 1.0f, d.Dh));+ c.value_hist.push_back(make_values(total * d.Hkv * d.Dv, seed + 20 + static_cast<uint32_t>(s), 1.0f, d.Dv));+ }+ c.sel.assign(c.tokens * d.topk, 0);+ c.count.assign(c.tokens, 0);+ size_t t = 0;+ for (const auto& s : seqs) {+ for (size_t i = 0; i < s.q_len; i++, t++) {+ const size_t n_complete = (s.past + i + 1) / d.r;+ const size_t cnt = std::min(d.topk, n_complete);+ for (size_t j = 0; j < cnt; j++) {+ c.sel[t * d.topk + j] = static_cast<int32_t>(j * n_complete / cnt);+ }+ c.count[t] = static_cast<int32_t>(cnt);+ }+ }+ return c;+}++/// Quantizes tokens [from, to) of a sequence into `qp`, in the order the GPU kernels see them (token modes row by+/// row; BY_CHANNEL group by group, re-quantizing a group that already holds cached tokens).+void cpu_write_range(quant_pages& qp, const case_data& c, size_t seq, const std::vector<float>& hist, size_t head_size, size_t from, size_t to) {+ const auto& d = c.d;+ const size_t phys_base = c.page_first[seq];+ auto phys = [&](size_t tok) {+ return static_cast<size_t>(c.block_indices[phys_base + tok / d.page]);+ };+ for (size_t h = 0; h < d.Hkv; h++) {+ if (qp.q.mode == Mode::BY_TOKEN) {+ for (size_t t = from; t < to; t++) {+ qp.write_token(phys(t), h, t % d.page, &hist[(t * d.Hkv + h) * head_size]);+ }+ continue;+ }+ const size_t G = qp.q.group_size;+ for (size_t g = from / G; g * G < to; g++) {+ const size_t g0 = g * G;+ const size_t n_valid = std::min(G, to - g0);+ const size_t n_old = from > g0 ? std::min(from - g0, n_valid) : 0;+ std::vector<std::vector<float>> rows;+ for (size_t t = 0; t < n_valid; t++) {+ if (t < n_old) {+ rows.push_back(qp.read_row(phys(g0), h, (g0 % d.page) + t));+ } else {+ rows.emplace_back(hist.begin() + ((g0 + t) * d.Hkv + h) * head_size, hist.begin() + ((g0 + t) * d.Hkv + h + 1) * head_size);+ }+ }+ qp.write_group(phys(g0), h, g0 % d.page, rows);+ }+ }+}++template <typename T>+memory::ptr make_device_mem(engine& eng, const ov::PartialShape& shape, data_types dt, const std::vector<T>& data) {+ auto mem = eng.allocate_memory(layout{shape, dt, format::bfyx}, allocation_type::usm_device);+ if (!data.empty()) {+ mem->copy_from(get_test_stream(), data.data(), true);+ }+ return mem;+}++memory::ptr make_f16_mem(engine& eng, const ov::PartialShape& shape, const std::vector<float>& data) {+ std::vector<ov::float16> h(data.size());+ for (size_t i = 0; i < data.size(); i++) {+ h[i] = ov::float16(data[i]);+ }+ return make_device_mem(eng, shape, data_types::f16, h);+}++template <typename T>+std::vector<T> read_mem(const memory::ptr& mem) {+ mem_lock<T, mem_lock_type::read> lock(mem, get_test_stream());+ return {lock.begin(), lock.end()};+}++struct gpu_run {+ std::vector<float> out;+ std::vector<uint8_t> key_bytes, value_bytes;+ std::vector<float> key_f16, value_f16; // for f16 caches+};++struct run_options {+ bool profile = false;+ int warmup = 0;+ int iterations = 1;+ double gpu_ms_min = 0.0, gpu_ms_avg = 0.0;+ size_t kernels = 0;+ std::vector<double> stage_ms; // per dispatched stage of the best iteration+};++ov::PartialShape cache_shape(const case_data& c, const KVQuant& q, size_t head_size) {+ const auto lay = kv_page_layout(q, c.d.page, head_size);+ return q.enabled() ? ov::PartialShape{I(c.total_pages), I(c.d.Hkv), I(lay.total_rows), I(lay.row_bytes)}+ : ov::PartialShape{I(c.total_pages), I(c.d.Hkv), I(c.d.page), I(head_size)};+}++/// Runs the sparse_pa primitive. Caches start from `key_init` / `value_init` (raw bytes / f16 values).+gpu_run run_gpu(const case_data& c, const std::vector<uint8_t>& key_init, const std::vector<uint8_t>& value_init, run_options* opt = nullptr) {+ auto& engine = get_test_engine();+ const auto& d = c.d;+ const size_t T = c.tokens;++ // New tokens (the kernel writes them): token-major [T, Hkv*D].+ std::vector<float> key_new(T * d.Hkv * d.Dh), value_new(T * d.Hkv * d.Dv);+ size_t t0 = 0;+ for (size_t s = 0; s < c.seqs.size(); s++) {+ const auto& sp = c.seqs[s];+ std::copy(c.key_hist[s].begin() + sp.past * d.Hkv * d.Dh, c.key_hist[s].end(), key_new.begin() + t0 * d.Hkv * d.Dh);+ std::copy(c.value_hist[s].begin() + sp.past * d.Hkv * d.Dv, c.value_hist[s].end(), value_new.begin() + t0 * d.Hkv * d.Dv);+ t0 += sp.q_len;+ }++ cldnn::sparse_pa::Config cfg;+ cfg.num_heads = d.Hq;+ cfg.num_kv_heads = d.Hkv;+ cfg.num_selection_heads = 1;+ cfg.k_head_size = d.Dh;+ cfg.v_head_size = d.Dv;+ cfg.key_block_size = d.r;+ cfg.query_block_size = 1;+ cfg.causal = true;+ cfg.page_size = d.page;+ cfg.key_quant = c.kq;+ cfg.value_quant = c.vq;+ const float scale = 1.0f / std::sqrt(static_cast<float>(d.Dh));++ const auto kshape = cache_shape(c, c.kq, d.Dh);+ const auto vshape = cache_shape(c, c.vq, d.Dv);+ const auto kdt = c.kq.enabled() ? data_types::u8 : data_types::f16;+ const auto vdt = c.vq.enabled() ? data_types::u8 : data_types::f16;++ auto key_cache = engine.allocate_memory(layout{kshape, kdt, format::bfyx}, allocation_type::usm_device);+ auto value_cache = engine.allocate_memory(layout{vshape, vdt, format::bfyx}, allocation_type::usm_device);+ key_cache->copy_from(get_test_stream(), key_init.data(), true);+ value_cache->copy_from(get_test_stream(), value_init.data(), true);++ topology topo;+ topo.add(input_layout("query", layout{{I(T), I(d.Hq * d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("key", layout{{I(T), I(d.Hkv * d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("value", layout{{I(T), I(d.Hkv * d.Dv)}, data_types::f16, format::bfyx}));+ topo.add(input_layout("key_cache", layout{kshape, kdt, format::bfyx}));+ topo.add(input_layout("value_cache", layout{vshape, vdt, format::bfyx}));+ topo.add(data("past_lens", make_device_mem(engine, {I(c.past_lens.size())}, data_types::i32, c.past_lens)));+ topo.add(data("subsequence_begins", make_device_mem(engine, {I(c.subsequence_begins.size())}, data_types::i32, c.subsequence_begins)));+ topo.add(data("block_indices", make_device_mem(engine, {I(c.block_indices.size())}, data_types::i32, c.block_indices)));+ topo.add(data("block_indices_begins", make_device_mem(engine, {I(c.block_indices_begins.size())}, data_types::i32, c.block_indices_begins)));+ topo.add(data("sel", make_device_mem(engine, {I(T), 1, I(d.topk)}, data_types::i32, c.sel)));+ topo.add(data("count", make_device_mem(engine, {I(T), 1}, data_types::i32, c.count)));+ topo.add(sparse_pa("attn",+ {input_info("query"),+ input_info("key"),+ input_info("value"),+ input_info("key_cache"),+ input_info("value_cache"),+ input_info("past_lens"),+ input_info("subsequence_begins"),+ input_info("block_indices"),+ input_info("block_indices_begins"),+ input_info("sel"),+ input_info("count")},+ cfg,+ scale));++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ if (opt && opt->profile) {+ config.set_property(ov::enable_profiling(true));+ }+ network net(engine, topo, config);+ net.set_input_data("query", make_f16_mem(engine, {I(T), I(d.Hq * d.Dh)}, c.query));+ net.set_input_data("key", make_f16_mem(engine, {I(T), I(d.Hkv * d.Dh)}, key_new));+ net.set_input_data("value", make_f16_mem(engine, {I(T), I(d.Hkv * d.Dv)}, value_new));+ net.set_input_data("key_cache", key_cache);+ net.set_input_data("value_cache", value_cache);++ gpu_run run;+ const int warmup = opt ? opt->warmup : 0;+ const int iterations = opt ? opt->iterations : 1;+ std::vector<double> gpu_times;+ for (int it = 0; it < warmup + iterations; it++) {+ const bool measure = opt != nullptr && opt->profile && it >= warmup;+ ov::intel_gpu::ocl::qsa::QsaStageEvents::events().clear();+ ov::intel_gpu::ocl::qsa::QsaStageEvents::armed() = measure;+ auto outputs = net.execute();+ outputs.at("attn").get_memory();+ net.get_stream().finish();+ ov::intel_gpu::ocl::qsa::QsaStageEvents::armed() = false;+ if (measure) {+ double total = 0.0;+ std::vector<double> stages;+ for (const auto& ev : ov::intel_gpu::ocl::qsa::QsaStageEvents::events()) {+ for (const auto& interval : ev->get_profiling_info()) {+ if (interval.stage == instrumentation::profiling_stage::executing) {+ const double ms = std::chrono::duration<double, std::milli>(interval.value->value()).count();+ total += ms;+ stages.push_back(ms);+ break;+ }+ }+ }+ opt->kernels = ov::intel_gpu::ocl::qsa::QsaStageEvents::events().size();+ if (gpu_times.empty() || total < *std::min_element(gpu_times.begin(), gpu_times.end())) {+ opt->stage_ms = stages;+ }+ gpu_times.push_back(total);+ }+ if (it + 1 == warmup + iterations) {+ for (auto& v : read_mem<ov::float16>(outputs.at("attn").get_memory())) {+ run.out.push_back(static_cast<float>(v));+ }+ }+ }+ if (opt && !gpu_times.empty()) {+ opt->gpu_ms_min = *std::min_element(gpu_times.begin(), gpu_times.end());+ opt->gpu_ms_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) / static_cast<double>(gpu_times.size());+ }+ if (c.kq.enabled()) {+ run.key_bytes = read_mem<uint8_t>(key_cache);+ }+ if (c.vq.enabled()) {+ run.value_bytes = read_mem<uint8_t>(value_cache);+ }+ return run;+}++/// Attention reference over per-token K/V rows supplied by `k_row(seq, pos, head)` / `v_row`.+template <typename KRow, typename VRow>+std::vector<float> reference_attention(const case_data& c, KRow&& k_row, VRow&& v_row) {+ const auto& d = c.d;+ std::vector<float> out(c.tokens * d.Hq * d.Dv, 0.0f);+ const size_t group = d.Hq / d.Hkv;+ const double scale = 1.0 / std::sqrt(static_cast<double>(d.Dh));+ size_t t = 0;+ for (size_t s = 0; s < c.seqs.size(); s++) {+ for (size_t i = 0; i < c.seqs[s].q_len; i++, t++) {+ const size_t abs_pos = c.seqs[s].past + i;+ std::vector<size_t> tokens;+ for (int32_t j = 0; j < c.count[t]; j++) {+ const size_t b = static_cast<size_t>(c.sel[t * d.topk + j]);+ for (size_t k = 0; k < d.r; k++) {+ tokens.push_back(b * d.r + k);+ }+ }+ for (size_t p = ((abs_pos + 1) / d.r) * d.r; p <= abs_pos; p++) {+ tokens.push_back(p);+ }+ for (size_t h = 0; h < d.Hq; h++) {+ const size_t kv = h / group;+ std::vector<double> logits(tokens.size());+ for (size_t n = 0; n < tokens.size(); n++) {+ const auto krow = k_row(s, tokens[n], kv);+ double dot = 0.0;+ for (size_t j = 0; j < d.Dh; j++) {+ dot += static_cast<double>(c.query[(t * d.Hq + h) * d.Dh + j]) * krow[j];+ }+ logits[n] = dot * scale;+ }+ const double m = *std::max_element(logits.begin(), logits.end());+ double sum = 0.0;+ for (auto& x : logits) {+ x = std::exp(x - m);+ sum += x;+ }+ std::vector<double> acc(d.Dv, 0.0);+ for (size_t n = 0; n < tokens.size(); n++) {+ const auto vrow = v_row(s, tokens[n], kv);+ for (size_t j = 0; j < d.Dv; j++) {+ acc[j] += logits[n] * vrow[j];+ }+ }+ for (size_t j = 0; j < d.Dv; j++) {+ out[(t * d.Hq + h) * d.Dv + j] = static_cast<float>(acc[j] / sum);+ }+ }+ }+ }+ return out;+}++struct err_stats {+ double max_abs = 0, mean_abs = 0, max_rel = 0;+ size_t bad = 0;+};++err_stats compare(const std::vector<float>& actual, const std::vector<float>& expected, double atol, double rtol) {+ err_stats e;+ EXPECT_EQ(actual.size(), expected.size());+ double sum = 0.0;+ for (size_t i = 0; i < std::min(actual.size(), expected.size()); i++) {+ const double diff = std::fabs(static_cast<double>(actual[i]) - expected[i]);+ e.max_abs = std::max(e.max_abs, diff);+ e.max_rel = std::max(e.max_rel, diff / (std::fabs(static_cast<double>(expected[i])) + 1e-6));+ sum += diff;+ if (!std::isfinite(actual[i]) || diff > atol + rtol * std::fabs(static_cast<double>(expected[i]))) {+ e.bad++;+ }+ }+ e.mean_abs = sum / static_cast<double>(std::max<size_t>(1, actual.size()));+ return e;+}++struct kvq_case {+ std::string name;+ dims d;+ KVQuant k, v;+ std::vector<seq_spec> seqs;+};++/// Builds the initial caches (history quantized on the CPU), runs the GPU and checks the three properties.+void run_case(const kvq_case& tc) {+ const auto c = make_case(tc.d, tc.k, tc.v, tc.seqs, 1);+ const auto& d = c.d;+ const size_t D[2] = {d.Dh, d.Dv};+ std::vector<quant_pages> hist(2), expected(2);+ const KVQuant quants[2] = {c.kq, c.vq};+ for (int which = 0; which < 2; which++) {+ hist[which] = quant_pages(quants[which], c.total_pages, d.Hkv, d.page, D[which]);+ for (size_t s = 0; s < c.seqs.size(); s++) {+ cpu_write_range(hist[which], c, s, which == 0 ? c.key_hist[s] : c.value_hist[s], D[which], 0, c.seqs[s].past);+ }+ expected[which] = hist[which];+ for (size_t s = 0; s < c.seqs.size(); s++) {+ cpu_write_range(expected[which], c, s, which == 0 ? c.key_hist[s] : c.value_hist[s], D[which], c.seqs[s].past, c.seqs[s].past + c.seqs[s].q_len);+ }+ }++ const auto run = run_gpu(c, hist[0].bytes, hist[1].bytes);+ ASSERT_FALSE(run.out.empty());++ // 1. The cache the GPU wrote vs the predicted one: dequantized difference in quantization steps.+ quant_pages gpu_pages[2] = {hist[0], hist[1]};+ gpu_pages[0].bytes = run.key_bytes;+ gpu_pages[1].bytes = run.value_bytes;+ for (int which = 0; which < 2; which++) {+ double max_steps = 0.0;+ size_t differing = 0, total = 0;+ for (size_t s = 0; s < c.seqs.size(); s++) {+ const size_t tot = c.seqs[s].past + c.seqs[s].q_len;+ for (size_t t = 0; t < tot; t++) {+ const size_t page = static_cast<size_t>(c.block_indices[c.page_first[s] + t / d.page]);+ for (size_t h = 0; h < d.Hkv; h++) {+ const auto got = gpu_pages[which].read_row(page, h, t % d.page);+ const auto want = expected[which].read_row(page, h, t % d.page);+ float scale_s = 0, scale_z = 0;+ std::vector<float> ch_s, ch_z;+ if (quants[which].mode == Mode::BY_TOKEN) {+ expected[which].get_params_token(page, h, t % d.page, scale_s, scale_z);+ } else {+ expected[which].get_params_channel(page, h, t % d.page, ch_s, ch_z);+ }+ for (size_t j = 0; j < D[which]; j++) {+ const double step = quants[which].mode == Mode::BY_TOKEN ? scale_s : ch_s[j];+ const double diff = std::fabs(static_cast<double>(got[j]) - want[j]);+ max_steps = std::max(max_steps, diff / step);+ differing += diff > 1e-6 ? 1 : 0;+ total++;+ }+ }+ }+ }+ std::cout << "QSA_KVQ_CACHE " << tc.name << (which == 0 ? " key" : " value") << " max_diff_steps=" << max_steps << " differing=" << std::setprecision(4)+ << 100.0 * static_cast<double>(differing) / static_cast<double>(total) << "%" << std::endl;+ EXPECT_LE(max_steps, 2.5) << tc.name << (which == 0 ? " key" : " value") << " cache differs from the prediction";+ EXPECT_LE(static_cast<double>(differing) / static_cast<double>(total), 0.05) << tc.name << (which == 0 ? " key" : " value");+ }++ // 2. Attention over the GPU cache read back through the CPU dequantizer.+ auto cache_row = [&](int which, size_t s, size_t pos, size_t kv) {+ const size_t page = static_cast<size_t>(c.block_indices[c.page_first[s] + pos / d.page]);+ return gpu_pages[which].read_row(page, kv, pos % d.page);+ };+ const auto ref_cache = reference_attention(+ c,+ [&](size_t s, size_t pos, size_t kv) {+ return cache_row(0, s, pos, kv);+ },+ [&](size_t s, size_t pos, size_t kv) {+ return cache_row(1, s, pos, kv);+ });+ const auto e_attn = compare(run.out, ref_cache, 1.5e-2, 1.5e-2);+ std::cout << "QSA_KVQ_ATTN " << tc.name << " max_abs=" << e_attn.max_abs << " mean_abs=" << e_attn.mean_abs << " bad=" << e_attn.bad << std::endl;+ EXPECT_EQ(e_attn.bad, 0u) << tc.name << ": attention output differs from the dequantized-cache reference";++ // 3. Accuracy against the unquantized f16 reference.+ const auto ref_f16 = reference_attention(+ c,+ [&](size_t s, size_t pos, size_t kv) {+ return std::vector<float>(c.key_hist[s].begin() + (pos * d.Hkv + kv) * d.Dh, c.key_hist[s].begin() + (pos * d.Hkv + kv + 1) * d.Dh);+ },+ [&](size_t s, size_t pos, size_t kv) {+ return std::vector<float>(c.value_hist[s].begin() + (pos * d.Hkv + kv) * d.Dv, c.value_hist[s].begin() + (pos * d.Hkv + kv + 1) * d.Dv);+ });+ const auto e_q = compare(run.out, ref_f16, 1e9, 1e9);+ double ref_mean = 0.0;+ for (float x : ref_f16) {+ ref_mean += std::fabs(x);+ }+ ref_mean /= static_cast<double>(ref_f16.size());+ std::cout << "QSA_KVQ_ACCURACY " << tc.name << " max_abs=" << e_q.max_abs << " mean_abs=" << e_q.mean_abs << " rel_mean=" << e_q.mean_abs / ref_mean+ << std::endl;+ EXPECT_LT(e_q.mean_abs / ref_mean, tc.k.bits == 4 || tc.v.bits == 4 ? 0.5 : 0.03) << tc.name;+}++std::string case_name(const char* dim_name, const KVQuant& k, const KVQuant& v, const std::vector<seq_spec>& seqs) {+ std::ostringstream os;+ os << dim_name << "_K" << quant_name(k) << "_V" << quant_name(v);+ for (const auto& s : seqs) {+ os << "_" << s.past << "p" << s.q_len;+ }+ return os.str();+}++class sparse_pa_kvq : public ::testing::TestWithParam<kvq_case> {};++TEST_P(sparse_pa_kvq, matches_reference) {+ if (!ocl_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ run_case(GetParam());+}++std::vector<kvq_case> all_cases() {+ std::vector<kvq_case> cases;+ auto add = [&](const char* dn, const dims& d, const KVQuant& k, const KVQuant& v, std::vector<seq_spec> seqs) {+ cases.push_back({case_name(dn, k, v, seqs), d, k, v, std::move(seqs)});+ };+ const std::vector<std::vector<seq_spec>> scenarios = {{{0, 37}}, {{21, 1}}, {{123, 45}}, {{2051, 1}}, {{40, 1}, {0, 70}, {17, 3}}};+ for (const auto& seqs : scenarios) {+ // Token-mode keys, both bit widths and both symmetries.+ add("qwen", qwen38(), token_quant(8, false), token_quant(8, false), seqs);+ add("qwen", qwen38(), token_quant(4, true), token_quant(4, true), seqs);+ // BY_CHANNEL keys.+ add("qwen", qwen38(), channel_quant(8, false, 16), token_quant(8, false), seqs);+ add("qwen", qwen38(), channel_quant(4, false, 16), token_quant(4, false), seqs);+ add("qwen", qwen38(), channel_quant(8, true, 16), token_quant(8, true), seqs);+ }+ // Page 32 with 32-token groups, and the scalar kernels (head size 64 -> no GQA-DPAS for quantized caches).+ dims wide_page = qwen38();+ wide_page.page = 32;+ for (const auto& seqs : {std::vector<seq_spec>{{0, 100}}, std::vector<seq_spec>{{33, 1}}, std::vector<seq_spec>{{70, 40}}}) {+ add("qwenpage32", wide_page, channel_quant(8, false, 32), token_quant(8, false), seqs);+ add("qwenpage32", wide_page, channel_quant(4, true, 32), token_quant(4, true), seqs);+ }+ // Head size 128: GQA-DPAS workers load 32-channel slices (16-byte 4-bit rows per message).+ dims d128 = qwen38();+ d128.Dh = d128.Dv = 128;+ for (const auto& seqs :+ {std::vector<seq_spec>{{0, 37}}, std::vector<seq_spec>{{21, 1}}, std::vector<seq_spec>{{123, 45}}, std::vector<seq_spec>{{40, 1}, {0, 70}, {17, 3}}}) {+ add("d128", d128, token_quant(8, false), token_quant(8, false), seqs);+ add("d128", d128, token_quant(4, true), token_quant(4, true), seqs);+ add("d128", d128, channel_quant(8, false, 16), token_quant(8, false), seqs);+ add("d128", d128, channel_quant(4, false, 16), token_quant(4, false), seqs);+ }+ for (const auto& seqs : scenarios) {+ add("toy", toy(), token_quant(8, false), token_quant(4, false), seqs);+ add("toy", toy(), channel_quant(4, false, 16), token_quant(8, true), seqs);+ add("toy", toy(), channel_quant(8, false, 16), token_quant(8, false), seqs);+ }+ return cases;+}++INSTANTIATE_TEST_SUITE_P(smoke, sparse_pa_kvq, ::testing::ValuesIn(all_cases()), [](const ::testing::TestParamInfo<kvq_case>& info) {+ return info.param.name;+});++// Attention-only: a cache that mixes an f16 key cache with a quantized value cache (and vice versa).+TEST(sparse_pa_kvq_mixed, f16_key_quantized_value) {+ if (!ocl_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ const auto c = make_case(qwen38(), KVQuant{}, token_quant(8, false), {{123, 45}}, 7);+ const auto& d = c.d;+ quant_pages vhist(c.vq, c.total_pages, d.Hkv, d.page, d.Dv);+ cpu_write_range(vhist, c, 0, c.value_hist[0], d.Dv, 0, 123);+ std::vector<ov::float16> khist(c.total_pages * d.Hkv * d.page * d.Dh, ov::float16(0.0f));+ for (size_t t = 0; t < 123; t++) {+ const size_t page = static_cast<size_t>(c.block_indices[c.page_first[0] + t / d.page]);+ for (size_t h = 0; h < d.Hkv; h++) {+ for (size_t j = 0; j < d.Dh; j++) {+ khist[((page * d.Hkv + h) * d.page + t % d.page) * d.Dh + j] = ov::float16(c.key_hist[0][(t * d.Hkv + h) * d.Dh + j]);+ }+ }+ }+ std::vector<uint8_t> kbytes(khist.size() * 2);+ std::memcpy(kbytes.data(), khist.data(), kbytes.size());+ const auto run = run_gpu(c, kbytes, vhist.bytes);+ quant_pages vpages = vhist;+ vpages.bytes = run.value_bytes;+ const auto ref = reference_attention(+ c,+ [&](size_t s, size_t pos, size_t kv) {+ return std::vector<float>(c.key_hist[s].begin() + (pos * d.Hkv + kv) * d.Dh, c.key_hist[s].begin() + (pos * d.Hkv + kv + 1) * d.Dh);+ },+ [&](size_t s, size_t pos, size_t kv) {+ const size_t page = static_cast<size_t>(c.block_indices[c.page_first[s] + pos / d.page]);+ return vpages.read_row(page, kv, pos % d.page);+ });+ const auto e = compare(run.out, ref, 1.5e-2, 1.5e-2);+ std::cout << "QSA_KVQ_ATTN mixed_f16K_i8V max_abs=" << e.max_abs << " bad=" << e.bad << std::endl;+ EXPECT_EQ(e.bad, 0u);+}++// ---------------------------------------------------------------------------+// Dense SparseSDPA with compressed K/V (KVCacheCompressed format, see intel_gpu/op/sparse_kv_quant.hpp): i8 data+// tensors with planar scale / zero point tensors. The history is quantized on the CPU in the format of the cache.+// ---------------------------------------------------------------------------++struct dense_case {+ dims d;+ std::vector<size_t> key_len; // valid keys per batch row (left padded inside S = max)+ size_t q_len;+ KVQuant k = token_quant(8, false);+ KVQuant v = token_quant(8, false);+};++/// A quantized dense history [B, Hkv, S, D].+struct dense_quantized {+ std::vector<int8_t> data; // [B, Hkv, S, row_bytes]+ std::vector<float> scale, zp; // elements of the parameter tensors (zp unused when symmetric)+ ov::PartialShape param_shape; // [B, Hkv, S, 1]+ std::vector<float> deq; // dequantized [B, Hkv, S, D] in the kernels' f16 arithmetic+};++dense_quantized quantize_dense(const KVQuant& q, const std::vector<float>& x, size_t B, size_t H, size_t S, size_t D) {+ using ov::intel_gpu::op::dense_row_bytes;+ using ov::intel_gpu::op::dense_signed_codes;+ dense_quantized out;+ const size_t row_bytes = dense_row_bytes(q, D);+ const float qmax = q.bits == 8 ? 255.0f : 15.0f;+ const float zero_code = q.bits == 8 ? 128.0f : 8.0f;+ out.data.assign(B * H * S * row_bytes, 0);+ out.deq.assign(B * H * S * D, 0.0f);++ // Stores a code: signed 8-bit codes as is, unsigned ones as bytes / packed nibbles (low nibble = even channel).+ auto put = [&](size_t row, size_t c, int code) {+ if (q.bits == 8) {+ out.data[row * row_bytes + c] = static_cast<int8_t>(code);+ } else {+ auto& b = reinterpret_cast<uint8_t&>(out.data[row * row_bytes + c / 2]);+ b = (c % 2 == 0) ? static_cast<uint8_t>((b & 0xF0) | code) : static_cast<uint8_t>((b & 0x0F) | (code << 4));+ }+ };++ {+ out.param_shape = ov::PartialShape{I(B), I(H), I(S), 1};+ out.scale.assign(B * H * S, 1.0f);+ out.zp.assign(B * H * S, 0.0f);+ for (size_t row = 0; row < B * H * S; row++) {+ const float* r = &x[row * D];+ float mn = 0.0f, mx = 0.0f;+ for (size_t c = 0; c < D; c++) {+ mn = std::min(mn, r[c]);+ mx = std::max(mx, r[c]);+ }+ if (dense_signed_codes(q) && !q.symmetric) {+ // 8-bit asymmetric: signed codes with an integer zero point.+ const float scale = f16r(std::max((mx - mn) / 255.0f, kMinScale));+ const int zp = std::min(127, std::max(-128, static_cast<int>(std::lround(-128.0f - mn / scale))));+ out.scale[row] = scale;+ out.zp[row] = static_cast<float>(zp);+ for (size_t c = 0; c < D; c++) {+ const int code = std::min(127, std::max(-128, static_cast<int>(std::lround(r[c] / scale)) + zp));+ put(row, c, code);+ out.deq[row * D + c] = f16r(f16r(static_cast<float>(code - zp)) * scale);+ }+ } else if (dense_signed_codes(q)) {+ // 8-bit symmetric: signed codes, no zero point.+ const float scale = f16r(std::max(std::max(mx, -mn) / 127.0f, kMinScale));+ out.scale[row] = scale;+ for (size_t c = 0; c < D; c++) {+ const int code = std::min(127, std::max(-127, static_cast<int>(std::lround(r[c] / scale))));+ put(row, c, code);+ out.deq[row * D + c] = f16r(f16r(static_cast<float>(code)) * scale);+ }+ } else {+ // 4-bit: unsigned codes, f16 zero point (symmetric: biased by 8).+ float scale, zp;+ if (q.symmetric) {+ scale = std::max(std::max(mx, -mn) / 7.0f, kMinScale);+ zp = zero_code;+ } else {+ scale = std::max((mx - mn) / qmax, kMinScale);+ zp = -mn / scale;+ }+ scale = f16r(scale);+ zp = f16r(zp);+ out.scale[row] = scale;+ out.zp[row] = zp;+ for (size_t c = 0; c < D; c++) {+ const int code = static_cast<int>(std::min(std::max(r[c] / scale + zp, 0.0f), qmax) + 0.5f);+ put(row, c, code);+ out.deq[row * D + c] = f16r(f16r(static_cast<float>(code) - zp) * scale);+ }+ }+ }+ return out;+ }+}++void run_dense_case(const dense_case& tc, const char* name) {+ const auto& d = tc.d;+ const size_t B = tc.key_len.size();+ const size_t L = tc.q_len;+ const size_t S = *std::max_element(tc.key_len.begin(), tc.key_len.end());++ // Logical keys/values, stored left padded: logical j of row b at index S - kl + j.+ std::vector<float> key(B * d.Hkv * S * d.Dh, 0.0f), value(B * d.Hkv * S * d.Dv, 0.0f);+ {+ const auto kv = make_values(B * d.Hkv * S * d.Dh, 5, 1.0f, d.Dh);+ const auto vv = make_values(B * d.Hkv * S * d.Dv, 6, 1.0f, d.Dv);+ for (size_t b = 0; b < B; b++) {+ for (size_t h = 0; h < d.Hkv; h++) {+ for (size_t j = 0; j < tc.key_len[b]; j++) {+ const size_t row = (b * d.Hkv + h) * S + (S - tc.key_len[b]) + j;+ std::copy(kv.begin() + row * d.Dh, kv.begin() + (row + 1) * d.Dh, key.begin() + row * d.Dh);+ std::copy(vv.begin() + row * d.Dv, vv.begin() + (row + 1) * d.Dv, value.begin() + row * d.Dv);+ }+ }+ }+ }+ const auto kq = quantize_dense(tc.k, key, B, d.Hkv, S, d.Dh);+ const auto vq = quantize_dense(tc.v, value, B, d.Hkv, S, d.Dv);+ const auto query = make_values(B * d.Hq * L * d.Dh, 7, 1.0f, d.Dh);++ std::vector<int32_t> sel(B * L * d.topk, 0), count(B * L, 0), key_length;+ for (size_t b = 0; b < B; b++) {+ key_length.push_back(static_cast<int32_t>(tc.key_len[b]));+ for (size_t l = 0; l < L; l++) {+ const size_t abs_pos = tc.key_len[b] - L + l;+ const size_t n_complete = (abs_pos + 1) / d.r;+ const size_t cnt = std::min(d.topk, n_complete);+ for (size_t j = 0; j < cnt; j++) {+ sel[(b * L + l) * d.topk + j] = static_cast<int32_t>(j * n_complete / cnt);+ }+ count[b * L + l] = static_cast<int32_t>(cnt);+ }+ }++ auto& engine = get_test_engine();+ ov::intel_gpu::op::SparseSDPA::Config cfg;+ cfg.num_heads = d.Hq;+ cfg.num_kv_heads = d.Hkv;+ cfg.num_selection_heads = 1;+ cfg.k_head_size = d.Dh;+ cfg.v_head_size = d.Dv;+ cfg.key_block_size = d.r;+ cfg.query_block_size = 1;+ cfg.causal = true;+ cfg.key_quant = tc.k;+ cfg.value_quant = tc.v;+ const float scale = 1.0f / std::sqrt(static_cast<float>(d.Dh));++ const ov::PartialShape kv_shape_k{I(B), I(d.Hkv), I(S), I(ov::intel_gpu::op::dense_row_bytes(tc.k, d.Dh))};+ const ov::PartialShape kv_shape_v{I(B), I(d.Hkv), I(S), I(ov::intel_gpu::op::dense_row_bytes(tc.v, d.Dv))};+ auto zp_mem = [&](const KVQuant& q, const dense_quantized& dq) {+ if (ov::intel_gpu::op::dense_zp_is_f16(q)) {+ return make_f16_mem(engine, dq.param_shape, dq.zp);+ }+ std::vector<int8_t> zp(dq.zp.size());+ for (size_t i = 0; i < zp.size(); i++) {+ zp[i] = static_cast<int8_t>(dq.zp[i]);+ }+ return make_device_mem(engine, dq.param_shape, data_types::i8, zp);+ };+ topology topo;+ topo.add(input_layout("query", layout{{I(B), I(d.Hq), I(L), I(d.Dh)}, data_types::f16, format::bfyx}));+ topo.add(data("key", make_device_mem(engine, kv_shape_k, data_types::i8, kq.data)));+ topo.add(data("value", make_device_mem(engine, kv_shape_v, data_types::i8, vq.data)));+ topo.add(data("sel", make_device_mem(engine, {I(B), 1, I(L), I(d.topk)}, data_types::i32, sel)));+ topo.add(data("count", make_device_mem(engine, {I(B), 1, I(L)}, data_types::i32, count)));+ topo.add(data("key_length", make_device_mem(engine, {I(B)}, data_types::i32, key_length)));+ topo.add(data("key_scale", make_f16_mem(engine, kq.param_shape, kq.scale)));+ topo.add(data("value_scale", make_f16_mem(engine, vq.param_shape, vq.scale)));+ std::vector<input_info> attn_inputs = {input_info("query"),+ input_info("key"),+ input_info("value"),+ input_info("sel"),+ input_info("count"),+ input_info("key_length"),+ input_info("key_scale"),+ input_info("value_scale")};+ if (!tc.k.symmetric) {+ topo.add(data("key_zp", zp_mem(tc.k, kq)));+ topo.add(data("value_zp", zp_mem(tc.v, vq)));+ attn_inputs.push_back(input_info("key_zp"));+ attn_inputs.push_back(input_info("value_zp"));+ }+ topo.add(sparse_sdpa("attn", attn_inputs, cfg, scale));+ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network net(engine, topo, config);+ net.set_input_data("query", make_f16_mem(engine, {I(B), I(d.Hq), I(L), I(d.Dh)}, query));+ auto outputs = net.execute();+ std::vector<float> out;+ for (auto v : read_mem<ov::float16>(outputs.at("attn").get_memory())) {+ out.push_back(static_cast<float>(v));+ }++ // Reference over the dequantized (and, for the accuracy line, the original) K/V.+ const size_t group = d.Hq / d.Hkv;+ std::vector<float> ref(B * d.Hq * L * d.Dv), ref_f16(B * d.Hq * L * d.Dv);+ for (int which = 0; which < 2; which++) {+ auto& dst = which == 0 ? ref : ref_f16;+ const auto& K = which == 0 ? kq.deq : key;+ const auto& V = which == 0 ? vq.deq : value;+ for (size_t b = 0; b < B; b++) {+ for (size_t l = 0; l < L; l++) {+ const size_t abs_pos = tc.key_len[b] - L + l;+ std::vector<size_t> tokens;+ for (int32_t j = 0; j < count[b * L + l]; j++) {+ for (size_t k = 0; k < d.r; k++) {+ tokens.push_back(static_cast<size_t>(sel[(b * L + l) * d.topk + j]) * d.r + k);+ }+ }+ for (size_t p = ((abs_pos + 1) / d.r) * d.r; p <= abs_pos; p++) {+ tokens.push_back(p);+ }+ for (size_t h = 0; h < d.Hq; h++) {+ const size_t kv = h / group;+ std::vector<double> logits(tokens.size());+ for (size_t n = 0; n < tokens.size(); n++) {+ const size_t row = (b * d.Hkv + kv) * S + (S - tc.key_len[b]) + tokens[n];+ double dot = 0.0;+ for (size_t j = 0; j < d.Dh; j++) {+ dot += static_cast<double>(query[((b * d.Hq + h) * L + l) * d.Dh + j]) * K[row * d.Dh + j];+ }+ logits[n] = dot * scale;+ }+ const double m = *std::max_element(logits.begin(), logits.end());+ double sum = 0.0;+ for (auto& x : logits) {+ x = std::exp(x - m);+ sum += x;+ }+ for (size_t j = 0; j < d.Dv; j++) {+ double acc = 0.0;+ for (size_t n = 0; n < tokens.size(); n++) {+ const size_t row = (b * d.Hkv + kv) * S + (S - tc.key_len[b]) + tokens[n];+ acc += logits[n] * V[row * d.Dv + j];+ }+ dst[((b * d.Hq + h) * L + l) * d.Dv + j] = static_cast<float>(acc / sum);+ }+ }+ }+ }+ }+ const auto e = compare(out, ref, 1.5e-2, 1.5e-2);+ const auto e_q = compare(out, ref_f16, 1e9, 1e9);+ double ref_mean = 0.0;+ for (float x : ref_f16) {+ ref_mean += std::fabs(x);+ }+ ref_mean /= static_cast<double>(ref_f16.size());+ std::cout << "QSA_KVQ_DENSE " << name << " vs_dequant max_abs=" << e.max_abs << " bad=" << e.bad << " | vs_f16 mean_abs=" << e_q.mean_abs+ << " rel_mean=" << e_q.mean_abs / ref_mean << std::endl;+ EXPECT_EQ(e.bad, 0u) << name;+ EXPECT_LT(e_q.mean_abs / ref_mean, tc.k.bits == 4 ? 0.5 : 0.03) << name;+}++TEST(sparse_sdpa_kvq, qwen_decode_left_padded) {+ if (!ocl_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ run_dense_case({qwen38(), {2051, 1500}, 1}, "qwen_decode_2x");+}++TEST(sparse_sdpa_kvq, qwen_prefill_left_padded) {+ if (!ocl_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ run_dense_case({qwen38(), {300, 211}, 150}, "qwen_prefill_2x");+}++TEST(sparse_sdpa_kvq, toy_scalar_kernel) {+ if (!ocl_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ run_dense_case({toy(), {90, 61}, 7}, "toy_prefill_2x");+ run_dense_case({toy(), {120}, 1}, "toy_decode");+}++// 4-bit and symmetric dense caches, read by the scalar and GQA-DPAS kernels.+struct dense_format_case {+ std::string name;+ dense_case tc;+};++class sparse_sdpa_kvq_formats : public ::testing::TestWithParam<dense_format_case> {};++TEST_P(sparse_sdpa_kvq_formats, matches_dequantized_reference) {+ if (!ocl_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ run_dense_case(GetParam().tc, GetParam().name.c_str());+}++std::vector<dense_format_case> dense_format_cases() {+ struct scenario {+ const char* name;+ dims d;+ std::vector<size_t> key_len;+ size_t q_len;+ };+ dims d128 = qwen38();+ d128.Dh = d128.Dv = 128;+ const std::vector<scenario> scenarios = {{"qwen_decode", qwen38(), {2051, 1500}, 1},+ {"qwen_prefill", qwen38(), {300, 211}, 150},+ {"d128_decode", d128, {500}, 1},+ {"toy_prefill", toy(), {90, 61}, 7},+ {"toy_decode", toy(), {120}, 1}};+ struct format {+ const char* name;+ KVQuant k, v;+ };+ const std::vector<format> formats = {{"Ktok_i8sym_Vtok_i8sym", token_quant(8, true), token_quant(8, true)},+ {"Ktok_u4_Vtok_u4", token_quant(4, false), token_quant(4, false)},+ {"Ktok_u4sym_Vtok_u4sym", token_quant(4, true), token_quant(4, true)}};+ std::vector<dense_format_case> cases;+ for (const auto& f : formats) {+ for (const auto& s : scenarios) {+ cases.push_back({std::string(s.name) + "_" + f.name, {s.d, s.key_len, s.q_len, f.k, f.v}});+ }+ }+ return cases;+}++INSTANTIATE_TEST_SUITE_P(smoke,+ sparse_sdpa_kvq_formats,+ ::testing::ValuesIn(dense_format_cases()),+ [](const ::testing::TestParamInfo<dense_format_case>& info) {+ return info.param.name;+ });++// ---------------------------------------------------------------------------+// Performance (DISABLED_): GPU time of the whole SparsePA call (write + attention stages) per KV cache format.+// ---------------------------------------------------------------------------++struct perf_case {+ std::string name;+ KVQuant k, v;+ size_t past, q_len;+ size_t page = 16;+};++class sparse_pa_kvq_perf : public ::testing::TestWithParam<perf_case> {};++TEST_P(sparse_pa_kvq_perf, qwen38) {+ if (!ocl_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }+ const auto& pc = GetParam();+ dims perf_dims = qwen38();+ perf_dims.page = pc.page;+ const auto c = make_case(perf_dims, pc.k, pc.v, {{pc.past, pc.q_len}}, 3);+ const auto& d = c.d;+ const KVQuant quants[2] = {pc.k, pc.v};+ const size_t D[2] = {d.Dh, d.Dv};+ std::vector<uint8_t> init[2];+ for (int which = 0; which < 2; which++) {+ const auto& hist = which == 0 ? c.key_hist[0] : c.value_hist[0];+ if (quants[which].enabled()) {+ quant_pages qp(quants[which], c.total_pages, d.Hkv, d.page, D[which]);+ cpu_write_range(qp, c, 0, hist, D[which], 0, pc.past);+ init[which] = qp.bytes;+ } else {+ std::vector<ov::float16> h(c.total_pages * d.Hkv * d.page * D[which], ov::float16(0.0f));+ for (size_t t = 0; t < pc.past; t++) {+ const size_t page = static_cast<size_t>(c.block_indices[c.page_first[0] + t / d.page]);+ for (size_t hd = 0; hd < d.Hkv; hd++) {+ for (size_t j = 0; j < D[which]; j++) {+ h[((page * d.Hkv + hd) * d.page + t % d.page) * D[which] + j] = ov::float16(hist[(t * d.Hkv + hd) * D[which] + j]);+ }+ }+ }+ init[which].resize(h.size() * 2);+ std::memcpy(init[which].data(), h.data(), init[which].size());+ }+ }+ run_options opt;+ opt.profile = true;+ opt.warmup = 20;+ opt.iterations = 50;+ run_gpu(c, init[0], init[1], &opt);+ const auto kl = kv_page_layout(pc.k, d.page, d.Dh);+ const auto vl = kv_page_layout(pc.v, d.page, d.Dv);+ const double cache_mb = static_cast<double>(c.total_pages * d.Hkv * (kl.page_bytes + vl.page_bytes)) / 1e6;+ std::cout << "QSA_KVQ_PERF " << std::left << std::setw(26) << pc.name << " mode=" << std::setw(7) << (pc.q_len == 1 ? "decode" : "prefill")+ << " ctx=" << std::setw(7) << (pc.past + pc.q_len) << " q=" << std::setw(5) << pc.q_len << std::right << std::fixed << std::setprecision(4)+ << " gpu_min_ms=" << std::setw(9) << opt.gpu_ms_min << " gpu_avg_ms=" << std::setw(9) << opt.gpu_ms_avg << std::setprecision(1)+ << " cache_MB=" << std::setw(8) << cache_mb << " kernels=" << opt.kernels << " stages_ms=[";+ for (size_t i = 0; i < opt.stage_ms.size(); i++) {+ std::cout << (i ? "," : "") << std::setprecision(4) << opt.stage_ms[i];+ }+ std::cout << "]" << std::endl;+}++std::vector<perf_case> perf_cases() {+ struct fmt {+ const char* name;+ KVQuant k, v;+ };+ const std::vector<fmt> formats = {+ {"f16", {}, {}},+ {"Ktok_i8_Vtok_i8", token_quant(8, false), token_quant(8, false)},+ {"Ktok_u4_Vtok_u4", token_quant(4, false), token_quant(4, false)},+ {"Kch16_i8_Vtok_i8", channel_quant(8, false, 16), token_quant(8, false)},+ {"Kch16_u4_Vtok_u4", channel_quant(4, false, 16), token_quant(4, false)},+ {"Kch32_i8_Vtok_i8_page32", channel_quant(8, false, 32), token_quant(8, false)},+ {"Ktok_i8sym_Vtok_i8sym", token_quant(8, true), token_quant(8, true)},+ {"Kch16_u4sym_Vtok_u4sym", channel_quant(4, true, 16), token_quant(4, true)},+ };+ std::vector<perf_case> out;+ for (const auto& f : formats) {+ const size_t page = std::string(f.name).find("page32") != std::string::npos ? 32 : 16;+ for (size_t ctx : {size_t{4096}, size_t{16384}, size_t{32768}, size_t{65536}, size_t{131072}}) {+ out.push_back({f.name, f.k, f.v, ctx - 1, 1, page});+ }+ out.push_back({f.name, f.k, f.v, 0, 4096, page});+ out.push_back({f.name, f.k, f.v, 0, 16384, page});+ }+ return out;+}++INSTANTIATE_TEST_SUITE_P(DISABLED_sparse_pa_kvq_perf,+ sparse_pa_kvq_perf,+ ::testing::ValuesIn(perf_cases()),+ [](const ::testing::TestParamInfo<perf_case>& info) {+ return info.param.name + "_ctx" + std::to_string(info.param.past + info.param.q_len) + "_q" + std::to_string(info.param.q_len);+ });++} // namespace